1
0

ServerUtils.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Reflection;
  30. using System.Xml;
  31. using System.Xml.Serialization;
  32. using System.Text;
  33. using System.Collections.Generic;
  34. using log4net;
  35. using Nini.Config;
  36. using OpenSim.Framework;
  37. using OpenMetaverse;
  38. using Mono.Addins;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Framework.Servers;
  41. [assembly:AddinRoot("Robust", OpenSim.VersionInfo.VersionNumber)]
  42. namespace OpenSim.Server.Base
  43. {
  44. [TypeExtensionPoint(Path="/Robust/Connector", Name="RobustConnector")]
  45. public interface IRobustConnector
  46. {
  47. string ConfigName
  48. {
  49. get;
  50. }
  51. bool Enabled
  52. {
  53. get;
  54. }
  55. string PluginPath
  56. {
  57. get;
  58. set;
  59. }
  60. uint Configure(IConfigSource config);
  61. void Initialize(IHttpServer server);
  62. void Unload();
  63. }
  64. public class PluginLoader
  65. {
  66. static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  67. public AddinRegistry Registry
  68. {
  69. get;
  70. private set;
  71. }
  72. public IConfigSource Config
  73. {
  74. get;
  75. private set;
  76. }
  77. public PluginLoader(IConfigSource config, string registryPath)
  78. {
  79. Config = config;
  80. Registry = new AddinRegistry(registryPath, ".");
  81. //suppress_console_output_(true);
  82. AddinManager.Initialize(registryPath);
  83. //suppress_console_output_(false);
  84. AddinManager.Registry.Update();
  85. CommandManager commandmanager = new CommandManager(Registry);
  86. AddinManager.AddExtensionNodeHandler("/Robust/Connector", OnExtensionChanged);
  87. }
  88. private static TextWriter prev_console_;
  89. // Temporarily masking the errors reported on start
  90. // This is caused by a non-managed dll in the ./bin dir
  91. // when the registry is initialized. The dll belongs to
  92. // libomv, which has a hard-coded path to "." for pinvoke
  93. // to load the openjpeg dll
  94. //
  95. // Will look for a way to fix, but for now this keeps the
  96. // confusion to a minimum. this was copied from our region
  97. // plugin loader, we have been doing this in there for a long time.
  98. //
  99. public void suppress_console_output_(bool save)
  100. {
  101. if (save)
  102. {
  103. prev_console_ = System.Console.Out;
  104. System.Console.SetOut(new StreamWriter(Stream.Null));
  105. }
  106. else
  107. {
  108. if (prev_console_ != null)
  109. System.Console.SetOut(prev_console_);
  110. }
  111. }
  112. private void OnExtensionChanged(object s, ExtensionNodeEventArgs args)
  113. {
  114. IRobustConnector connector = (IRobustConnector)args.ExtensionObject;
  115. Addin a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
  116. if(a == null)
  117. {
  118. Registry.Rebuild(null);
  119. a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
  120. }
  121. switch(args.Change)
  122. {
  123. case ExtensionChange.Add:
  124. if (a.AddinFile.Contains(Registry.DefaultAddinsFolder))
  125. {
  126. m_log.InfoFormat("[SERVER UTILS]: Adding {0} from registry", a.Name);
  127. connector.PluginPath = System.IO.Path.Combine(Registry.DefaultAddinsFolder,a.Name.Replace(',', '.')); }
  128. else
  129. {
  130. m_log.InfoFormat("[SERVER UTILS]: Adding {0} from ./bin", a.Name);
  131. connector.PluginPath = a.AddinFile;
  132. }
  133. LoadPlugin(connector);
  134. break;
  135. case ExtensionChange.Remove:
  136. m_log.InfoFormat("[SERVER UTILS]: Removing {0}", a.Name);
  137. UnloadPlugin(connector);
  138. break;
  139. }
  140. }
  141. private void LoadPlugin(IRobustConnector connector)
  142. {
  143. IHttpServer server = null;
  144. uint port = connector.Configure(Config);
  145. if(connector.Enabled)
  146. {
  147. server = GetServer(connector, port);
  148. connector.Initialize(server);
  149. }
  150. else
  151. {
  152. m_log.InfoFormat("[SERVER UTILS]: {0} Disabled.", connector.ConfigName);
  153. }
  154. }
  155. private void UnloadPlugin(IRobustConnector connector)
  156. {
  157. m_log.InfoFormat("[SERVER UTILS]: Unloading {0}", connector.ConfigName);
  158. connector.Unload();
  159. }
  160. private IHttpServer GetServer(IRobustConnector connector, uint port)
  161. {
  162. IHttpServer server;
  163. if(port != 0)
  164. server = MainServer.GetHttpServer(port);
  165. else
  166. server = MainServer.Instance;
  167. return server;
  168. }
  169. }
  170. public static class ServerUtils
  171. {
  172. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  173. public static byte[] SerializeResult(XmlSerializer xs, object data)
  174. {
  175. using (MemoryStream ms = new MemoryStream())
  176. using (XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8))
  177. {
  178. xw.Formatting = Formatting.Indented;
  179. xs.Serialize(xw, data);
  180. xw.Flush();
  181. ms.Seek(0, SeekOrigin.Begin);
  182. byte[] ret = ms.GetBuffer();
  183. Array.Resize(ref ret, (int)ms.Length);
  184. return ret;
  185. }
  186. }
  187. /// <summary>
  188. /// Load a plugin from a dll with the given class or interface
  189. /// </summary>
  190. /// <param name="dllName"></param>
  191. /// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
  192. /// <returns></returns>
  193. public static T LoadPlugin<T> (string dllName, Object[] args) where T:class
  194. {
  195. // This is good to debug configuration problems
  196. //if (dllName == string.Empty)
  197. // Util.PrintCallStack();
  198. string className = String.Empty;
  199. // The path for a dynamic plugin will contain ":" on Windows
  200. string[] parts = dllName.Split (new char[] {':'});
  201. if (parts [0].Length > 1)
  202. {
  203. dllName = parts [0];
  204. if (parts.Length > 1)
  205. className = parts[1];
  206. }
  207. else
  208. {
  209. // This is Windows - we must replace the ":" in the path
  210. dllName = String.Format ("{0}:{1}", parts [0], parts [1]);
  211. if (parts.Length > 2)
  212. className = parts[2];
  213. }
  214. return LoadPlugin<T>(dllName, className, args);
  215. }
  216. /// <summary>
  217. /// Load a plugin from a dll with the given class or interface
  218. /// </summary>
  219. /// <param name="dllName"></param>
  220. /// <param name="className"></param>
  221. /// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
  222. /// <returns></returns>
  223. public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
  224. {
  225. string interfaceName = typeof(T).ToString();
  226. try
  227. {
  228. Assembly pluginAssembly = Assembly.LoadFrom(dllName);
  229. foreach (Type pluginType in pluginAssembly.GetTypes())
  230. {
  231. if (pluginType.IsPublic)
  232. {
  233. if (className != String.Empty
  234. && pluginType.ToString() != pluginType.Namespace + "." + className)
  235. continue;
  236. Type typeInterface = pluginType.GetInterface(interfaceName);
  237. if (typeInterface != null)
  238. {
  239. T plug = null;
  240. try
  241. {
  242. plug = (T)Activator.CreateInstance(pluginType,
  243. args);
  244. }
  245. catch (Exception e)
  246. {
  247. if (!(e is System.MissingMethodException))
  248. {
  249. m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin {0} from {1}. Exception: {2}",
  250. interfaceName,
  251. dllName,
  252. e.InnerException == null ? e.Message : e.InnerException.Message),
  253. e);
  254. }
  255. m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0}: {1} args.Length {2}", dllName, e.Message, args.Length);
  256. return null;
  257. }
  258. return plug;
  259. }
  260. }
  261. }
  262. return null;
  263. }
  264. catch (ReflectionTypeLoadException rtle)
  265. {
  266. m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}:\n{1}", dllName,
  267. String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
  268. rtle);
  269. return null;
  270. }
  271. catch (Exception e)
  272. {
  273. m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}", dllName), e);
  274. return null;
  275. }
  276. }
  277. public static Dictionary<string, object> ParseQueryString(string query)
  278. {
  279. Dictionary<string, object> result = new Dictionary<string, object>();
  280. string[] terms = query.Split(new char[] {'&'});
  281. if (terms.Length == 0)
  282. return result;
  283. foreach (string t in terms)
  284. {
  285. string[] elems = t.Split(new char[] {'='});
  286. if (elems.Length == 0)
  287. continue;
  288. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  289. string value = String.Empty;
  290. if (elems.Length > 1)
  291. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  292. if (name.EndsWith("[]"))
  293. {
  294. string cleanName = name.Substring(0, name.Length - 2);
  295. if (result.ContainsKey(cleanName))
  296. {
  297. if (!(result[cleanName] is List<string>))
  298. continue;
  299. List<string> l = (List<string>)result[cleanName];
  300. l.Add(value);
  301. }
  302. else
  303. {
  304. List<string> newList = new List<string>();
  305. newList.Add(value);
  306. result[cleanName] = newList;
  307. }
  308. }
  309. else
  310. {
  311. if (!result.ContainsKey(name))
  312. result[name] = value;
  313. }
  314. }
  315. return result;
  316. }
  317. public static string BuildQueryString(Dictionary<string, object> data)
  318. {
  319. string qstring = String.Empty;
  320. string part;
  321. foreach (KeyValuePair<string, object> kvp in data)
  322. {
  323. if (kvp.Value is List<string>)
  324. {
  325. List<string> l = (List<String>)kvp.Value;
  326. foreach (string s in l)
  327. {
  328. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  329. "[]=" + System.Web.HttpUtility.UrlEncode(s);
  330. if (qstring != String.Empty)
  331. qstring += "&";
  332. qstring += part;
  333. }
  334. }
  335. else
  336. {
  337. if (kvp.Value.ToString() != String.Empty)
  338. {
  339. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  340. "=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
  341. }
  342. else
  343. {
  344. part = System.Web.HttpUtility.UrlEncode(kvp.Key);
  345. }
  346. if (qstring != String.Empty)
  347. qstring += "&";
  348. qstring += part;
  349. }
  350. }
  351. return qstring;
  352. }
  353. public static string BuildXmlResponse(Dictionary<string, object> data)
  354. {
  355. XmlDocument doc = new XmlDocument();
  356. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  357. "", "");
  358. doc.AppendChild(xmlnode);
  359. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  360. "");
  361. doc.AppendChild(rootElement);
  362. BuildXmlData(rootElement, data);
  363. return doc.InnerXml;
  364. }
  365. private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
  366. {
  367. foreach (KeyValuePair<string, object> kvp in data)
  368. {
  369. if (kvp.Value == null)
  370. continue;
  371. XmlElement elem = parent.OwnerDocument.CreateElement("",
  372. XmlConvert.EncodeLocalName(kvp.Key), "");
  373. if (kvp.Value is Dictionary<string, object>)
  374. {
  375. XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
  376. "type", "");
  377. type.Value = "List";
  378. elem.Attributes.Append(type);
  379. BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
  380. }
  381. else
  382. {
  383. elem.AppendChild(parent.OwnerDocument.CreateTextNode(
  384. kvp.Value.ToString()));
  385. }
  386. parent.AppendChild(elem);
  387. }
  388. }
  389. public static Dictionary<string, object> ParseXmlResponse(string data)
  390. {
  391. //m_log.DebugFormat("[XXX]: received xml string: {0}", data);
  392. Dictionary<string, object> ret = new Dictionary<string, object>();
  393. XmlDocument doc = new XmlDocument();
  394. doc.LoadXml(data);
  395. XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
  396. if (rootL.Count != 1)
  397. return ret;
  398. XmlNode rootNode = rootL[0];
  399. ret = ParseElement(rootNode);
  400. return ret;
  401. }
  402. private static Dictionary<string, object> ParseElement(XmlNode element)
  403. {
  404. Dictionary<string, object> ret = new Dictionary<string, object>();
  405. XmlNodeList partL = element.ChildNodes;
  406. foreach (XmlNode part in partL)
  407. {
  408. XmlNode type = part.Attributes.GetNamedItem("type");
  409. if (type == null || type.Value != "List")
  410. {
  411. ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
  412. }
  413. else
  414. {
  415. ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
  416. }
  417. }
  418. return ret;
  419. }
  420. public static IConfig GetConfig(string configFile, string configName)
  421. {
  422. IConfig config;
  423. if (File.Exists(configFile))
  424. {
  425. IConfigSource configsource = new IniConfigSource(configFile);
  426. config = configsource.Configs[configName];
  427. }
  428. else
  429. config = null;
  430. return config;
  431. }
  432. public static IConfigSource LoadInitialConfig(string url)
  433. {
  434. IConfigSource source = new XmlConfigSource();
  435. m_log.InfoFormat("[SERVER UTILS]: {0} is a http:// URI, fetching ...", url);
  436. // The ini file path is a http URI
  437. // Try to read it
  438. try
  439. {
  440. XmlReader r = XmlReader.Create(url);
  441. IConfigSource cs = new XmlConfigSource(r);
  442. source.Merge(cs);
  443. }
  444. catch (Exception e)
  445. {
  446. m_log.FatalFormat("[SERVER UTILS]: Exception reading config from URI {0}\n" + e.ToString(), url);
  447. Environment.Exit(1);
  448. }
  449. return source;
  450. }
  451. }
  452. }