1
0

RestAssetServices.cs 15 KB

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