ServerUtils.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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", "0.1")]
  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. MemoryStream ms = new MemoryStream();
  176. XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
  177. xw.Formatting = Formatting.Indented;
  178. xs.Serialize(xw, data);
  179. xw.Flush();
  180. ms.Seek(0, SeekOrigin.Begin);
  181. byte[] ret = ms.GetBuffer();
  182. Array.Resize(ref ret, (int)ms.Length);
  183. return ret;
  184. }
  185. /// <summary>
  186. /// Load a plugin from a dll with the given class or interface
  187. /// </summary>
  188. /// <param name="dllName"></param>
  189. /// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
  190. /// <returns></returns>
  191. public static T LoadPlugin<T> (string dllName, Object[] args) where T:class
  192. {
  193. // This is good to debug configuration problems
  194. //if (dllName == string.Empty)
  195. // Util.PrintCallStack();
  196. string className = String.Empty;
  197. // The path for a dynamic plugin will contain ":" on Windows
  198. string[] parts = dllName.Split (new char[] {':'});
  199. if (parts [0].Length > 1)
  200. {
  201. dllName = parts [0];
  202. if (parts.Length > 1)
  203. className = parts[1];
  204. }
  205. else
  206. {
  207. // This is Windows - we must replace the ":" in the path
  208. dllName = String.Format ("{0}:{1}", parts [0], parts [1]);
  209. if (parts.Length > 2)
  210. className = parts[2];
  211. }
  212. return LoadPlugin<T>(dllName, className, args);
  213. }
  214. /// <summary>
  215. /// Load a plugin from a dll with the given class or interface
  216. /// </summary>
  217. /// <param name="dllName"></param>
  218. /// <param name="className"></param>
  219. /// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
  220. /// <returns></returns>
  221. public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
  222. {
  223. string interfaceName = typeof(T).ToString();
  224. try
  225. {
  226. Assembly pluginAssembly = Assembly.LoadFrom(dllName);
  227. foreach (Type pluginType in pluginAssembly.GetTypes())
  228. {
  229. if (pluginType.IsPublic)
  230. {
  231. if (className != String.Empty
  232. && pluginType.ToString() != pluginType.Namespace + "." + className)
  233. continue;
  234. Type typeInterface = pluginType.GetInterface(interfaceName, true);
  235. if (typeInterface != null)
  236. {
  237. T plug = null;
  238. try
  239. {
  240. plug = (T)Activator.CreateInstance(pluginType,
  241. args);
  242. }
  243. catch (Exception e)
  244. {
  245. if (!(e is System.MissingMethodException))
  246. {
  247. m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0} from {1}. Exception: {2}, {3}",
  248. interfaceName,
  249. dllName,
  250. e.InnerException == null ? e.Message : e.InnerException.Message,
  251. e.StackTrace);
  252. }
  253. m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0}: {1} args.Length {2}", dllName, e.Message, args.Length);
  254. return null;
  255. }
  256. return plug;
  257. }
  258. }
  259. }
  260. return null;
  261. }
  262. catch (ReflectionTypeLoadException rtle)
  263. {
  264. m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}:\n{1}", dllName,
  265. String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
  266. rtle);
  267. return null;
  268. }
  269. catch (Exception e)
  270. {
  271. m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}", dllName), e);
  272. return null;
  273. }
  274. }
  275. public static Dictionary<string, object> ParseQueryString(string query)
  276. {
  277. Dictionary<string, object> result = new Dictionary<string, object>();
  278. string[] terms = query.Split(new char[] {'&'});
  279. if (terms.Length == 0)
  280. return result;
  281. foreach (string t in terms)
  282. {
  283. string[] elems = t.Split(new char[] {'='});
  284. if (elems.Length == 0)
  285. continue;
  286. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  287. string value = String.Empty;
  288. if (elems.Length > 1)
  289. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  290. if (name.EndsWith("[]"))
  291. {
  292. string cleanName = name.Substring(0, name.Length - 2);
  293. if (result.ContainsKey(cleanName))
  294. {
  295. if (!(result[cleanName] is List<string>))
  296. continue;
  297. List<string> l = (List<string>)result[cleanName];
  298. l.Add(value);
  299. }
  300. else
  301. {
  302. List<string> newList = new List<string>();
  303. newList.Add(value);
  304. result[cleanName] = newList;
  305. }
  306. }
  307. else
  308. {
  309. if (!result.ContainsKey(name))
  310. result[name] = value;
  311. }
  312. }
  313. return result;
  314. }
  315. public static string BuildQueryString(Dictionary<string, object> data)
  316. {
  317. string qstring = String.Empty;
  318. string part;
  319. foreach (KeyValuePair<string, object> kvp in data)
  320. {
  321. if (kvp.Value is List<string>)
  322. {
  323. List<string> l = (List<String>)kvp.Value;
  324. foreach (string s in l)
  325. {
  326. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  327. "[]=" + System.Web.HttpUtility.UrlEncode(s);
  328. if (qstring != String.Empty)
  329. qstring += "&";
  330. qstring += part;
  331. }
  332. }
  333. else
  334. {
  335. if (kvp.Value.ToString() != String.Empty)
  336. {
  337. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  338. "=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
  339. }
  340. else
  341. {
  342. part = System.Web.HttpUtility.UrlEncode(kvp.Key);
  343. }
  344. if (qstring != String.Empty)
  345. qstring += "&";
  346. qstring += part;
  347. }
  348. }
  349. return qstring;
  350. }
  351. public static string BuildXmlResponse(Dictionary<string, object> data)
  352. {
  353. XmlDocument doc = new XmlDocument();
  354. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  355. "", "");
  356. doc.AppendChild(xmlnode);
  357. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  358. "");
  359. doc.AppendChild(rootElement);
  360. BuildXmlData(rootElement, data);
  361. return doc.InnerXml;
  362. }
  363. private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
  364. {
  365. foreach (KeyValuePair<string, object> kvp in data)
  366. {
  367. if (kvp.Value == null)
  368. continue;
  369. XmlElement elem = parent.OwnerDocument.CreateElement("",
  370. XmlConvert.EncodeLocalName(kvp.Key), "");
  371. if (kvp.Value is Dictionary<string, object>)
  372. {
  373. XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
  374. "type", "");
  375. type.Value = "List";
  376. elem.Attributes.Append(type);
  377. BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
  378. }
  379. else
  380. {
  381. elem.AppendChild(parent.OwnerDocument.CreateTextNode(
  382. kvp.Value.ToString()));
  383. }
  384. parent.AppendChild(elem);
  385. }
  386. }
  387. public static Dictionary<string, object> ParseXmlResponse(string data)
  388. {
  389. //m_log.DebugFormat("[XXX]: received xml string: {0}", data);
  390. Dictionary<string, object> ret = new Dictionary<string, object>();
  391. XmlDocument doc = new XmlDocument();
  392. doc.LoadXml(data);
  393. XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
  394. if (rootL.Count != 1)
  395. return ret;
  396. XmlNode rootNode = rootL[0];
  397. ret = ParseElement(rootNode);
  398. return ret;
  399. }
  400. private static Dictionary<string, object> ParseElement(XmlNode element)
  401. {
  402. Dictionary<string, object> ret = new Dictionary<string, object>();
  403. XmlNodeList partL = element.ChildNodes;
  404. foreach (XmlNode part in partL)
  405. {
  406. XmlNode type = part.Attributes.GetNamedItem("type");
  407. if (type == null || type.Value != "List")
  408. {
  409. ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
  410. }
  411. else
  412. {
  413. ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
  414. }
  415. }
  416. return ret;
  417. }
  418. public static IConfig GetConfig(string configFile, string configName)
  419. {
  420. IConfig config;
  421. if (File.Exists(configFile))
  422. {
  423. IConfigSource configsource = new IniConfigSource(configFile);
  424. config = configsource.Configs[configName];
  425. }
  426. else
  427. config = null;
  428. return config;
  429. }
  430. public static IConfigSource LoadInitialConfig(string url)
  431. {
  432. IConfigSource source = new XmlConfigSource();
  433. m_log.InfoFormat("[SERVER UTILS]: {0} is a http:// URI, fetching ...", url);
  434. // The ini file path is a http URI
  435. // Try to read it
  436. try
  437. {
  438. XmlReader r = XmlReader.Create(url);
  439. IConfigSource cs = new XmlConfigSource(r);
  440. source.Merge(cs);
  441. }
  442. catch (Exception e)
  443. {
  444. m_log.FatalFormat("[SERVER UTILS]: Exception reading config from URI {0}\n" + e.ToString(), url);
  445. Environment.Exit(1);
  446. }
  447. return source;
  448. }
  449. }
  450. }