RestAssetServices.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 OpenMetaverse;
  28. using Nini.Config;
  29. using System;
  30. using System.Collections.Generic;
  31. using System.IO;
  32. using System.Threading;
  33. using System.Xml;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Servers;
  36. using OpenSim.Framework.Communications;
  37. using OpenSim.Framework.Communications.Cache;
  38. namespace OpenSim.ApplicationPlugins.Rest.Inventory
  39. {
  40. public class RestAssetServices : IRest
  41. {
  42. private bool enabled = false;
  43. private string qPrefix = "assets";
  44. // A simple constructor is used to handle any once-only
  45. // initialization of working classes.
  46. public RestAssetServices()
  47. {
  48. Rest.Log.InfoFormat("{0} Asset services initializing", MsgId);
  49. Rest.Log.InfoFormat("{0} Using REST Implementation Version {1}", MsgId, Rest.Version);
  50. // This is better than a null reference.
  51. if (Rest.AssetServices == null)
  52. throw new Exception(String.Format("{0} OpenSim asset services are not available",
  53. MsgId));
  54. // If the handler specifies a relative path for its domain
  55. // then we must add the standard absolute prefix, e.g. /admin
  56. if (!qPrefix.StartsWith(Rest.UrlPathSeparator))
  57. {
  58. Rest.Log.InfoFormat("{0} Prefixing domain name ({1})", MsgId, qPrefix);
  59. qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix);
  60. Rest.Log.InfoFormat("{0} Fully qualified domain name is <{1}>", MsgId, qPrefix);
  61. }
  62. // Register interface using the fully-qualified prefix
  63. Rest.Plugin.AddPathHandler(DoAsset, qPrefix, Allocate);
  64. // Activate if all went OK
  65. enabled = true;
  66. Rest.Log.InfoFormat("{0} Asset services initialization complete", MsgId);
  67. }
  68. // Post-construction, pre-enabled initialization opportunity
  69. // Not currently exploited.
  70. public void Initialize()
  71. {
  72. }
  73. // Called by the plug-in to halt REST processing. Local processing is
  74. // disabled, and control blocks until all current processing has
  75. // completed. No new processing will be started
  76. public void Close()
  77. {
  78. enabled = false;
  79. Rest.Log.InfoFormat("{0} Asset services ({1}) closing down", MsgId, qPrefix);
  80. }
  81. // Properties
  82. internal string MsgId
  83. {
  84. get { return Rest.MsgId; }
  85. }
  86. #region Interface
  87. private RequestData Allocate(OSHttpRequest request, OSHttpResponse response, string prefix)
  88. {
  89. return (RequestData) new AssetRequestData(request, response, prefix);
  90. }
  91. // Asset Handler
  92. private void DoAsset(RequestData rparm)
  93. {
  94. if (!enabled) return;
  95. AssetRequestData rdata = (AssetRequestData) rparm;
  96. Rest.Log.DebugFormat("{0} REST Asset handler ({1}) ENTRY", MsgId, qPrefix);
  97. // Now that we know this is a serious attempt to
  98. // access inventory data, we should find out who
  99. // is asking, and make sure they are authorized
  100. // to do so. We need to validate the caller's
  101. // identity before revealing anything about the
  102. // status quo. Authenticate throws an exception
  103. // via Fail if no identity information is present.
  104. //
  105. // With the present HTTP server we can't use the
  106. // builtin authentication mechanisms because they
  107. // would be enforced for all in-bound requests.
  108. // Instead we look at the headers ourselves and
  109. // handle authentication directly.
  110. try
  111. {
  112. if (!rdata.IsAuthenticated)
  113. {
  114. rdata.Fail(Rest.HttpStatusCodeNotAuthorized, String.Format("user \"{0}\" could not be authenticated"));
  115. }
  116. }
  117. catch (RestException e)
  118. {
  119. if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
  120. {
  121. Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
  122. Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId,
  123. rdata.request.Headers.Get("Authorization"));
  124. }
  125. else
  126. {
  127. Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
  128. Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId,
  129. rdata.request.Headers.Get("Authorization"));
  130. }
  131. throw (e);
  132. }
  133. // Remove the prefix and what's left are the parameters. If we don't have
  134. // the parameters we need, fail the request. Parameters do NOT include
  135. // any supplied query values.
  136. if (rdata.Parameters.Length > 0)
  137. {
  138. switch (rdata.method)
  139. {
  140. case "get" :
  141. DoGet(rdata);
  142. break;
  143. case "put" :
  144. DoPut(rdata);
  145. break;
  146. case "post" :
  147. DoPost(rdata);
  148. break;
  149. case "delete" :
  150. default :
  151. Rest.Log.WarnFormat("{0} Asset: Method not supported: {1}",
  152. MsgId, rdata.method);
  153. rdata.Fail(Rest.HttpStatusCodeBadRequest,String.Format("method <{0}> not supported", rdata.method));
  154. break;
  155. }
  156. }
  157. else
  158. {
  159. Rest.Log.WarnFormat("{0} Asset: No agent information provided", MsgId);
  160. rdata.Fail(Rest.HttpStatusCodeBadRequest, "no agent information provided");
  161. }
  162. Rest.Log.DebugFormat("{0} REST Asset handler EXIT", MsgId);
  163. }
  164. #endregion Interface
  165. /// <summary>
  166. /// The only parameter we recognize is a UUID.If an asset with this identification is
  167. /// found, it's content, base-64 encoded, is returned to the client.
  168. /// </summary>
  169. private void DoGet(AssetRequestData rdata)
  170. {
  171. bool istexture = false;
  172. Rest.Log.DebugFormat("{0} REST Asset handler, Method = <{1}> ENTRY", MsgId, rdata.method);
  173. if (rdata.Parameters.Length == 1)
  174. {
  175. UUID uuid = new UUID(rdata.Parameters[0]);
  176. AssetBase asset = Rest.AssetServices.GetAsset(uuid, istexture);
  177. if (asset != null)
  178. {
  179. Rest.Log.DebugFormat("{0} Asset located <{1}>", MsgId, rdata.Parameters[0]);
  180. rdata.initXmlWriter();
  181. rdata.writer.WriteStartElement(String.Empty,"Asset",String.Empty);
  182. rdata.writer.WriteAttributeString("id", asset.ID.ToString());
  183. rdata.writer.WriteAttributeString("name", asset.Name);
  184. rdata.writer.WriteAttributeString("desc", asset.Description);
  185. rdata.writer.WriteAttributeString("type", asset.Type.ToString());
  186. rdata.writer.WriteAttributeString("local", asset.Local.ToString());
  187. rdata.writer.WriteAttributeString("temporary", asset.Temporary.ToString());
  188. rdata.writer.WriteBase64(asset.Data,0,asset.Data.Length);
  189. rdata.writer.WriteFullEndElement();
  190. }
  191. else
  192. {
  193. Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, rdata.path);
  194. rdata.Fail(Rest.HttpStatusCodeNotFound, "invalid parameters");
  195. }
  196. }
  197. rdata.Complete();
  198. rdata.Respond(String.Format("Asset <{0}> : Normal completion", rdata.method));
  199. }
  200. /// <summary>
  201. /// UPDATE existing item, if it exists. URI identifies the item in question.
  202. /// The only parameter we recognize is a UUID. The enclosed asset data (base-64 encoded)
  203. /// is decoded and stored in the database, identified by the supplied UUID.
  204. /// </summary>
  205. private void DoPut(AssetRequestData rdata)
  206. {
  207. bool modified = false;
  208. bool created = false;
  209. AssetBase asset = null;
  210. Rest.Log.DebugFormat("{0} REST Asset handler, Method = <{1}> ENTRY", MsgId, rdata.method);
  211. if (rdata.Parameters.Length == 1)
  212. {
  213. rdata.initXmlReader();
  214. XmlReader xml = rdata.reader;
  215. if (!xml.ReadToFollowing("Asset"))
  216. {
  217. Rest.Log.DebugFormat("{0} Invalid request data: <{1}>", MsgId, rdata.path);
  218. rdata.Fail(Rest.HttpStatusCodeBadRequest,"invalid request data");
  219. }
  220. UUID uuid = new UUID(rdata.Parameters[0]);
  221. asset = Rest.AssetServices.GetAsset(uuid, false);
  222. modified = (asset != null);
  223. created = !modified;
  224. asset = new AssetBase();
  225. asset.FullID = uuid;
  226. asset.Name = xml.GetAttribute("name");
  227. asset.Description = xml.GetAttribute("desc");
  228. asset.Type = SByte.Parse(xml.GetAttribute("type"));
  229. asset.Local = Int32.Parse(xml.GetAttribute("local")) != 0;
  230. asset.Temporary = Int32.Parse(xml.GetAttribute("temporary")) != 0;
  231. asset.Data = Convert.FromBase64String(xml.ReadElementContentAsString("Asset", ""));
  232. if (asset.ID != rdata.Parameters[0])
  233. {
  234. Rest.Log.WarnFormat("{0} URI and payload disagree on UUID U:{1} vs P:{2}",
  235. MsgId, rdata.Parameters[0], asset.ID);
  236. }
  237. Rest.AssetServices.AddAsset(asset);
  238. }
  239. else
  240. {
  241. Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, rdata.path);
  242. rdata.Fail(Rest.HttpStatusCodeNotFound, "invalid parameters");
  243. }
  244. if (created)
  245. {
  246. rdata.appendStatus(String.Format("<p> Created asset {0}, UUID {1} <p>", asset.Name, asset.FullID));
  247. rdata.Complete(Rest.HttpStatusCodeCreated);
  248. }
  249. else
  250. {
  251. if (modified)
  252. {
  253. rdata.appendStatus(String.Format("<p> Modified asset {0}, UUID {1} <p>", asset.Name, asset.FullID));
  254. rdata.Complete(Rest.HttpStatusCodeOK);
  255. }
  256. else
  257. {
  258. rdata.Complete(Rest.HttpStatusCodeNoContent);
  259. }
  260. }
  261. rdata.Respond(String.Format("Asset {0} : Normal completion", rdata.method));
  262. }
  263. /// <summary>
  264. /// CREATE new item, replace if it exists. URI identifies the context for the item in question.
  265. /// No parameters are required for POST, just thepayload.
  266. /// </summary>
  267. private void DoPost(AssetRequestData rdata)
  268. {
  269. bool modified = false;
  270. bool created = false;
  271. Rest.Log.DebugFormat("{0} REST Asset handler, Method = <{1}> ENTRY", MsgId, rdata.method);
  272. if (rdata.Parameters.Length != 0)
  273. {
  274. Rest.Log.WarnFormat("{0} Parameters ignored <{1}>", MsgId, rdata.path);
  275. Rest.Log.InfoFormat("{0} POST of an asset has no parameters", MsgId, rdata.path);
  276. }
  277. rdata.initXmlReader();
  278. XmlReader xml = rdata.reader;
  279. if (!xml.ReadToFollowing("Asset"))
  280. {
  281. Rest.Log.DebugFormat("{0} Invalid request data: <{1}>", MsgId, rdata.path);
  282. rdata.Fail(Rest.HttpStatusCodeBadRequest,"invalid request data");
  283. }
  284. UUID uuid = new UUID(xml.GetAttribute("id"));
  285. AssetBase asset = Rest.AssetServices.GetAsset(uuid, false);
  286. modified = (asset != null);
  287. created = !modified;
  288. asset = new AssetBase();
  289. asset.FullID = uuid;
  290. asset.Name = xml.GetAttribute("name");
  291. asset.Description = xml.GetAttribute("desc");
  292. asset.Type = SByte.Parse(xml.GetAttribute("type"));
  293. asset.Local = Int32.Parse(xml.GetAttribute("local")) != 0;
  294. asset.Temporary = Int32.Parse(xml.GetAttribute("temporary")) != 0;
  295. asset.Data = Convert.FromBase64String(xml.ReadElementContentAsString("Asset", ""));
  296. Rest.AssetServices.AddAsset(asset);
  297. if (created)
  298. {
  299. rdata.appendStatus(String.Format("<p> Created asset {0}, UUID {1} <p>", asset.Name, asset.FullID));
  300. rdata.Complete(Rest.HttpStatusCodeCreated);
  301. }
  302. else
  303. {
  304. if (modified)
  305. {
  306. rdata.appendStatus(String.Format("<p> Modified asset {0}, UUID {1} <p>", asset.Name, asset.FullID));
  307. rdata.Complete(Rest.HttpStatusCodeOK);
  308. }
  309. else
  310. {
  311. rdata.Complete(Rest.HttpStatusCodeNoContent);
  312. }
  313. }
  314. rdata.Respond(String.Format("Asset {0} : Normal completion", rdata.method));
  315. }
  316. /// <summary>
  317. /// Asset processing has no special data area requirements.
  318. /// </summary>
  319. internal class AssetRequestData : RequestData
  320. {
  321. internal AssetRequestData(OSHttpRequest request, OSHttpResponse response, string prefix)
  322. : base(request, response, prefix)
  323. {
  324. }
  325. }
  326. }
  327. }