ServerUtils.cs 19 KB

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