RestInventoryServices.cs 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  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.Collections.Generic;
  29. using System.Drawing;
  30. using System.Globalization;
  31. using System.IO;
  32. using System.Threading;
  33. using System.Timers;
  34. using System.Xml;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Imaging;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Communications.Cache;
  39. using OpenSim.Framework.Servers;
  40. using OpenSim.Framework.Servers.HttpServer;
  41. using Timer=System.Timers.Timer;
  42. namespace OpenSim.ApplicationPlugins.Rest.Inventory
  43. {
  44. public class RestInventoryServices : IRest
  45. {
  46. private static readonly int PARM_USERID = 0;
  47. private static readonly int PARM_PATH = 1;
  48. private bool enabled = false;
  49. private string qPrefix = "inventory";
  50. private static readonly string PRIVATE_ROOT_NAME = "My Inventory";
  51. /// <summary>
  52. /// The constructor makes sure that the service prefix is absolute
  53. /// and the registers the service handler and the allocator.
  54. /// </summary>
  55. public RestInventoryServices()
  56. {
  57. Rest.Log.InfoFormat("{0} Inventory services initializing", MsgId);
  58. Rest.Log.InfoFormat("{0} Using REST Implementation Version {1}", MsgId, Rest.Version);
  59. // If a relative path was specified for the handler's domain,
  60. // add the standard prefix to make it absolute, e.g. /admin
  61. if (!qPrefix.StartsWith(Rest.UrlPathSeparator))
  62. {
  63. Rest.Log.InfoFormat("{0} Domain is relative, adding absolute prefix", MsgId);
  64. qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix);
  65. Rest.Log.InfoFormat("{0} Domain is now <{1}>", MsgId, qPrefix);
  66. }
  67. // Register interface using the absolute URI.
  68. Rest.Plugin.AddPathHandler(DoInventory,qPrefix,Allocate);
  69. // Activate if everything went OK
  70. enabled = true;
  71. Rest.Log.InfoFormat("{0} Inventory services initialization complete", MsgId);
  72. }
  73. /// <summary>
  74. /// Post-construction, pre-enabled initialization opportunity
  75. /// Not currently exploited.
  76. /// </summary>
  77. public void Initialize()
  78. {
  79. }
  80. /// <summary>
  81. /// Called by the plug-in to halt service processing. Local processing is
  82. /// disabled.
  83. /// </summary>
  84. public void Close()
  85. {
  86. enabled = false;
  87. Rest.Log.InfoFormat("{0} Inventory services closing down", MsgId);
  88. }
  89. /// <summary>
  90. /// This property is declared locally because it is used a lot and
  91. /// brevity is nice.
  92. /// </summary>
  93. internal string MsgId
  94. {
  95. get { return Rest.MsgId; }
  96. }
  97. #region Interface
  98. /// <summary>
  99. /// The plugin (RestHandler) calls this method to allocate the request
  100. /// state carrier for a new request. It is destroyed when the request
  101. /// completes. All request-instance specific state is kept here. This
  102. /// is registered when this service provider is registered.
  103. /// </summary>
  104. /// <param name=request>Inbound HTTP request information</param>
  105. /// <param name=response>Outbound HTTP request information</param>
  106. /// <param name=qPrefix>REST service domain prefix</param>
  107. /// <returns>A RequestData instance suitable for this service</returns>
  108. private RequestData Allocate(OSHttpRequest request, OSHttpResponse response, string prefix)
  109. {
  110. return (RequestData) new InventoryRequestData(request, response, prefix);
  111. }
  112. /// <summary>
  113. /// This method is registered with the handler when this service provider
  114. /// is initialized. It is called whenever the plug-in identifies this service
  115. /// provider as the best match for a given request.
  116. /// It handles all aspects of inventory REST processing, i.e. /admin/inventory
  117. /// </summary>
  118. /// <param name=hdata>A consolidated HTTP request work area</param>
  119. private void DoInventory(RequestData hdata)
  120. {
  121. InventoryRequestData rdata = (InventoryRequestData) hdata;
  122. Rest.Log.DebugFormat("{0} DoInventory ENTRY", MsgId);
  123. // If we're disabled, do nothing.
  124. if (!enabled)
  125. {
  126. return;
  127. }
  128. // Now that we know this is a serious attempt to
  129. // access inventory data, we should find out who
  130. // is asking, and make sure they are authorized
  131. // to do so. We need to validate the caller's
  132. // identity before revealing anything about the
  133. // status quo. Authenticate throws an exception
  134. // via Fail if no identity information is present.
  135. //
  136. // With the present HTTP server we can't use the
  137. // builtin authentication mechanisms because they
  138. // would be enforced for all in-bound requests.
  139. // Instead we look at the headers ourselves and
  140. // handle authentication directly.
  141. try
  142. {
  143. if (!rdata.IsAuthenticated)
  144. {
  145. rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
  146. }
  147. }
  148. catch (RestException e)
  149. {
  150. if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
  151. {
  152. Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
  153. Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
  154. }
  155. else
  156. {
  157. Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
  158. Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
  159. }
  160. throw (e);
  161. }
  162. Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
  163. // We can only get here if we are authorized
  164. //
  165. // The requestor may have specified an UUID or
  166. // a conjoined FirstName LastName string. We'll
  167. // try both. If we fail with the first, UUID,
  168. // attempt, we try the other. As an example, the
  169. // URI for a valid inventory request might be:
  170. //
  171. // http://<host>:<port>/admin/inventory/Arthur Dent
  172. //
  173. // Indicating that this is an inventory request for
  174. // an avatar named Arthur Dent. This is ALL that is
  175. // required to designate a GET for an entire
  176. // inventory.
  177. //
  178. // Do we have at least a user agent name?
  179. if (rdata.Parameters.Length < 1)
  180. {
  181. Rest.Log.WarnFormat("{0} Inventory: No user agent identifier specified", MsgId);
  182. rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
  183. }
  184. // The first parameter MUST be the agent identification, either an UUID
  185. // or a space-separated First-name Last-Name specification. We check for
  186. // an UUID first, if anyone names their character using a valid UUID
  187. // that identifies another existing avatar will cause this a problem...
  188. try
  189. {
  190. rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
  191. Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
  192. rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
  193. }
  194. catch
  195. {
  196. string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
  197. if (names.Length == 2)
  198. {
  199. Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
  200. rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
  201. }
  202. else
  203. {
  204. Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
  205. rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
  206. }
  207. }
  208. // If the user profile is null then either the server is broken, or the
  209. // user is not known. We always assume the latter case.
  210. if (rdata.userProfile != null)
  211. {
  212. Rest.Log.DebugFormat("{0} Profile obtained for agent {1} {2}",
  213. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  214. }
  215. else
  216. {
  217. Rest.Log.WarnFormat("{0} No profile for {1}", MsgId, rdata.path);
  218. rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
  219. }
  220. // If we get to here, then we have effectively validated the user's
  221. // identity. Now we need to get the inventory. If the server does not
  222. // have the inventory, we reject the request with an appropriate explanation.
  223. //
  224. // Note that inventory retrieval is an asynchronous event, we use the rdata
  225. // class instance as the basis for our synchronization.
  226. //
  227. // TODO
  228. // If something went wrong in inventory processing the thread could stall here
  229. // indefinitely. There should be a watchdog timer to fail the request if the
  230. // response is not received in a timely fashion.
  231. rdata.uuid = rdata.userProfile.ID;
  232. if (Rest.InventoryServices.HasInventoryForUser(rdata.uuid))
  233. {
  234. rdata.root = Rest.InventoryServices.RequestRootFolder(rdata.uuid);
  235. Rest.Log.DebugFormat("{0} Inventory Root retrieved for {1} {2}",
  236. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  237. Rest.InventoryServices.RequestInventoryForUser(rdata.uuid, rdata.GetUserInventory);
  238. Rest.Log.DebugFormat("{0} Inventory catalog requested for {1} {2}",
  239. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  240. lock (rdata)
  241. {
  242. if (!rdata.HaveInventory)
  243. {
  244. rdata.startWD(1000);
  245. rdata.timeout = false;
  246. Monitor.Wait(rdata);
  247. }
  248. }
  249. if (rdata.timeout)
  250. {
  251. Rest.Log.WarnFormat("{0} Inventory not available for {1} {2}. No response from service.",
  252. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  253. rdata.Fail(Rest.HttpStatusCodeServerError, "inventory server not responding");
  254. }
  255. if (rdata.root == null)
  256. {
  257. Rest.Log.WarnFormat("{0} Inventory is not available [1] for agent {1} {2}",
  258. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  259. rdata.Fail(Rest.HttpStatusCodeServerError, "inventory retrieval failed");
  260. }
  261. }
  262. else
  263. {
  264. Rest.Log.WarnFormat("{0} Inventory is not locally available for agent {1} {2}",
  265. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  266. rdata.Fail(Rest.HttpStatusCodeNotFound, "no local inventory for user");
  267. }
  268. // If we get here, then we have successfully retrieved the user's information
  269. // and inventory information is now available locally.
  270. switch (rdata.method)
  271. {
  272. case Rest.HEAD : // Do the processing, set the status code, suppress entity
  273. DoGet(rdata);
  274. rdata.buffer = null;
  275. break;
  276. case Rest.GET : // Do the processing, set the status code, return entity
  277. DoGet(rdata);
  278. break;
  279. case Rest.PUT : // Update named element
  280. DoUpdate(rdata);
  281. break;
  282. case Rest.POST : // Add new information to identified context.
  283. DoExtend(rdata);
  284. break;
  285. case Rest.DELETE : // Delete information
  286. DoDelete(rdata);
  287. break;
  288. default :
  289. Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
  290. MsgId, rdata.method, rdata.path);
  291. rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
  292. String.Format("{0} not supported", rdata.method));
  293. break;
  294. }
  295. }
  296. #endregion Interface
  297. #region method-specific processing
  298. /// <summary>
  299. /// This method implements GET processing for inventory.
  300. /// Any remaining parameters are used to locate the
  301. /// corresponding subtree based upon node name.
  302. /// </summary>
  303. /// <param name=rdata>HTTP service request work area</param>
  304. private void DoGet(InventoryRequestData rdata)
  305. {
  306. rdata.initXmlWriter();
  307. rdata.writer.WriteStartElement(String.Empty,"Inventory",String.Empty);
  308. // If there are additional parameters, then these represent
  309. // a path relative to the root of the inventory. This path
  310. // must be traversed before we format the sub-tree thus
  311. // identified.
  312. traverse(rdata, rdata.root, PARM_PATH);
  313. // Close all open elements
  314. rdata.writer.WriteFullEndElement();
  315. // Indicate a successful request
  316. rdata.Complete();
  317. // Send the response to the user. The body will be implicitly
  318. // constructed from the result of the XML writer.
  319. rdata.Respond(String.Format("Inventory {0} Normal completion", rdata.method));
  320. }
  321. /// <summary>
  322. /// In the case of the inventory, and probably in general,
  323. /// the distinction between PUT and POST is not always
  324. /// easy to discern. The standard is badly worded in places,
  325. /// and adding a node to a hierarchy can be viewed as
  326. /// an addition, or as a modification to the inventory as
  327. /// a whole. This is exacerbated by an unjustified lack of
  328. /// consistency across different implementations.
  329. ///
  330. /// For OpenSim PUT is an update and POST is an addition. This
  331. /// is the behavior required by the HTTP specification and
  332. /// therefore as required by REST.
  333. ///
  334. /// The best way to explain the distinction is to
  335. /// consider the relationship between the URI and the
  336. /// enclosed entity. For PUT, the URI identifies the
  337. /// actual entity to be modified or replaced, i.e. the
  338. /// enclosed entity.
  339. ///
  340. /// If the operation is POST,then the URI describes the
  341. /// context into which the new entity will be added.
  342. ///
  343. /// As an example, suppose the URI contains:
  344. /// /admin/inventory/Clothing
  345. ///
  346. /// A PUT request will normally result in some modification of
  347. /// the folder or item named "Clothing". Whereas a POST
  348. /// request will normally add some new information into the
  349. /// content identified by Clothing. It follows from this
  350. /// that for POST, the element identified by the URI MUST
  351. /// be a folder.
  352. /// </summary>
  353. /// <summary>
  354. /// POST adds new information to the inventory in the
  355. /// context identified by the URI.
  356. /// </summary>
  357. /// <param name=rdata>HTTP service request work area</param>
  358. private void DoExtend(InventoryRequestData rdata)
  359. {
  360. bool created = false;
  361. bool modified = false;
  362. string newnode = String.Empty;
  363. // Resolve the context node specified in the URI. Entity
  364. // data will be ADDED beneath this node. rdata already contains
  365. // information about the current content of the user's
  366. // inventory.
  367. Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill);
  368. // Processing depends upon the type of inventory node
  369. // identified in the URI. This is the CONTEXT for the
  370. // change. We either got a context or we threw an
  371. // exception.
  372. // It follows that we can only add information if the URI
  373. // has identified a folder. So only a type of folder is supported
  374. // in this case.
  375. if (typeof(InventoryFolderBase) == InventoryNode.GetType() ||
  376. typeof(InventoryFolderImpl) == InventoryNode.GetType())
  377. {
  378. // Cast the context node appropriately.
  379. InventoryFolderBase context = (InventoryFolderBase) InventoryNode;
  380. Rest.Log.DebugFormat("{0} {1}: Resource(s) will be added to folder {2}",
  381. MsgId, rdata.method, rdata.path);
  382. // Reconstitute the inventory sub-tree from the XML supplied in the entity.
  383. // The result is a stand-alone inventory subtree, not yet integrated into the
  384. // existing tree. An inventory collection consists of three components:
  385. // [1] A (possibly empty) set of folders.
  386. // [2] A (possibly empty) set of items.
  387. // [3] A (possibly empty) set of assets.
  388. // If all of these are empty, then the POST is a harmless no-operation.
  389. XmlInventoryCollection entity = ReconstituteEntity(rdata);
  390. // Inlined assets can be included in entity. These must be incorporated into
  391. // the asset database before we attempt to update the inventory. If anything
  392. // fails, return a failure to requestor.
  393. if (entity.Assets.Count > 0)
  394. {
  395. Rest.Log.DebugFormat("{0} Adding {1} assets to server",
  396. MsgId, entity.Assets.Count);
  397. foreach (AssetBase asset in entity.Assets)
  398. {
  399. Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}",
  400. MsgId, asset.ID, asset.Type, asset.Name);
  401. Rest.AssetServices.AddAsset(asset);
  402. created = true;
  403. rdata.appendStatus(String.Format("<p> Created asset {0}, UUID {1} <p>",
  404. asset.Name, asset.ID));
  405. if (Rest.DEBUG && Rest.DumpAsset)
  406. {
  407. Rest.Dump(asset.Data);
  408. }
  409. }
  410. }
  411. // Modify the context using the collection of folders and items
  412. // returned in the XmlInventoryCollection.
  413. foreach (InventoryFolderBase folder in entity.Folders)
  414. {
  415. InventoryFolderBase found;
  416. // If the parentID is zero, then this folder is going
  417. // into the root folder identified by the URI. The requestor
  418. // may have already set the parent ID explicitly, in which
  419. // case we don't have to do it here.
  420. if (folder.ParentID == UUID.Zero || folder.ParentID == context.ID)
  421. {
  422. if (newnode != String.Empty)
  423. {
  424. Rest.Log.DebugFormat("{0} Too many resources", MsgId);
  425. rdata.Fail(Rest.HttpStatusCodeBadRequest, "only one root entity is allowed");
  426. }
  427. folder.ParentID = context.ID;
  428. newnode = folder.Name;
  429. }
  430. // Search the existing inventory for an existing entry. If
  431. // we have one, we need to decide if it has really changed.
  432. // It could just be present as (unnecessary) context, and we
  433. // don't want to waste time updating the database in that
  434. // case, OR, it could be being moved from another location
  435. // in which case an update is most certainly necessary.
  436. found = null;
  437. foreach (InventoryFolderBase xf in rdata.folders)
  438. {
  439. // Compare identifying attribute
  440. if (xf.ID == folder.ID)
  441. {
  442. found = xf;
  443. break;
  444. }
  445. }
  446. if (found != null && FolderHasChanged(folder,found))
  447. {
  448. Rest.Log.DebugFormat("{0} Updating existing folder", MsgId);
  449. Rest.InventoryServices.MoveFolder(folder);
  450. modified = true;
  451. rdata.appendStatus(String.Format("<p> Created folder {0}, UUID {1} <p>",
  452. folder.Name, folder.ID));
  453. }
  454. else
  455. {
  456. Rest.Log.DebugFormat("{0} Adding new folder", MsgId);
  457. Rest.InventoryServices.AddFolder(folder);
  458. created = true;
  459. rdata.appendStatus(String.Format("<p> Modified folder {0}, UUID {1} <p>",
  460. folder.Name, folder.ID));
  461. }
  462. }
  463. // Now we repeat a similar process for the items included
  464. // in the entity.
  465. foreach (InventoryItemBase item in entity.Items)
  466. {
  467. InventoryItemBase found = null;
  468. // If the parentID is zero, then this is going
  469. // directly into the root identified by the URI.
  470. if (item.Folder == UUID.Zero)
  471. {
  472. item.Folder = context.ID;
  473. }
  474. // Determine whether this is a new item or a
  475. // replacement definition.
  476. foreach (InventoryItemBase xi in rdata.items)
  477. {
  478. // Compare identifying attribute
  479. if (xi.ID == item.ID)
  480. {
  481. found = xi;
  482. break;
  483. }
  484. }
  485. if (found != null && ItemHasChanged(item, found))
  486. {
  487. Rest.Log.DebugFormat("{0} Updating item {1} {2} {3} {4} {5}",
  488. MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name);
  489. Rest.InventoryServices.UpdateItem(item);
  490. modified = true;
  491. rdata.appendStatus(String.Format("<p> Modified item {0}, UUID {1} <p>", item.Name, item.ID));
  492. }
  493. else
  494. {
  495. Rest.Log.DebugFormat("{0} Adding item {1} {2} {3} {4} {5}",
  496. MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name);
  497. Rest.InventoryServices.AddItem(item);
  498. created = true;
  499. rdata.appendStatus(String.Format("<p> Created item {0}, UUID {1} <p>", item.Name, item.ID));
  500. }
  501. }
  502. if (created)
  503. {
  504. // Must include a location header with a URI that identifies the new resource.
  505. rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}/{3}",
  506. rdata.hostname, rdata.port,rdata.path,newnode));
  507. rdata.Complete(Rest.HttpStatusCodeCreated);
  508. }
  509. else
  510. {
  511. if (modified)
  512. {
  513. rdata.Complete(Rest.HttpStatusCodeOK);
  514. }
  515. else
  516. {
  517. rdata.Complete(Rest.HttpStatusCodeNoContent);
  518. }
  519. }
  520. rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method));
  521. }
  522. else
  523. {
  524. Rest.Log.DebugFormat("{0} {1}: Resource {2} is not a valid context: {3}",
  525. MsgId, rdata.method, rdata.path, InventoryNode.GetType());
  526. rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid resource context");
  527. }
  528. }
  529. /// <summary>
  530. /// PUT updates the URI-identified element in the inventory. This
  531. /// is actually far more flexible than it might at first sound. For
  532. /// PUT the URI serves two purposes:
  533. /// [1] It identifies the user whose inventory is to be
  534. /// processed.
  535. /// [2] It optionally specifies a subtree of the inventory
  536. /// that is to be used to resolve any relative subtree
  537. /// specifications in the entity. If nothing is specified
  538. /// then the whole of the private inventory is implied.
  539. /// Please note that the subtree specified by the URI is only relevant
  540. /// to an entity containing a URI relative specification, i.e. one or
  541. /// more elements do not specify parent folder information. These
  542. /// elements will be implicitly referenced within the context identified
  543. /// by the URI.
  544. /// If an element in the entity specifies an explicit parent folder, then
  545. /// that parent is effective, regardless of any value specified in the
  546. /// URI. If the parent does not exist, then the element, and any dependent
  547. /// elements, are ignored. This case is actually detected and handled
  548. /// during the reconstitution process.
  549. /// </summary>
  550. /// <param name=rdata>HTTP service request work area</param>
  551. private void DoUpdate(InventoryRequestData rdata)
  552. {
  553. int count = 0;
  554. bool created = false;
  555. bool modified = false;
  556. // Resolve the inventory node that is to be modified.
  557. // rdata already contains information about the current
  558. // content of the user's inventory.
  559. Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill);
  560. // As long as we have a node, then we have something
  561. // meaningful to do, unlike POST. So we reconstitute the
  562. // subtree before doing anything else. Note that we
  563. // etiher got a valid node or we threw an exception.
  564. XmlInventoryCollection entity = ReconstituteEntity(rdata);
  565. // Incorporate any inlined assets first. Any failures
  566. // will terminate the request.
  567. if (entity.Assets.Count > 0)
  568. {
  569. Rest.Log.DebugFormat("{0} Adding {1} assets to server",
  570. MsgId, entity.Assets.Count);
  571. foreach (AssetBase asset in entity.Assets)
  572. {
  573. Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}",
  574. MsgId, asset.ID, asset.Type, asset.Name);
  575. // The asset was validated during the collection process
  576. Rest.AssetServices.AddAsset(asset);
  577. created = true;
  578. rdata.appendStatus(String.Format("<p> Created asset {0}, UUID {1} <p>", asset.Name, asset.ID));
  579. if (Rest.DEBUG && Rest.DumpAsset)
  580. {
  581. Rest.Dump(asset.Data);
  582. }
  583. }
  584. }
  585. // The URI specifies either a folder or an item to be updated.
  586. //
  587. // The root node in the entity will replace the node identified
  588. // by the URI. This means the parent will remain the same, but
  589. // any or all attributes associated with the named element
  590. // will change.
  591. //
  592. // If the inventory collection contains an element with a zero
  593. // parent ID, then this is taken to be the replacement for the
  594. // named node. The collection MAY also specify an explicit
  595. // parent ID, in this case it MAY identify the same parent as
  596. // the current node, or it MAY specify a different parent,
  597. // indicating that the folder is being moved in addition to any
  598. // other modifications being made.
  599. if (typeof(InventoryFolderBase) == InventoryNode.GetType() ||
  600. typeof(InventoryFolderImpl) == InventoryNode.GetType())
  601. {
  602. bool rfound = false;
  603. InventoryFolderBase uri = (InventoryFolderBase) InventoryNode;
  604. InventoryFolderBase xml = null;
  605. // If the entity to be replaced resolved to be the root
  606. // directory itself (My Inventory), then make sure that
  607. // the supplied data include as appropriately typed and
  608. // named folder. Note that we can;t rule out the possibility
  609. // of a sub-directory being called "My Inventory", so that
  610. // is anticipated.
  611. if (uri == rdata.root)
  612. {
  613. foreach (InventoryFolderBase folder in entity.Folders)
  614. {
  615. if ((rfound = (folder.Name == PRIVATE_ROOT_NAME)))
  616. {
  617. if ((rfound = (folder.ParentID == UUID.Zero)))
  618. break;
  619. }
  620. }
  621. if (!rfound)
  622. {
  623. Rest.Log.DebugFormat("{0} {1}: Path <{2}> will result in loss of inventory",
  624. MsgId, rdata.method, rdata.path);
  625. rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid inventory structure");
  626. }
  627. }
  628. // Scan the set of folders in the entity collection for an
  629. // entry that matches the context folder. It is assumed that
  630. // the only reliable indicator of this is a zero UUID ( using
  631. // implicit context), or the parent's UUID matches that of the
  632. // URI designated node (explicit context). We don't allow
  633. // ambiguity in this case because this is POST and we are
  634. // supposed to be modifying a specific node.
  635. // We assign any element IDs required as an economy; we don't
  636. // want to iterate over the fodler set again if it can be
  637. // helped.
  638. foreach (InventoryFolderBase folder in entity.Folders)
  639. {
  640. if (folder.ParentID == uri.ParentID ||
  641. folder.ParentID == UUID.Zero)
  642. {
  643. folder.ParentID = uri.ParentID;
  644. xml = folder;
  645. count++;
  646. }
  647. }
  648. // More than one entry is ambiguous. Other folders should be
  649. // added using the POST verb.
  650. if (count > 1)
  651. {
  652. Rest.Log.DebugFormat("{0} {1}: Request for <{2}> is ambiguous",
  653. MsgId, rdata.method, rdata.path);
  654. rdata.Fail(Rest.HttpStatusCodeConflict, "context is ambiguous");
  655. }
  656. // Exactly one entry means we ARE replacing the node
  657. // identified by the URI. So we delete the old folder
  658. // by moving it to the trash and then purging it.
  659. // We then add all of the folders and items we
  660. // included in the entity. The subtree has been
  661. // modified.
  662. if (count == 1)
  663. {
  664. InventoryFolderBase TrashCan = GetTrashCan(rdata);
  665. // All went well, so we generate a UUID is one is
  666. // needed.
  667. if (xml.ID == UUID.Zero)
  668. {
  669. xml.ID = UUID.Random();
  670. }
  671. uri.ParentID = TrashCan.ID;
  672. Rest.InventoryServices.MoveFolder(uri);
  673. Rest.InventoryServices.PurgeFolder(TrashCan);
  674. modified = true;
  675. }
  676. // Now, regardelss of what they represent, we
  677. // integrate all of the elements in the entity.
  678. foreach (InventoryFolderBase f in entity.Folders)
  679. {
  680. rdata.appendStatus(String.Format("<p>Moving folder {0} UUID {1} <p>", f.Name, f.ID));
  681. Rest.InventoryServices.MoveFolder(f);
  682. }
  683. foreach (InventoryItemBase it in entity.Items)
  684. {
  685. rdata.appendStatus(String.Format("<p>Storing item {0} UUID {1} <p>", it.Name, it.ID));
  686. Rest.InventoryServices.AddItem(it);
  687. }
  688. }
  689. /// <summary>
  690. /// URI specifies an item to be updated
  691. /// </summary>
  692. /// <remarks>
  693. /// The entity must contain a single item node to be
  694. /// updated. ID and Folder ID must be correct.
  695. /// </remarks>
  696. else
  697. {
  698. InventoryItemBase uri = (InventoryItemBase) InventoryNode;
  699. InventoryItemBase xml = null;
  700. if (entity.Folders.Count != 0)
  701. {
  702. Rest.Log.DebugFormat("{0} {1}: Request should not contain any folders <{2}>",
  703. MsgId, rdata.method, rdata.path);
  704. rdata.Fail(Rest.HttpStatusCodeBadRequest, "folder is not allowed");
  705. }
  706. if (entity.Items.Count > 1)
  707. {
  708. Rest.Log.DebugFormat("{0} {1}: Entity contains too many items <{2}>",
  709. MsgId, rdata.method, rdata.path);
  710. rdata.Fail(Rest.HttpStatusCodeBadRequest, "too may items");
  711. }
  712. xml = entity.Items[0];
  713. if (xml.ID == UUID.Zero)
  714. {
  715. xml.ID = UUID.Random();
  716. }
  717. // If the folder reference has changed, then this item is
  718. // being moved. Otherwise we'll just delete the old, and
  719. // add in the new.
  720. // Delete the old item
  721. Rest.InventoryServices.DeleteItem(uri);
  722. // Add the new item to the inventory
  723. Rest.InventoryServices.AddItem(xml);
  724. rdata.appendStatus(String.Format("<p>Storing item {0} UUID {1} <p>", xml.Name, xml.ID));
  725. }
  726. if (created)
  727. {
  728. rdata.Complete(Rest.HttpStatusCodeCreated);
  729. }
  730. else
  731. {
  732. if (modified)
  733. {
  734. rdata.Complete(Rest.HttpStatusCodeOK);
  735. }
  736. else
  737. {
  738. rdata.Complete(Rest.HttpStatusCodeNoContent);
  739. }
  740. }
  741. rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method));
  742. }
  743. /// <summary>
  744. /// Arguably the most damaging REST interface. It deletes the inventory
  745. /// item or folder identified by the URI.
  746. ///
  747. /// We only process if the URI identified node appears to exist
  748. /// We do not test for success because we either get a context,
  749. /// or an exception is thrown.
  750. ///
  751. /// Folders are deleted by moving them to another folder and then
  752. /// purging that folder. We'll do that by creating a temporary
  753. /// sub-folder in the TrashCan and purging that folder's
  754. /// contents. If we can't can it, we don't delete it...
  755. /// So, if no trashcan is available, the request does nothing.
  756. /// Items are summarily deleted.
  757. ///
  758. /// In the interests of safety, a delete request should normally
  759. /// be performed using UUID, as a name might identify several
  760. /// elements.
  761. /// </summary>
  762. /// <param name=rdata>HTTP service request work area</param>
  763. private void DoDelete(InventoryRequestData rdata)
  764. {
  765. Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, false);
  766. if (typeof(InventoryFolderBase) == InventoryNode.GetType() ||
  767. typeof(InventoryFolderImpl) == InventoryNode.GetType())
  768. {
  769. InventoryFolderBase TrashCan = GetTrashCan(rdata);
  770. InventoryFolderBase folder = (InventoryFolderBase) InventoryNode;
  771. Rest.Log.DebugFormat("{0} {1}: Folder {2} will be deleted",
  772. MsgId, rdata.method, rdata.path);
  773. folder.ParentID = TrashCan.ID;
  774. Rest.InventoryServices.MoveFolder(folder);
  775. Rest.InventoryServices.PurgeFolder(TrashCan);
  776. rdata.appendStatus(String.Format("<p>Deleted folder {0} UUID {1} <p>", folder.Name, folder.ID));
  777. }
  778. // Deleting items is much more straight forward.
  779. else
  780. {
  781. InventoryItemBase item = (InventoryItemBase) InventoryNode;
  782. Rest.Log.DebugFormat("{0} {1}: Item {2} will be deleted",
  783. MsgId, rdata.method, rdata.path);
  784. Rest.InventoryServices.DeleteItem(item);
  785. rdata.appendStatus(String.Format("<p>Deleted item {0} UUID {1} <p>", item.Name, item.ID));
  786. }
  787. rdata.Complete();
  788. rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method));
  789. }
  790. #endregion method-specific processing
  791. /// <summary>
  792. /// This method is called to obtain the OpenSim inventory object identified
  793. /// by the supplied URI. This may be either an Item or a Folder, so a suitably
  794. /// ambiguous return type is employed (Object). This method recurses as
  795. /// necessary to process the designated hierarchy.
  796. ///
  797. /// If we reach the end of the URI then we return the contextual folder to
  798. /// our caller.
  799. ///
  800. /// If we are not yet at the end of the URI we attempt to find a child folder
  801. /// and if we succeed we recurse.
  802. ///
  803. /// If this is the last node, then we look to see if this is an item. If it is,
  804. /// we return that item.
  805. ///
  806. /// If we reach the end of an inventory path and the URI si not yet exhausted,
  807. /// then if 'fill' is specified, we create the intermediate nodes.
  808. ///
  809. /// Otherwise we fail the request on the ground of an invalid URI.
  810. ///
  811. /// An ambiguous request causes the request to fail.
  812. ///
  813. /// </summary>
  814. /// <param name=rdata>HTTP service request work area</param>
  815. /// <param name=folder>The folder to be searched (parent)</param>
  816. /// <param name=pi>URI parameter index</param>
  817. /// <param name=fill>Should missing path members be created?</param>
  818. private Object getInventoryNode(InventoryRequestData rdata,
  819. InventoryFolderBase folder,
  820. int pi, bool fill)
  821. {
  822. InventoryFolderBase foundf = null;
  823. int fk = 0;
  824. Rest.Log.DebugFormat("{0} Searching folder {1} {2} [{3}]", MsgId, folder.ID, folder.Name, pi);
  825. // We have just run off the end of the parameter sequence
  826. if (pi >= rdata.Parameters.Length)
  827. {
  828. return folder;
  829. }
  830. // There are more names in the parameter sequence,
  831. // look for the folder named by param[pi] as a
  832. // child of the folder supplied as an argument.
  833. // Note that a UUID may have been supplied as the
  834. // identifier (it is the ONLY guaranteed unambiguous
  835. // option.
  836. if (rdata.folders != null)
  837. {
  838. foreach (InventoryFolderBase f in rdata.folders)
  839. {
  840. // Look for the present node in the directory list
  841. if (f.ParentID == folder.ID &&
  842. (f.Name == rdata.Parameters[pi] ||
  843. f.ID.ToString() == rdata.Parameters[pi]))
  844. {
  845. foundf = f;
  846. fk++;
  847. }
  848. }
  849. }
  850. // If more than one node matched, then the path, as specified
  851. // is ambiguous.
  852. if (fk > 1)
  853. {
  854. Rest.Log.DebugFormat("{0} {1}: Request for {2} is ambiguous",
  855. MsgId, rdata.method, rdata.path);
  856. rdata.Fail(Rest.HttpStatusCodeConflict, "request is ambiguous");
  857. }
  858. // If we find a match, then the method
  859. // increment the parameter index, and calls itself
  860. // passing the found folder as the new context.
  861. if (foundf != null)
  862. {
  863. return getInventoryNode(rdata, foundf, pi+1, fill);
  864. }
  865. // No folders that match. Perhaps this parameter identifies an item? If
  866. // it does, then it MUST also be the last name in the sequence.
  867. if (pi == rdata.Parameters.Length-1)
  868. {
  869. if (rdata.items != null)
  870. {
  871. int k = 0;
  872. InventoryItemBase li = null;
  873. foreach (InventoryItemBase i in rdata.items)
  874. {
  875. if (i.Folder == folder.ID &&
  876. (i.Name == rdata.Parameters[pi] ||
  877. i.ID.ToString() == rdata.Parameters[pi]))
  878. {
  879. li = i;
  880. k++;
  881. }
  882. }
  883. if (k == 1)
  884. {
  885. return li;
  886. }
  887. else if (k > 1)
  888. {
  889. Rest.Log.DebugFormat("{0} {1}: Request for {2} is ambiguous",
  890. MsgId, rdata.method, rdata.path);
  891. rdata.Fail(Rest.HttpStatusCodeConflict, "request is ambiguous");
  892. }
  893. }
  894. }
  895. // If fill is enabled, then we must create the missing intermediate nodes.
  896. // And of course, even this is not straightforward. All intermediate nodes
  897. // are obviously folders, but the last node may be a folder or an item.
  898. if (fill)
  899. {
  900. }
  901. // No fill, so abandon the request
  902. Rest.Log.DebugFormat("{0} {1}: Resource {2} not found",
  903. MsgId, rdata.method, rdata.path);
  904. rdata.Fail(Rest.HttpStatusCodeNotFound,
  905. String.Format("resource {0}:{1} not found", rdata.method, rdata.path));
  906. return null; /* Never reached */
  907. }
  908. /// <summary>
  909. /// This routine traverse the inventory's structure until the end-point identified
  910. /// in the URI is reached, the remainder of the inventory (if any) is then formatted
  911. /// and returned to the requestor.
  912. ///
  913. /// Note that this method is only interested in those folder that match elements of
  914. /// the URI supplied by the requestor, so once a match is fund, the processing does
  915. /// not need to consider any further elements.
  916. ///
  917. /// Only the last element in the URI should identify an item.
  918. /// </summary>
  919. /// <param name=rdata>HTTP service request work area</param>
  920. /// <param name=folder>The folder to be searched (parent)</param>
  921. /// <param name=pi>URI parameter index</param>
  922. private void traverse(InventoryRequestData rdata, InventoryFolderBase folder, int pi)
  923. {
  924. Rest.Log.DebugFormat("{0} Traverse[initial] : {1} {2} [{3}]", MsgId, folder.ID, folder.Name, pi);
  925. if (rdata.folders != null)
  926. {
  927. // If there was only one parameter (avatar name), then the entire
  928. // inventory is being requested.
  929. if (rdata.Parameters.Length == 1)
  930. {
  931. formatInventory(rdata, rdata.root, String.Empty);
  932. }
  933. // Has the client specified the root directory name explicitly?
  934. // if yes, then we just absorb the reference, because the folder
  935. // we start looking in for a match *is* the root directory. If there
  936. // are more parameters remaining we tarverse, otehrwise it's time
  937. // to format. Otherwise,we consider the "My Inventory" to be implied
  938. // and we just traverse normally.
  939. else if (folder.ID.ToString() == rdata.Parameters[pi] ||
  940. folder.Name == rdata.Parameters[pi])
  941. {
  942. // Length is -1 because the avatar name is a parameter
  943. if (pi<(rdata.Parameters.Length-1))
  944. {
  945. traverseInventory(rdata, folder, pi+1);
  946. }
  947. else
  948. {
  949. formatInventory(rdata, folder, String.Empty);
  950. }
  951. }
  952. else
  953. {
  954. traverseInventory(rdata, folder, pi);
  955. }
  956. return;
  957. }
  958. }
  959. /// <summary>
  960. /// This is the recursive method. I've separated them in this way so that
  961. /// we do not have to waste cycles on any first-case-only processing.
  962. /// </summary>
  963. private void traverseInventory(InventoryRequestData rdata, InventoryFolderBase folder, int pi)
  964. {
  965. int fk = 0;
  966. InventoryFolderBase ffound = null;
  967. InventoryItemBase ifound = null;
  968. Rest.Log.DebugFormat("{0} Traverse Folder : {1} {2} [{3}]", MsgId, folder.ID, folder.Name, pi);
  969. foreach (InventoryFolderBase f in rdata.folders)
  970. {
  971. if (f.ParentID == folder.ID &&
  972. (f.Name == rdata.Parameters[pi] ||
  973. f.ID.ToString() == rdata.Parameters[pi]))
  974. {
  975. fk++;
  976. ffound = f;
  977. }
  978. }
  979. // If this is the last element in the parameter sequence, then
  980. // it is reasonable to check for an item. All intermediate nodes
  981. // MUST be folders.
  982. if (pi == rdata.Parameters.Length-1)
  983. {
  984. // Only if there are any items, and there pretty much always are.
  985. if (rdata.items != null)
  986. {
  987. foreach (InventoryItemBase i in rdata.items)
  988. {
  989. if (i.Folder == folder.ID &&
  990. (i.Name == rdata.Parameters[pi] ||
  991. i.ID.ToString() == rdata.Parameters[pi]))
  992. {
  993. fk++;
  994. ifound = i;
  995. }
  996. }
  997. }
  998. }
  999. if (fk == 1)
  1000. {
  1001. if (ffound != null)
  1002. {
  1003. if (pi < rdata.Parameters.Length-1)
  1004. {
  1005. traverseInventory(rdata, ffound, pi+1);
  1006. }
  1007. else
  1008. {
  1009. formatInventory(rdata, ffound, String.Empty);
  1010. }
  1011. return;
  1012. }
  1013. else
  1014. {
  1015. // Fetching an Item has a special significance. In this
  1016. // case we also want to fetch the associated asset.
  1017. // To make it interesting, we'll do this via redirection.
  1018. string asseturl = String.Format("http://{0}:{1}/{2}{3}{4}", rdata.hostname, rdata.port,
  1019. "admin/assets",Rest.UrlPathSeparator,ifound.AssetID.ToString());
  1020. rdata.Redirect(asseturl,Rest.PERMANENT);
  1021. Rest.Log.DebugFormat("{0} Never Reached", MsgId);
  1022. }
  1023. }
  1024. else if (fk > 1)
  1025. {
  1026. rdata.Fail(Rest.HttpStatusCodeConflict,
  1027. String.Format("ambiguous element ({0}) in path specified: <{1}>",
  1028. pi, rdata.path));
  1029. }
  1030. Rest.Log.DebugFormat("{0} Inventory does not contain item/folder: <{1}>",
  1031. MsgId, rdata.path);
  1032. rdata.Fail(Rest.HttpStatusCodeNotFound,String.Format("no such item/folder : {0}",
  1033. rdata.Parameters[pi]));
  1034. }
  1035. /// <summary>
  1036. /// This method generates XML that describes an instance of InventoryFolderBase.
  1037. /// It recurses as necessary to reflect a folder hierarchy, and calls formatItem
  1038. /// to generate XML for any items encountered along the way.
  1039. /// The indentation parameter is solely for the benefit of trace record
  1040. /// formatting.
  1041. /// </summary>
  1042. /// <param name=rdata>HTTP service request work area</param>
  1043. /// <param name=folder>The folder to be searched (parent)</param>
  1044. /// <param name=indent>pretty print indentation</param>
  1045. private void formatInventory(InventoryRequestData rdata, InventoryFolderBase folder, string indent)
  1046. {
  1047. if (Rest.DEBUG)
  1048. {
  1049. Rest.Log.DebugFormat("{0} Folder : {1} {2} {3} type = {4}",
  1050. MsgId, folder.ID, indent, folder.Name, folder.Type);
  1051. indent += "\t";
  1052. }
  1053. // Start folder item
  1054. rdata.writer.WriteStartElement(String.Empty,"Folder",String.Empty);
  1055. rdata.writer.WriteAttributeString("name",String.Empty,folder.Name);
  1056. rdata.writer.WriteAttributeString("uuid",String.Empty,folder.ID.ToString());
  1057. rdata.writer.WriteAttributeString("parent",String.Empty,folder.ParentID.ToString());
  1058. rdata.writer.WriteAttributeString("owner",String.Empty,folder.Owner.ToString());
  1059. rdata.writer.WriteAttributeString("type",String.Empty,folder.Type.ToString());
  1060. rdata.writer.WriteAttributeString("version",String.Empty,folder.Version.ToString());
  1061. if (rdata.folders != null)
  1062. {
  1063. foreach (InventoryFolderBase f in rdata.folders)
  1064. {
  1065. if (f.ParentID == folder.ID)
  1066. {
  1067. formatInventory(rdata, f, indent);
  1068. }
  1069. }
  1070. }
  1071. if (rdata.items != null)
  1072. {
  1073. foreach (InventoryItemBase i in rdata.items)
  1074. {
  1075. if (i.Folder == folder.ID)
  1076. {
  1077. formatItem(rdata, i, indent);
  1078. }
  1079. }
  1080. }
  1081. // End folder item
  1082. rdata.writer.WriteEndElement();
  1083. }
  1084. /// <summary>
  1085. /// This method generates XML that describes an instance of InventoryItemBase.
  1086. /// </summary>
  1087. /// <param name="rdata">HTTP service request work area</param>
  1088. /// <param name="i">The item to be formatted</param>
  1089. /// <param name="indent">Pretty print indentation</param>
  1090. private void formatItem(InventoryRequestData rdata, InventoryItemBase i, string indent)
  1091. {
  1092. Rest.Log.DebugFormat("{0} Item : {1} {2} {3} Type = {4}, AssetType = {5}",
  1093. MsgId, i.ID, indent, i.Name, i.InvType, i.AssetType);
  1094. rdata.writer.WriteStartElement(String.Empty, "Item", String.Empty);
  1095. rdata.writer.WriteAttributeString("name", String.Empty, i.Name);
  1096. rdata.writer.WriteAttributeString("desc", String.Empty, i.Description);
  1097. rdata.writer.WriteAttributeString("uuid", String.Empty, i.ID.ToString());
  1098. rdata.writer.WriteAttributeString("folder", String.Empty, i.Folder.ToString());
  1099. rdata.writer.WriteAttributeString("owner", String.Empty, i.Owner.ToString());
  1100. rdata.writer.WriteAttributeString("creator", String.Empty, i.CreatorId);
  1101. rdata.writer.WriteAttributeString("creationdate", String.Empty, i.CreationDate.ToString());
  1102. rdata.writer.WriteAttributeString("invtype", String.Empty, i.InvType.ToString());
  1103. rdata.writer.WriteAttributeString("assettype", String.Empty, i.AssetType.ToString());
  1104. rdata.writer.WriteAttributeString("groupowned", String.Empty, i.GroupOwned.ToString());
  1105. rdata.writer.WriteAttributeString("groupid", String.Empty, i.GroupID.ToString());
  1106. rdata.writer.WriteAttributeString("saletype", String.Empty, i.SaleType.ToString());
  1107. rdata.writer.WriteAttributeString("saleprice", String.Empty, i.SalePrice.ToString());
  1108. rdata.writer.WriteAttributeString("flags", String.Empty, i.Flags.ToString());
  1109. rdata.writer.WriteStartElement(String.Empty, "Permissions", String.Empty);
  1110. rdata.writer.WriteAttributeString("current", String.Empty, i.CurrentPermissions.ToString("X"));
  1111. rdata.writer.WriteAttributeString("next", String.Empty, i.NextPermissions.ToString("X"));
  1112. rdata.writer.WriteAttributeString("group", String.Empty, i.GroupPermissions.ToString("X"));
  1113. rdata.writer.WriteAttributeString("everyone", String.Empty, i.EveryOnePermissions.ToString("X"));
  1114. rdata.writer.WriteAttributeString("base", String.Empty, i.BasePermissions.ToString("X"));
  1115. rdata.writer.WriteEndElement();
  1116. rdata.writer.WriteElementString("Asset", i.AssetID.ToString());
  1117. rdata.writer.WriteEndElement();
  1118. }
  1119. /// <summary>
  1120. /// This method creates a "trashcan" folder to support folder and item
  1121. /// deletions by this interface. The xisting trash folder is found and
  1122. /// this folder is created within it. It is called "tmp" to indicate to
  1123. /// the client that it is OK to delete this folder. The REST interface
  1124. /// will recreate the folder on an as-required basis.
  1125. /// If the trash can cannot be created, then by implication the request
  1126. /// that required it cannot be completed, and it fails accordingly.
  1127. /// </summary>
  1128. /// <param name=rdata>HTTP service request work area</param>
  1129. private InventoryFolderBase GetTrashCan(InventoryRequestData rdata)
  1130. {
  1131. InventoryFolderBase TrashCan = null;
  1132. foreach (InventoryFolderBase f in rdata.folders)
  1133. {
  1134. if (f.Name == "Trash")
  1135. {
  1136. foreach (InventoryFolderBase t in rdata.folders)
  1137. {
  1138. if (t.Name == "tmp")
  1139. {
  1140. TrashCan = t;
  1141. }
  1142. }
  1143. if (TrashCan == null)
  1144. {
  1145. TrashCan = new InventoryFolderBase();
  1146. TrashCan.Name = "tmp";
  1147. TrashCan.ID = UUID.Random();
  1148. TrashCan.Version = 1;
  1149. TrashCan.Type = (short) AssetType.TrashFolder;
  1150. TrashCan.ParentID = f.ID;
  1151. TrashCan.Owner = f.Owner;
  1152. Rest.InventoryServices.AddFolder(TrashCan);
  1153. }
  1154. }
  1155. }
  1156. if (TrashCan == null)
  1157. {
  1158. Rest.Log.DebugFormat("{0} No Trash Can available", MsgId);
  1159. rdata.Fail(Rest.HttpStatusCodeServerError, "unable to create trash can");
  1160. }
  1161. return TrashCan;
  1162. }
  1163. /// <summary>
  1164. /// Make sure that an unchanged folder is not unnecessarily
  1165. /// processed.
  1166. /// </summary>
  1167. /// <param name=newf>Folder obtained from enclosed entity</param>
  1168. /// <param name=oldf>Folder obtained from the user's inventory</param>
  1169. private bool FolderHasChanged(InventoryFolderBase newf, InventoryFolderBase oldf)
  1170. {
  1171. return (newf.Name != oldf.Name
  1172. || newf.ParentID != oldf.ParentID
  1173. || newf.Owner != oldf.Owner
  1174. || newf.Type != oldf.Type
  1175. || newf.Version != oldf.Version
  1176. );
  1177. }
  1178. /// <summary>
  1179. /// Make sure that an unchanged item is not unnecessarily
  1180. /// processed.
  1181. /// </summary>
  1182. /// <param name=newf>Item obtained from enclosed entity</param>
  1183. /// <param name=oldf>Item obtained from the user's inventory</param>
  1184. private bool ItemHasChanged(InventoryItemBase newf, InventoryItemBase oldf)
  1185. {
  1186. return (newf.Name != oldf.Name
  1187. || newf.Folder != oldf.Folder
  1188. || newf.Description != oldf.Description
  1189. || newf.Owner != oldf.Owner
  1190. || newf.CreatorId != oldf.CreatorId
  1191. || newf.AssetID != oldf.AssetID
  1192. || newf.GroupID != oldf.GroupID
  1193. || newf.GroupOwned != oldf.GroupOwned
  1194. || newf.InvType != oldf.InvType
  1195. || newf.AssetType != oldf.AssetType
  1196. );
  1197. }
  1198. /// <summary>
  1199. /// This method is called by PUT and POST to create an XmlInventoryCollection
  1200. /// instance that reflects the content of the entity supplied on the request.
  1201. /// Any elements in the completed collection whose UUID is zero, are
  1202. /// considered to be located relative to the end-point identified int he
  1203. /// URI. In this way, an entire sub-tree can be conveyed in a single REST
  1204. /// PUT or POST request.
  1205. ///
  1206. /// A new instance of XmlInventoryCollection is created and, if the request
  1207. /// has an entity, it is more completely initialized. thus, if no entity was
  1208. /// provided the collection is valid, but empty.
  1209. ///
  1210. /// The entity is then scanned and each tag is processed to produce the
  1211. /// appropriate inventory elements. At the end f the scan, teh XmlInventoryCollection
  1212. /// will reflect the subtree described by the entity.
  1213. ///
  1214. /// This is a very flexible mechanism, the entity may contain arbitrary,
  1215. /// discontiguous tree fragments, or may contain single element. The caller is
  1216. /// responsible for integrating this collection (and ensuring that any
  1217. /// missing parent IDs are resolved).
  1218. /// </summary>
  1219. /// <param name=rdata>HTTP service request work area</param>
  1220. internal XmlInventoryCollection ReconstituteEntity(InventoryRequestData rdata)
  1221. {
  1222. Rest.Log.DebugFormat("{0} Reconstituting entity", MsgId);
  1223. XmlInventoryCollection ic = new XmlInventoryCollection();
  1224. if (rdata.request.HasEntityBody)
  1225. {
  1226. Rest.Log.DebugFormat("{0} Entity present", MsgId);
  1227. ic.init(rdata);
  1228. try
  1229. {
  1230. while (ic.xml.Read())
  1231. {
  1232. switch (ic.xml.NodeType)
  1233. {
  1234. case XmlNodeType.Element:
  1235. Rest.Log.DebugFormat("{0} StartElement: <{1}>",
  1236. MsgId, ic.xml.Name);
  1237. switch (ic.xml.Name)
  1238. {
  1239. case "Folder":
  1240. Rest.Log.DebugFormat("{0} Processing {1} element",
  1241. MsgId, ic.xml.Name);
  1242. CollectFolder(ic);
  1243. break;
  1244. case "Item":
  1245. Rest.Log.DebugFormat("{0} Processing {1} element",
  1246. MsgId, ic.xml.Name);
  1247. CollectItem(ic);
  1248. break;
  1249. case "Asset":
  1250. Rest.Log.DebugFormat("{0} Processing {1} element",
  1251. MsgId, ic.xml.Name);
  1252. CollectAsset(ic);
  1253. break;
  1254. case "Permissions":
  1255. Rest.Log.DebugFormat("{0} Processing {1} element",
  1256. MsgId, ic.xml.Name);
  1257. CollectPermissions(ic);
  1258. break;
  1259. default:
  1260. Rest.Log.DebugFormat("{0} Ignoring {1} element",
  1261. MsgId, ic.xml.Name);
  1262. break;
  1263. }
  1264. // This stinks, but the ReadElement call above not only reads
  1265. // the imbedded data, but also consumes the end tag for Asset
  1266. // and moves the element pointer on to the containing Item's
  1267. // element-end, however, if there was a permissions element
  1268. // following, it would get us to the start of that..
  1269. if (ic.xml.NodeType == XmlNodeType.EndElement &&
  1270. ic.xml.Name == "Item")
  1271. {
  1272. Validate(ic);
  1273. }
  1274. break;
  1275. case XmlNodeType.EndElement :
  1276. switch (ic.xml.Name)
  1277. {
  1278. case "Folder":
  1279. Rest.Log.DebugFormat("{0} Completing {1} element",
  1280. MsgId, ic.xml.Name);
  1281. ic.Pop();
  1282. break;
  1283. case "Item":
  1284. Rest.Log.DebugFormat("{0} Completing {1} element",
  1285. MsgId, ic.xml.Name);
  1286. Validate(ic);
  1287. break;
  1288. case "Asset":
  1289. Rest.Log.DebugFormat("{0} Completing {1} element",
  1290. MsgId, ic.xml.Name);
  1291. break;
  1292. case "Permissions":
  1293. Rest.Log.DebugFormat("{0} Completing {1} element",
  1294. MsgId, ic.xml.Name);
  1295. break;
  1296. default:
  1297. Rest.Log.DebugFormat("{0} Ignoring {1} element",
  1298. MsgId, ic.xml.Name);
  1299. break;
  1300. }
  1301. break;
  1302. default:
  1303. Rest.Log.DebugFormat("{0} Ignoring: <{1}>:<{2}>",
  1304. MsgId, ic.xml.NodeType, ic.xml.Value);
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. catch (XmlException e)
  1310. {
  1311. Rest.Log.WarnFormat("{0} XML parsing error: {1}", MsgId, e.Message);
  1312. throw e;
  1313. }
  1314. catch (Exception e)
  1315. {
  1316. Rest.Log.WarnFormat("{0} Unexpected XML parsing error: {1}", MsgId, e.Message);
  1317. throw e;
  1318. }
  1319. }
  1320. else
  1321. {
  1322. Rest.Log.DebugFormat("{0} Entity absent", MsgId);
  1323. }
  1324. if (Rest.DEBUG)
  1325. {
  1326. Rest.Log.DebugFormat("{0} Reconstituted entity", MsgId);
  1327. Rest.Log.DebugFormat("{0} {1} assets", MsgId, ic.Assets.Count);
  1328. Rest.Log.DebugFormat("{0} {1} folder", MsgId, ic.Folders.Count);
  1329. Rest.Log.DebugFormat("{0} {1} items", MsgId, ic.Items.Count);
  1330. }
  1331. return ic;
  1332. }
  1333. /// <summary>
  1334. /// This method creates an inventory Folder from the
  1335. /// information supplied in the request's entity.
  1336. /// A folder instance is created and initialized to reflect
  1337. /// default values. These values are then overridden
  1338. /// by information supplied in the entity.
  1339. /// If context was not explicitly provided, then the
  1340. /// appropriate ID values are determined.
  1341. /// </summary>
  1342. private void CollectFolder(XmlInventoryCollection ic)
  1343. {
  1344. Rest.Log.DebugFormat("{0} Interpret folder element", MsgId);
  1345. InventoryFolderBase result = new InventoryFolderBase();
  1346. // Default values
  1347. result.Name = String.Empty;
  1348. result.ID = UUID.Zero;
  1349. result.Owner = ic.UserID;
  1350. result.ParentID = UUID.Zero; // Context
  1351. result.Type = (short) AssetType.Folder;
  1352. result.Version = 1;
  1353. if (ic.xml.HasAttributes)
  1354. {
  1355. for (int i = 0; i < ic.xml.AttributeCount; i++)
  1356. {
  1357. ic.xml.MoveToAttribute(i);
  1358. switch (ic.xml.Name)
  1359. {
  1360. case "name":
  1361. result.Name = ic.xml.Value;
  1362. break;
  1363. case "uuid":
  1364. result.ID = new UUID(ic.xml.Value);
  1365. break;
  1366. case "parent":
  1367. result.ParentID = new UUID(ic.xml.Value);
  1368. break;
  1369. case "owner":
  1370. result.Owner = new UUID(ic.xml.Value);
  1371. break;
  1372. case "type":
  1373. result.Type = Int16.Parse(ic.xml.Value);
  1374. break;
  1375. case "version":
  1376. result.Version = UInt16.Parse(ic.xml.Value);
  1377. break;
  1378. default:
  1379. Rest.Log.DebugFormat("{0} Folder: unrecognized attribute: {1}:{2}",
  1380. MsgId, ic.xml.Name, ic.xml.Value);
  1381. ic.Fail(Rest.HttpStatusCodeBadRequest, String.Format("unrecognized attribute <{0}>",
  1382. ic.xml.Name));
  1383. break;
  1384. }
  1385. }
  1386. }
  1387. ic.xml.MoveToElement();
  1388. // The client is relying upon the reconstitution process
  1389. // to determine the parent's UUID based upon context. This
  1390. // is necessary where a new folder may have been
  1391. // introduced.
  1392. if (result.ParentID == UUID.Zero)
  1393. {
  1394. result.ParentID = ic.Parent();
  1395. }
  1396. else
  1397. {
  1398. bool found = false;
  1399. foreach (InventoryFolderBase parent in ic.rdata.folders)
  1400. {
  1401. if ( parent.ID == result.ParentID )
  1402. {
  1403. found = true;
  1404. break;
  1405. }
  1406. }
  1407. if (!found)
  1408. {
  1409. Rest.Log.ErrorFormat("{0} Invalid parent ID ({1}) in folder {2}",
  1410. MsgId, ic.Item.Folder, result.ID);
  1411. ic.Fail(Rest.HttpStatusCodeBadRequest, "invalid parent");
  1412. }
  1413. }
  1414. // This is a new folder, so no existing UUID is available
  1415. // or appropriate
  1416. if (result.ID == UUID.Zero)
  1417. {
  1418. result.ID = UUID.Random();
  1419. }
  1420. // Treat this as a new context. Any other information is
  1421. // obsolete as a consequence.
  1422. ic.Push(result);
  1423. }
  1424. /// <summary>
  1425. /// This method is called to handle the construction of an Item
  1426. /// instance from the supplied request entity. It is called
  1427. /// whenever an Item start tag is detected.
  1428. /// An instance of an Item is created and initialized to default
  1429. /// values. These values are then overridden from values supplied
  1430. /// as attributes to the Item element.
  1431. /// This item is then stored in the XmlInventoryCollection and
  1432. /// will be verified by Validate.
  1433. /// All context is reset whenever the effective folder changes
  1434. /// or an item is successfully validated.
  1435. /// </summary>
  1436. private void CollectItem(XmlInventoryCollection ic)
  1437. {
  1438. Rest.Log.DebugFormat("{0} Interpret item element", MsgId);
  1439. InventoryItemBase result = new InventoryItemBase();
  1440. result.Name = String.Empty;
  1441. result.Description = String.Empty;
  1442. result.ID = UUID.Zero;
  1443. result.Folder = UUID.Zero;
  1444. result.Owner = ic.UserID;
  1445. result.CreatorId = ic.UserID.ToString();
  1446. result.AssetID = UUID.Zero;
  1447. result.GroupID = UUID.Zero;
  1448. result.GroupOwned = false;
  1449. result.InvType = (int) InventoryType.Unknown;
  1450. result.AssetType = (int) AssetType.Unknown;
  1451. if (ic.xml.HasAttributes)
  1452. {
  1453. for (int i = 0; i < ic.xml.AttributeCount; i++)
  1454. {
  1455. ic.xml.MoveToAttribute(i);
  1456. switch (ic.xml.Name)
  1457. {
  1458. case "name":
  1459. result.Name = ic.xml.Value;
  1460. break;
  1461. case "desc":
  1462. result.Description = ic.xml.Value;
  1463. break;
  1464. case "uuid":
  1465. result.ID = new UUID(ic.xml.Value);
  1466. break;
  1467. case "folder":
  1468. result.Folder = new UUID(ic.xml.Value);
  1469. break;
  1470. case "owner":
  1471. result.Owner = new UUID(ic.xml.Value);
  1472. break;
  1473. case "invtype":
  1474. result.InvType = Int32.Parse(ic.xml.Value);
  1475. break;
  1476. case "creator":
  1477. result.CreatorId = ic.xml.Value;
  1478. break;
  1479. case "assettype":
  1480. result.AssetType = Int32.Parse(ic.xml.Value);
  1481. break;
  1482. case "groupowned":
  1483. result.GroupOwned = Boolean.Parse(ic.xml.Value);
  1484. break;
  1485. case "groupid":
  1486. result.GroupID = new UUID(ic.xml.Value);
  1487. break;
  1488. case "flags":
  1489. result.Flags = UInt32.Parse(ic.xml.Value);
  1490. break;
  1491. case "creationdate":
  1492. result.CreationDate = Int32.Parse(ic.xml.Value);
  1493. break;
  1494. case "saletype":
  1495. result.SaleType = Byte.Parse(ic.xml.Value);
  1496. break;
  1497. case "saleprice":
  1498. result.SalePrice = Int32.Parse(ic.xml.Value);
  1499. break;
  1500. default:
  1501. Rest.Log.DebugFormat("{0} Item: Unrecognized attribute: {1}:{2}",
  1502. MsgId, ic.xml.Name, ic.xml.Value);
  1503. ic.Fail(Rest.HttpStatusCodeBadRequest, String.Format("unrecognized attribute",
  1504. ic.xml.Name));
  1505. break;
  1506. }
  1507. }
  1508. }
  1509. ic.xml.MoveToElement();
  1510. ic.Push(result);
  1511. }
  1512. /// <summary>
  1513. /// This method assembles an asset instance from the
  1514. /// information supplied in the request's entity. It is
  1515. /// called as a result of detecting a start tag for a
  1516. /// type of Asset.
  1517. /// The information is collected locally, and an asset
  1518. /// instance is created only if the basic XML parsing
  1519. /// completes successfully.
  1520. /// Default values for all parts of the asset are
  1521. /// established before overriding them from the supplied
  1522. /// XML.
  1523. /// If an asset has inline=true as an attribute, then
  1524. /// the element contains the data representing the
  1525. /// asset. This is saved as the data component.
  1526. /// inline=false means that the element's payload is
  1527. /// simply the UUID of the asset referenced by the
  1528. /// item being constructed.
  1529. /// An asset, if created is stored in the
  1530. /// XmlInventoryCollection
  1531. /// </summary>
  1532. private void CollectAsset(XmlInventoryCollection ic)
  1533. {
  1534. Rest.Log.DebugFormat("{0} Interpret asset element", MsgId);
  1535. string name = String.Empty;
  1536. string desc = String.Empty;
  1537. sbyte type = (sbyte) AssetType.Unknown;
  1538. bool temp = false;
  1539. bool local = false;
  1540. // This is not a persistent attribute
  1541. bool inline = false;
  1542. UUID uuid = UUID.Zero;
  1543. // Attribute is optional
  1544. if (ic.xml.HasAttributes)
  1545. {
  1546. for (int i = 0; i < ic.xml.AttributeCount; i++)
  1547. {
  1548. ic.xml.MoveToAttribute(i);
  1549. switch (ic.xml.Name)
  1550. {
  1551. case "name" :
  1552. name = ic.xml.Value;
  1553. break;
  1554. case "type" :
  1555. type = SByte.Parse(ic.xml.Value);
  1556. break;
  1557. case "description" :
  1558. desc = ic.xml.Value;
  1559. break;
  1560. case "temporary" :
  1561. temp = Boolean.Parse(ic.xml.Value);
  1562. break;
  1563. case "uuid" :
  1564. uuid = new UUID(ic.xml.Value);
  1565. break;
  1566. case "inline" :
  1567. inline = Boolean.Parse(ic.xml.Value);
  1568. break;
  1569. case "local" :
  1570. local = Boolean.Parse(ic.xml.Value);
  1571. break;
  1572. default :
  1573. Rest.Log.DebugFormat("{0} Asset: Unrecognized attribute: {1}:{2}",
  1574. MsgId, ic.xml.Name, ic.xml.Value);
  1575. ic.Fail(Rest.HttpStatusCodeBadRequest,
  1576. String.Format("unrecognized attribute <{0}>", ic.xml.Name));
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. ic.xml.MoveToElement();
  1582. // If this is a reference to an existing asset, just store the
  1583. // asset ID into the item.
  1584. if (!inline)
  1585. {
  1586. if (ic.Item != null)
  1587. {
  1588. ic.Item.AssetID = new UUID(ic.xml.ReadElementContentAsString());
  1589. Rest.Log.DebugFormat("{0} Asset ID supplied: {1}", MsgId, ic.Item.AssetID);
  1590. }
  1591. else
  1592. {
  1593. Rest.Log.DebugFormat("{0} LLUID unimbedded asset must be inline", MsgId);
  1594. ic.Fail(Rest.HttpStatusCodeBadRequest, "no context for asset");
  1595. }
  1596. }
  1597. // Otherwise, generate an asset ID, store that into the item, and
  1598. // create an entry in the asset list for the inlined asset. But
  1599. // only if the size is non-zero.
  1600. else
  1601. {
  1602. AssetBase asset = null;
  1603. string b64string = null;
  1604. // Generate a UUID if none were given, and generally none should
  1605. // be. Ever.
  1606. if (uuid == UUID.Zero)
  1607. {
  1608. uuid = UUID.Random();
  1609. }
  1610. // Create AssetBase entity to hold the inlined asset
  1611. asset = new AssetBase(uuid, name);
  1612. asset.Description = desc;
  1613. asset.Type = type; // type == 0 == texture
  1614. asset.Local = local;
  1615. asset.Temporary = temp;
  1616. b64string = ic.xml.ReadElementContentAsString();
  1617. Rest.Log.DebugFormat("{0} Data length is {1}", MsgId, b64string.Length);
  1618. Rest.Log.DebugFormat("{0} Data content starts with: \n\t<{1}>", MsgId,
  1619. b64string.Substring(0, b64string.Length > 132 ? 132 : b64string.Length));
  1620. asset.Data = Convert.FromBase64String(b64string);
  1621. // Ensure the asset always has some kind of data component
  1622. if (asset.Data == null)
  1623. {
  1624. asset.Data = new byte[1];
  1625. }
  1626. // If this is in the context of an item, establish
  1627. // a link with the item in context.
  1628. if (ic.Item != null && ic.Item.AssetID == UUID.Zero)
  1629. {
  1630. ic.Item.AssetID = uuid;
  1631. }
  1632. ic.Push(asset);
  1633. }
  1634. }
  1635. /// <summary>
  1636. /// Store any permissions information provided by the request.
  1637. /// This overrides the default permissions set when the
  1638. /// XmlInventoryCollection object was created.
  1639. /// </summary>
  1640. private void CollectPermissions(XmlInventoryCollection ic)
  1641. {
  1642. if (ic.xml.HasAttributes)
  1643. {
  1644. for (int i = 0; i < ic.xml.AttributeCount; i++)
  1645. {
  1646. ic.xml.MoveToAttribute(i);
  1647. switch (ic.xml.Name)
  1648. {
  1649. case "current":
  1650. ic.CurrentPermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1651. break;
  1652. case "next":
  1653. ic.NextPermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1654. break;
  1655. case "group":
  1656. ic.GroupPermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1657. break;
  1658. case "everyone":
  1659. ic.EveryOnePermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1660. break;
  1661. case "base":
  1662. ic.BasePermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1663. break;
  1664. default:
  1665. Rest.Log.DebugFormat("{0} Permissions: invalid attribute {1}:{2}",
  1666. MsgId,ic.xml.Name, ic.xml.Value);
  1667. ic.Fail(Rest.HttpStatusCodeBadRequest,
  1668. String.Format("invalid attribute <{0}>", ic.xml.Name));
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. ic.xml.MoveToElement();
  1674. }
  1675. /// <summary>
  1676. /// This method is called whenever an Item has been successfully
  1677. /// reconstituted from the request's entity.
  1678. /// It uses the information curren tin the XmlInventoryCollection
  1679. /// to complete the item's specification, including any implied
  1680. /// context and asset associations.
  1681. /// It fails the request if any necessary item or asset information
  1682. /// is missing.
  1683. /// </summary>
  1684. private void Validate(XmlInventoryCollection ic)
  1685. {
  1686. // There really should be an item present if we've
  1687. // called validate. So fail if there is not.
  1688. if (ic.Item == null)
  1689. {
  1690. Rest.Log.ErrorFormat("{0} Unable to parse request", MsgId);
  1691. ic.Fail(Rest.HttpStatusCodeBadRequest, "request parse error");
  1692. }
  1693. // Every item is required to have a name (via REST anyway)
  1694. if (ic.Item.Name == String.Empty)
  1695. {
  1696. Rest.Log.ErrorFormat("{0} An item name MUST be specified", MsgId);
  1697. ic.Fail(Rest.HttpStatusCodeBadRequest, "item name required");
  1698. }
  1699. // An item MUST have an asset ID. AssetID should never be zero
  1700. // here. It should always get set from the information stored
  1701. // when the Asset element was processed.
  1702. if (ic.Item.AssetID == UUID.Zero)
  1703. {
  1704. Rest.Log.ErrorFormat("{0} Unable to complete request", MsgId);
  1705. Rest.Log.InfoFormat("{0} Asset information is missing", MsgId);
  1706. ic.Fail(Rest.HttpStatusCodeBadRequest, "asset information required");
  1707. }
  1708. // If the item is new, then assign it an ID
  1709. if (ic.Item.ID == UUID.Zero)
  1710. {
  1711. ic.Item.ID = UUID.Random();
  1712. }
  1713. // If the context is being implied, obtain the current
  1714. // folder item's ID. If it was specified explicitly, make
  1715. // sure that theparent folder exists.
  1716. if (ic.Item.Folder == UUID.Zero)
  1717. {
  1718. ic.Item.Folder = ic.Parent();
  1719. }
  1720. else
  1721. {
  1722. bool found = false;
  1723. foreach (InventoryFolderBase parent in ic.rdata.folders)
  1724. {
  1725. if ( parent.ID == ic.Item.Folder )
  1726. {
  1727. found = true;
  1728. break;
  1729. }
  1730. }
  1731. if (!found)
  1732. {
  1733. Rest.Log.ErrorFormat("{0} Invalid parent ID ({1}) in item {2}",
  1734. MsgId, ic.Item.Folder, ic.Item.ID);
  1735. ic.Fail(Rest.HttpStatusCodeBadRequest, "parent information required");
  1736. }
  1737. }
  1738. // If this is an inline asset being constructed in the context
  1739. // of a new Item, then use the itm's name here too.
  1740. if (ic.Asset != null)
  1741. {
  1742. if (ic.Asset.Name == String.Empty)
  1743. ic.Asset.Name = ic.Item.Name;
  1744. if (ic.Asset.Description == String.Empty)
  1745. ic.Asset.Description = ic.Item.Description;
  1746. }
  1747. // Assign permissions
  1748. ic.Item.CurrentPermissions = ic.CurrentPermissions;
  1749. ic.Item.EveryOnePermissions = ic.EveryOnePermissions;
  1750. ic.Item.BasePermissions = ic.BasePermissions;
  1751. ic.Item.GroupPermissions = ic.GroupPermissions;
  1752. ic.Item.NextPermissions = ic.NextPermissions;
  1753. // If no type was specified for this item, we can attempt to
  1754. // infer something from the file type maybe. This is NOT as
  1755. // good as having type be specified in the XML.
  1756. if (ic.Item.AssetType == (int) AssetType.Unknown ||
  1757. ic.Item.InvType == (int) InventoryType.Unknown)
  1758. {
  1759. Rest.Log.DebugFormat("{0} Attempting to infer item type", MsgId);
  1760. string[] parts = ic.Item.Name.Split(Rest.CA_PERIOD);
  1761. if (Rest.DEBUG)
  1762. {
  1763. for (int i = 0; i < parts.Length; i++)
  1764. {
  1765. Rest.Log.DebugFormat("{0} Name part {1} : {2}",
  1766. MsgId, i, parts[i]);
  1767. }
  1768. }
  1769. // If the associated item name is multi-part, then maybe
  1770. // the last part will indicate the item type - if we're
  1771. // lucky.
  1772. if (parts.Length > 1)
  1773. {
  1774. Rest.Log.DebugFormat("{0} File type is {1}",
  1775. MsgId, parts[parts.Length - 1]);
  1776. switch (parts[parts.Length - 1])
  1777. {
  1778. case "jpeg2000" :
  1779. case "jpeg-2000" :
  1780. case "jpg2000" :
  1781. case "jpg-2000" :
  1782. Rest.Log.DebugFormat("{0} Type {1} inferred",
  1783. MsgId, parts[parts.Length-1]);
  1784. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1785. ic.Item.AssetType = (int) AssetType.ImageJPEG;
  1786. if (ic.Item.InvType == (int) InventoryType.Unknown)
  1787. ic.Item.InvType = (int) InventoryType.Texture;
  1788. break;
  1789. case "jpg" :
  1790. case "jpeg" :
  1791. Rest.Log.DebugFormat("{0} Type {1} inferred",
  1792. MsgId, parts[parts.Length - 1]);
  1793. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1794. ic.Item.AssetType = (int) AssetType.ImageJPEG;
  1795. if (ic.Item.InvType == (int) InventoryType.Unknown)
  1796. ic.Item.InvType = (int) InventoryType.Texture;
  1797. break;
  1798. case "tga" :
  1799. if (parts[parts.Length - 2].IndexOf("_texture") != -1)
  1800. {
  1801. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1802. ic.Item.AssetType = (int) AssetType.TextureTGA;
  1803. if (ic.Item.InvType == (int) AssetType.Unknown)
  1804. ic.Item.InvType = (int) InventoryType.Texture;
  1805. }
  1806. else
  1807. {
  1808. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1809. ic.Item.AssetType = (int) AssetType.ImageTGA;
  1810. if (ic.Item.InvType == (int) InventoryType.Unknown)
  1811. ic.Item.InvType = (int) InventoryType.Snapshot;
  1812. }
  1813. break;
  1814. default :
  1815. Rest.Log.DebugFormat("{0} Asset/Inventory type could not be inferred for {1}",
  1816. MsgId,ic.Item.Name);
  1817. break;
  1818. }
  1819. }
  1820. }
  1821. /// If this is a TGA remember the fact
  1822. if (ic.Item.AssetType == (int) AssetType.TextureTGA ||
  1823. ic.Item.AssetType == (int) AssetType.ImageTGA)
  1824. {
  1825. Bitmap temp;
  1826. Stream tgadata = new MemoryStream(ic.Asset.Data);
  1827. temp = LoadTGAClass.LoadTGA(tgadata);
  1828. try
  1829. {
  1830. ic.Asset.Data = OpenJPEG.EncodeFromImage(temp, true);
  1831. }
  1832. catch (DllNotFoundException)
  1833. {
  1834. Rest.Log.ErrorFormat("OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", ic.Item.Name);
  1835. ic.Asset.Data = new Byte[0];
  1836. }
  1837. catch (IndexOutOfRangeException)
  1838. {
  1839. Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", ic.Item.Name);
  1840. ic.Asset.Data = new Byte[0];
  1841. }
  1842. catch (Exception)
  1843. {
  1844. Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", ic.Item.Name);
  1845. ic.Asset.Data = new Byte[0];
  1846. }
  1847. }
  1848. ic.reset();
  1849. }
  1850. #region Inventory RequestData extension
  1851. internal class InventoryRequestData : RequestData
  1852. {
  1853. /// <summary>
  1854. /// These are the inventory specific request/response state
  1855. /// extensions.
  1856. /// </summary>
  1857. internal UUID uuid = UUID.Zero;
  1858. internal bool HaveInventory = false;
  1859. internal ICollection<InventoryFolderImpl> folders = null;
  1860. internal ICollection<InventoryItemBase> items = null;
  1861. internal UserProfileData userProfile = null;
  1862. internal InventoryFolderBase root = null;
  1863. internal bool timeout = false;
  1864. internal Timer watchDog = new Timer();
  1865. internal InventoryRequestData(OSHttpRequest request, OSHttpResponse response, string prefix)
  1866. : base(request, response, prefix)
  1867. {
  1868. }
  1869. internal void startWD(double interval)
  1870. {
  1871. Rest.Log.DebugFormat("{0} Setting watchdog", MsgId);
  1872. watchDog.Elapsed += new ElapsedEventHandler(OnTimeOut);
  1873. watchDog.Interval = interval;
  1874. watchDog.AutoReset = false;
  1875. watchDog.Enabled = true;
  1876. watchDog.Start();
  1877. }
  1878. internal void stopWD()
  1879. {
  1880. Rest.Log.DebugFormat("{0} Reset watchdog", MsgId);
  1881. watchDog.Stop();
  1882. }
  1883. /// <summary>
  1884. /// This is the callback method required by the inventory watchdog. The
  1885. /// requestor issues an inventory request and then blocks until the
  1886. /// request completes, or this method signals the monitor.
  1887. /// </summary>
  1888. private void OnTimeOut(object sender, ElapsedEventArgs args)
  1889. {
  1890. Rest.Log.DebugFormat("{0} Asynchronous inventory update timed-out", MsgId);
  1891. // InventoryRequestData rdata = (InventoryRequestData) sender;
  1892. lock (this)
  1893. {
  1894. this.folders = null;
  1895. this.items = null;
  1896. this.HaveInventory = false;
  1897. this.timeout = true;
  1898. Monitor.Pulse(this);
  1899. }
  1900. }
  1901. /// <summary>
  1902. /// This is the callback method required by inventory services. The
  1903. /// requestor issues an inventory request and then blocks until this
  1904. /// method signals the monitor.
  1905. /// </summary>
  1906. internal void GetUserInventory(ICollection<InventoryFolderImpl> folders, ICollection<InventoryItemBase> items)
  1907. {
  1908. Rest.Log.DebugFormat("{0} Asynchronously updating inventory data", MsgId);
  1909. lock (this)
  1910. {
  1911. if (watchDog.Enabled)
  1912. {
  1913. this.stopWD();
  1914. }
  1915. this.folders = folders;
  1916. this.items = items;
  1917. this.HaveInventory = true;
  1918. this.timeout = false;
  1919. Monitor.Pulse(this);
  1920. }
  1921. }
  1922. }
  1923. #endregion Inventory RequestData extension
  1924. /// <summary>
  1925. /// This class is used to record and manage the hierarchy
  1926. /// constructed from the entity supplied in the request for
  1927. /// PUT and POST.
  1928. /// </summary>
  1929. internal class XmlInventoryCollection : InventoryCollection
  1930. {
  1931. internal InventoryRequestData rdata;
  1932. private Stack<InventoryFolderBase> stk;
  1933. internal List<AssetBase> Assets;
  1934. internal InventoryItemBase Item;
  1935. internal AssetBase Asset;
  1936. internal XmlReader xml;
  1937. internal /*static*/ const uint DefaultCurrent = 0x7FFFFFFF;
  1938. internal /*static*/ const uint DefaultNext = 0x82000;
  1939. internal /*static*/ const uint DefaultBase = 0x7FFFFFFF;
  1940. internal /*static*/ const uint DefaultEveryOne = 0x0;
  1941. internal /*static*/ const uint DefaultGroup = 0x0;
  1942. internal uint CurrentPermissions = 0x00;
  1943. internal uint NextPermissions = 0x00;
  1944. internal uint BasePermissions = 0x00;
  1945. internal uint EveryOnePermissions = 0x00;
  1946. internal uint GroupPermissions = 0x00;
  1947. internal XmlInventoryCollection()
  1948. {
  1949. Folders = new List<InventoryFolderBase>();
  1950. Items = new List<InventoryItemBase>();
  1951. Assets = new List<AssetBase>();
  1952. }
  1953. internal void init(InventoryRequestData p_rdata)
  1954. {
  1955. rdata = p_rdata;
  1956. UserID = rdata.uuid;
  1957. stk = new Stack<InventoryFolderBase>();
  1958. rdata.initXmlReader();
  1959. xml = rdata.reader;
  1960. initPermissions();
  1961. }
  1962. internal void initPermissions()
  1963. {
  1964. CurrentPermissions = DefaultCurrent;
  1965. NextPermissions = DefaultNext;
  1966. BasePermissions = DefaultBase;
  1967. GroupPermissions = DefaultGroup;
  1968. EveryOnePermissions = DefaultEveryOne;
  1969. }
  1970. internal UUID Parent()
  1971. {
  1972. if (stk.Count != 0)
  1973. {
  1974. return stk.Peek().ID;
  1975. }
  1976. else
  1977. {
  1978. return UUID.Zero;
  1979. }
  1980. }
  1981. internal void Push(InventoryFolderBase folder)
  1982. {
  1983. stk.Push(folder);
  1984. Folders.Add(folder);
  1985. reset();
  1986. }
  1987. internal void Push(InventoryItemBase item)
  1988. {
  1989. Item = item;
  1990. Items.Add(item);
  1991. }
  1992. internal void Push(AssetBase asset)
  1993. {
  1994. Asset = asset;
  1995. Assets.Add(asset);
  1996. }
  1997. internal void Pop()
  1998. {
  1999. stk.Pop();
  2000. reset();
  2001. }
  2002. internal void reset()
  2003. {
  2004. Item = null;
  2005. Asset = null;
  2006. initPermissions();
  2007. }
  2008. internal void Fail(int code, string addendum)
  2009. {
  2010. rdata.Fail(code, addendum);
  2011. }
  2012. }
  2013. }
  2014. }