ServerUtils.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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]: 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]: 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]: 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]: {0} Disabled.", connector.ConfigName);
  153. }
  154. }
  155. private void UnloadPlugin(IRobustConnector connector)
  156. {
  157. m_log.InfoFormat("[Server]: 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("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. return null;
  254. }
  255. return plug;
  256. }
  257. }
  258. }
  259. return null;
  260. }
  261. catch (ReflectionTypeLoadException rtle)
  262. {
  263. m_log.Error(string.Format("Error loading plugin from {0}:\n{1}", dllName,
  264. String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
  265. rtle);
  266. return null;
  267. }
  268. catch (Exception e)
  269. {
  270. m_log.Error(string.Format("Error loading plugin from {0}", dllName), e);
  271. return null;
  272. }
  273. }
  274. public static Dictionary<string, object> ParseQueryString(string query)
  275. {
  276. Dictionary<string, object> result = new Dictionary<string, object>();
  277. string[] terms = query.Split(new char[] {'&'});
  278. if (terms.Length == 0)
  279. return result;
  280. foreach (string t in terms)
  281. {
  282. string[] elems = t.Split(new char[] {'='});
  283. if (elems.Length == 0)
  284. continue;
  285. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  286. string value = String.Empty;
  287. if (elems.Length > 1)
  288. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  289. if (name.EndsWith("[]"))
  290. {
  291. string cleanName = name.Substring(0, name.Length - 2);
  292. if (result.ContainsKey(cleanName))
  293. {
  294. if (!(result[cleanName] is List<string>))
  295. continue;
  296. List<string> l = (List<string>)result[cleanName];
  297. l.Add(value);
  298. }
  299. else
  300. {
  301. List<string> newList = new List<string>();
  302. newList.Add(value);
  303. result[cleanName] = newList;
  304. }
  305. }
  306. else
  307. {
  308. if (!result.ContainsKey(name))
  309. result[name] = value;
  310. }
  311. }
  312. return result;
  313. }
  314. public static string BuildQueryString(Dictionary<string, object> data)
  315. {
  316. string qstring = String.Empty;
  317. string part;
  318. foreach (KeyValuePair<string, object> kvp in data)
  319. {
  320. if (kvp.Value is List<string>)
  321. {
  322. List<string> l = (List<String>)kvp.Value;
  323. foreach (string s in l)
  324. {
  325. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  326. "[]=" + System.Web.HttpUtility.UrlEncode(s);
  327. if (qstring != String.Empty)
  328. qstring += "&";
  329. qstring += part;
  330. }
  331. }
  332. else
  333. {
  334. if (kvp.Value.ToString() != String.Empty)
  335. {
  336. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  337. "=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
  338. }
  339. else
  340. {
  341. part = System.Web.HttpUtility.UrlEncode(kvp.Key);
  342. }
  343. if (qstring != String.Empty)
  344. qstring += "&";
  345. qstring += part;
  346. }
  347. }
  348. return qstring;
  349. }
  350. public static string BuildXmlResponse(Dictionary<string, object> data)
  351. {
  352. XmlDocument doc = new XmlDocument();
  353. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  354. "", "");
  355. doc.AppendChild(xmlnode);
  356. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  357. "");
  358. doc.AppendChild(rootElement);
  359. BuildXmlData(rootElement, data);
  360. return doc.InnerXml;
  361. }
  362. private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
  363. {
  364. foreach (KeyValuePair<string, object> kvp in data)
  365. {
  366. if (kvp.Value == null)
  367. continue;
  368. XmlElement elem = parent.OwnerDocument.CreateElement("",
  369. XmlConvert.EncodeLocalName(kvp.Key), "");
  370. if (kvp.Value is Dictionary<string, object>)
  371. {
  372. XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
  373. "type", "");
  374. type.Value = "List";
  375. elem.Attributes.Append(type);
  376. BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
  377. }
  378. else
  379. {
  380. elem.AppendChild(parent.OwnerDocument.CreateTextNode(
  381. kvp.Value.ToString()));
  382. }
  383. parent.AppendChild(elem);
  384. }
  385. }
  386. public static Dictionary<string, object> ParseXmlResponse(string data)
  387. {
  388. //m_log.DebugFormat("[XXX]: received xml string: {0}", data);
  389. Dictionary<string, object> ret = new Dictionary<string, object>();
  390. XmlDocument doc = new XmlDocument();
  391. doc.LoadXml(data);
  392. XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
  393. if (rootL.Count != 1)
  394. return ret;
  395. XmlNode rootNode = rootL[0];
  396. ret = ParseElement(rootNode);
  397. return ret;
  398. }
  399. private static Dictionary<string, object> ParseElement(XmlNode element)
  400. {
  401. Dictionary<string, object> ret = new Dictionary<string, object>();
  402. XmlNodeList partL = element.ChildNodes;
  403. foreach (XmlNode part in partL)
  404. {
  405. XmlNode type = part.Attributes.GetNamedItem("type");
  406. if (type == null || type.Value != "List")
  407. {
  408. ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
  409. }
  410. else
  411. {
  412. ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
  413. }
  414. }
  415. return ret;
  416. }
  417. public static IConfig GetConfig(string configFile, string configName)
  418. {
  419. IConfig config;
  420. if (File.Exists(configFile))
  421. {
  422. IConfigSource configsource = new IniConfigSource(configFile);
  423. config = configsource.Configs[configName];
  424. }
  425. else
  426. config = null;
  427. return config;
  428. }
  429. public static IConfigSource LoadInitialConfig(string url)
  430. {
  431. IConfigSource source = new XmlConfigSource();
  432. m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", url);
  433. // The ini file path is a http URI
  434. // Try to read it
  435. try
  436. {
  437. XmlReader r = XmlReader.Create(url);
  438. IConfigSource cs = new XmlConfigSource(r);
  439. source.Merge(cs);
  440. }
  441. catch (Exception e)
  442. {
  443. m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), url);
  444. Environment.Exit(1);
  445. }
  446. return source;
  447. }
  448. }
  449. }