RestPlugin.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 OpenSim 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.Threading;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.IO;
  32. using System.Net;
  33. using System.Reflection;
  34. using System.Timers;
  35. using System.Xml;
  36. using libsecondlife;
  37. using Mono.Addins;
  38. using Nwc.XmlRpc;
  39. using Nini.Config;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Console;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Framework.Communications;
  44. using OpenSim.Region.Environment.Scenes;
  45. // [assembly : Addin]
  46. // [assembly : AddinDependency("OpenSim", "0.5")]
  47. namespace OpenSim.ApplicationPlugins.Rest
  48. {
  49. // [Extension("/OpenSim/Startup")]
  50. public abstract class RestPlugin : IApplicationPlugin
  51. {
  52. #region properties
  53. protected static readonly log4net.ILog m_log =
  54. log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  55. private IConfig _config; // Configuration source: Rest Plugins
  56. private IConfig _pluginConfig; // Configuration source: Plugin specific
  57. private OpenSimBase _app; // The 'server'
  58. private BaseHttpServer _httpd; // The server's RPC interface
  59. private string _prefix; // URL prefix below
  60. // which all REST URLs
  61. // are living
  62. private StringWriter _sw = null;
  63. private RestXmlWriter _xw = null;
  64. private string _godkey;
  65. private int _reqk;
  66. [ThreadStaticAttribute]
  67. private static string _threadRequestID = String.Empty;
  68. /// <summary>
  69. /// Return an ever increasing request ID for logging
  70. /// </summary>
  71. protected string RequestID
  72. {
  73. get { return _reqk++.ToString(); }
  74. set { _reqk = Convert.ToInt32(value); }
  75. }
  76. /// <summary>
  77. /// Thread-constant message IDs for logging.
  78. /// </summary>
  79. protected string MsgID
  80. {
  81. get { return String.Format("[REST-{0}] #{1}", Name, _threadRequestID); }
  82. set { _threadRequestID = value; }
  83. }
  84. /// <summary>
  85. /// Returns true if Rest Plugins are enabled.
  86. /// </summary>
  87. public bool PluginsAreEnabled
  88. {
  89. get { return null != _config; }
  90. }
  91. /// <summary>
  92. /// Returns true if specific Rest Plugin is enabled.
  93. /// </summary>
  94. public bool IsEnabled
  95. {
  96. get
  97. {
  98. return (null != _pluginConfig) && _pluginConfig.GetBoolean("enabled", false);
  99. }
  100. }
  101. /// <summary>
  102. /// OpenSimMain application
  103. /// </summary>
  104. public OpenSimBase App
  105. {
  106. get { return _app; }
  107. }
  108. /// <summary>
  109. /// RPC server
  110. /// </summary>
  111. public BaseHttpServer HttpServer
  112. {
  113. get { return _httpd; }
  114. }
  115. /// <summary>
  116. /// URL prefix to use for all REST handlers
  117. /// </summary>
  118. public string Prefix
  119. {
  120. get { return _prefix; }
  121. }
  122. /// <summary>
  123. /// Access to GOD password string
  124. /// </summary>
  125. protected string GodKey
  126. {
  127. get { return _godkey; }
  128. }
  129. /// <summary>
  130. /// Configuration of the plugin
  131. /// </summary>
  132. public IConfig Config
  133. {
  134. get { return _pluginConfig; }
  135. }
  136. /// <summary>
  137. /// Name of the plugin
  138. /// </summary>
  139. public abstract string Name { get; }
  140. /// <summary>
  141. /// Return the config section name
  142. /// </summary>
  143. public abstract string ConfigName { get; }
  144. public XmlTextWriter XmlWriter
  145. {
  146. get {
  147. if (null == _xw)
  148. {
  149. _sw = new StringWriter();
  150. _xw = new RestXmlWriter(_sw);
  151. _xw.Formatting = Formatting.Indented;
  152. }
  153. return _xw; }
  154. }
  155. public string XmlWriterResult
  156. {
  157. get
  158. {
  159. _xw.Flush();
  160. _xw.Close();
  161. _xw = null;
  162. return _sw.ToString();
  163. }
  164. }
  165. #endregion properties
  166. #region methods
  167. // TODO: required by IPlugin, but likely not at all right
  168. string m_version = "0.0";
  169. public string Version { get { return m_version; } }
  170. public void Initialise()
  171. {
  172. m_log.Info("[RESTPLUGIN]: " + Name + " cannot be default-initialized!");
  173. throw new PluginNotInitialisedException (Name);
  174. }
  175. /// <summary>
  176. /// This method is called by OpenSimMain immediately after loading the
  177. /// plugin and after basic server setup, but before running any server commands.
  178. /// </summary>
  179. /// <remarks>
  180. /// Note that entries MUST be added to the active configuration files before
  181. /// the plugin can be enabled.
  182. /// </remarks>
  183. public virtual void Initialise(OpenSimBase openSim)
  184. {
  185. RequestID = "0";
  186. MsgID = RequestID;
  187. try
  188. {
  189. if ((_config = openSim.ConfigSource.Source.Configs["RestPlugins"]) == null)
  190. {
  191. m_log.WarnFormat("{0} Rest Plugins not configured", MsgID);
  192. return;
  193. }
  194. if (!_config.GetBoolean("enabled", false))
  195. {
  196. m_log.WarnFormat("{0} Rest Plugins are disabled", MsgID);
  197. return;
  198. }
  199. _app = openSim;
  200. _httpd = openSim.HttpServer;
  201. // Retrieve GOD key value, if any.
  202. _godkey = _config.GetString("god_key", String.Empty);
  203. // Retrive prefix if any.
  204. _prefix = _config.GetString("prefix", "/admin");
  205. // Get plugin specific config
  206. _pluginConfig = openSim.ConfigSource.Source.Configs[ConfigName];
  207. m_log.InfoFormat("{0} Rest Plugins Enabled", MsgID);
  208. }
  209. catch (Exception e)
  210. {
  211. // we can safely ignore this, as it just means that
  212. // the key lookup in Configs failed, which signals to
  213. // us that noone is interested in our services...they
  214. // don't know what they are missing out on...
  215. // NOTE: Under the present OpenSim implementation it is
  216. // not possible for the openSim pointer to be null. However
  217. // were the implementation to be changed, this could
  218. // result in a silent initialization failure. Harmless
  219. // except for lack of function and lack of any
  220. // diagnostic indication as to why. The same is true if
  221. // the HTTP server reference is bad.
  222. // We should at least issue a message...
  223. m_log.WarnFormat("{0} Initialization failed: {1}", MsgID, e.Message);
  224. m_log.DebugFormat("{0} Initialization failed: {1}", MsgID, e.ToString());
  225. }
  226. }
  227. private List<RestStreamHandler> _handlers = new List<RestStreamHandler>();
  228. private Dictionary<string, IHttpAgentHandler> _agents = new Dictionary<string, IHttpAgentHandler>();
  229. /// <summary>
  230. /// Add a REST stream handler to the underlying HTTP server.
  231. /// </summary>
  232. /// <param name="httpMethod">GET/PUT/POST/DELETE or
  233. /// similar</param>
  234. /// <param name="path">URL prefix</param>
  235. /// <param name="method">RestMethod handler doing the actual work</param>
  236. public virtual void AddRestStreamHandler(string httpMethod, string path, RestMethod method)
  237. {
  238. if (!IsEnabled) return;
  239. if (!path.StartsWith(_prefix))
  240. {
  241. path = String.Format("{0}{1}", _prefix, path);
  242. }
  243. RestStreamHandler h = new RestStreamHandler(httpMethod, path, method);
  244. _httpd.AddStreamHandler(h);
  245. _handlers.Add(h);
  246. m_log.DebugFormat("{0} Added REST handler {1} {2}", MsgID, httpMethod, path);
  247. }
  248. /// <summary>
  249. /// Add a powerful Agent handler to the underlying HTTP
  250. /// server.
  251. /// </summary>
  252. /// <param name="agentName">name of agent handler</param>
  253. /// <param name="handler">agent handler method</param>
  254. /// <returns>false when the plugin is disabled or the agent
  255. /// handler could not be added. Any generated exceptions are
  256. /// allowed to drop through to the caller, i.e. ArgumentException.
  257. /// </returns>
  258. public bool AddAgentHandler(string agentName, IHttpAgentHandler handler)
  259. {
  260. if (!IsEnabled) return false;
  261. _agents.Add(agentName, handler);
  262. return _httpd.AddAgentHandler(agentName, handler);
  263. }
  264. /// <summary>
  265. /// Remove a powerful Agent handler from the underlying HTTP
  266. /// server.
  267. /// </summary>
  268. /// <param name="agentName">name of agent handler</param>
  269. /// <param name="handler">agent handler method</param>
  270. /// <returns>false when the plugin is disabled or the agent
  271. /// handler could not be removed. Any generated exceptions are
  272. /// allowed to drop through to the caller, i.e. KeyNotFound.
  273. /// </returns>
  274. public bool RemoveAgentHandler(string agentName, IHttpAgentHandler handler)
  275. {
  276. if (!IsEnabled) return false;
  277. if (_agents[agentName] == handler)
  278. {
  279. _agents.Remove(agentName);
  280. return _httpd.RemoveAgentHandler(agentName, handler);
  281. }
  282. return false;
  283. }
  284. /// <summary>
  285. /// Check whether the HTTP request came from god; that is, is
  286. /// the god_key as configured in the config section supplied
  287. /// via X-OpenSim-Godkey?
  288. /// </summary>
  289. /// <param name="request">HTTP request header</param>
  290. /// <returns>true when the HTTP request came from god.</returns>
  291. protected bool IsGod(OSHttpRequest request)
  292. {
  293. string[] keys = request.Headers.GetValues("X-OpenSim-Godkey");
  294. if (null == keys) return false;
  295. // we take the last key supplied
  296. return keys[keys.Length-1] == _godkey;
  297. }
  298. /// <summary>
  299. /// Checks wether the X-OpenSim-Password value provided in the
  300. /// HTTP header is indeed the password on file for the avatar
  301. /// specified by the UUID
  302. /// </summary>
  303. protected bool IsVerifiedUser(OSHttpRequest request, LLUUID uuid)
  304. {
  305. // XXX under construction
  306. return false;
  307. }
  308. /// <summary>
  309. /// Clean up and remove all handlers that were added earlier.
  310. /// </summary>
  311. public virtual void Close()
  312. {
  313. foreach (RestStreamHandler h in _handlers)
  314. {
  315. _httpd.RemoveStreamHandler(h.HttpMethod, h.Path);
  316. }
  317. _handlers = null;
  318. foreach (KeyValuePair<string,IHttpAgentHandler> h in _agents)
  319. {
  320. _httpd.RemoveAgentHandler(h.Key,h.Value);
  321. }
  322. _agents = null;
  323. }
  324. public virtual void Dispose()
  325. {
  326. Close();
  327. }
  328. /// <summary>
  329. /// Return a failure message.
  330. /// </summary>
  331. /// <param name="method">origin of the failure message</param>
  332. /// <param name="message">failure message</param>
  333. /// <remarks>This should probably set a return code as
  334. /// well. (?)</remarks>
  335. protected string Failure(OSHttpResponse response, OSHttpStatusCode status,
  336. string method, string format, params string[] msg)
  337. {
  338. string m = String.Format(format, msg);
  339. response.StatusCode = (int)status;
  340. response.StatusDescription = m;
  341. m_log.ErrorFormat("{0} {1} failed: {2}", MsgID, method, m);
  342. return String.Format("<error>{0}</error>", m);
  343. }
  344. /// <summary>
  345. /// Return a failure message.
  346. /// </summary>
  347. /// <param name="method">origin of the failure message</param>
  348. /// <param name="e">exception causing the failure message</param>
  349. /// <remarks>This should probably set a return code as
  350. /// well. (?)</remarks>
  351. public string Failure(OSHttpResponse response, OSHttpStatusCode status,
  352. string method, Exception e)
  353. {
  354. string m = String.Format("exception occurred: {0}", e.Message);
  355. response.StatusCode = (int)status;
  356. response.StatusDescription = m;
  357. m_log.DebugFormat("{0} {1} failed: {2}", MsgID, method, e.ToString());
  358. m_log.ErrorFormat("{0} {1} failed: {2}", MsgID, method, e.Message);
  359. return String.Format("<error>{0}</error>", e.Message);
  360. }
  361. #endregion methods
  362. }
  363. }