RestInventoryServices.cs 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  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.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. rdata.uuid = rdata.userProfile.ID;
  228. if (Rest.InventoryServices.HasInventoryForUser(rdata.uuid))
  229. {
  230. rdata.root = Rest.InventoryServices.GetRootFolder(rdata.uuid);
  231. Rest.Log.DebugFormat("{0} Inventory Root retrieved for {1} {2}",
  232. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  233. Rest.InventoryServices.GetUserInventory(rdata.uuid, rdata.GetUserInventory);
  234. Rest.Log.DebugFormat("{0} Inventory catalog requested for {1} {2}",
  235. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  236. lock (rdata)
  237. {
  238. if (!rdata.HaveInventory)
  239. {
  240. rdata.startWD(1000);
  241. rdata.timeout = false;
  242. Monitor.Wait(rdata);
  243. }
  244. }
  245. if (rdata.timeout)
  246. {
  247. Rest.Log.WarnFormat("{0} Inventory not available for {1} {2}. No response from service.",
  248. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  249. rdata.Fail(Rest.HttpStatusCodeServerError, "inventory server not responding");
  250. }
  251. if (rdata.root == null)
  252. {
  253. Rest.Log.WarnFormat("{0} Inventory is not available [1] for agent {1} {2}",
  254. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  255. rdata.Fail(Rest.HttpStatusCodeServerError, "inventory retrieval failed");
  256. }
  257. }
  258. else
  259. {
  260. Rest.Log.WarnFormat("{0} Inventory is not locally available for agent {1} {2}",
  261. MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
  262. rdata.Fail(Rest.HttpStatusCodeNotFound, "no local inventory for user");
  263. }
  264. // If we get here, then we have successfully retrieved the user's information
  265. // and inventory information is now available locally.
  266. switch (rdata.method)
  267. {
  268. case Rest.HEAD : // Do the processing, set the status code, suppress entity
  269. DoGet(rdata);
  270. rdata.buffer = null;
  271. break;
  272. case Rest.GET : // Do the processing, set the status code, return entity
  273. DoGet(rdata);
  274. break;
  275. case Rest.PUT : // Update named element
  276. DoUpdate(rdata);
  277. break;
  278. case Rest.POST : // Add new information to identified context.
  279. DoExtend(rdata);
  280. break;
  281. case Rest.DELETE : // Delete information
  282. DoDelete(rdata);
  283. break;
  284. default :
  285. Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
  286. MsgId, rdata.method, rdata.path);
  287. rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
  288. String.Format("{0} not supported", rdata.method));
  289. break;
  290. }
  291. }
  292. #endregion Interface
  293. #region method-specific processing
  294. /// <summary>
  295. /// This method implements GET processing for inventory.
  296. /// Any remaining parameters are used to locate the
  297. /// corresponding subtree based upon node name.
  298. /// </summary>
  299. /// <param name=rdata>HTTP service request work area</param>
  300. private void DoGet(InventoryRequestData rdata)
  301. {
  302. rdata.initXmlWriter();
  303. rdata.writer.WriteStartElement(String.Empty,"Inventory",String.Empty);
  304. // If there are additional parameters, then these represent
  305. // a path relative to the root of the inventory. This path
  306. // must be traversed before we format the sub-tree thus
  307. // identified.
  308. traverse(rdata, rdata.root, PARM_PATH);
  309. // Close all open elements
  310. rdata.writer.WriteFullEndElement();
  311. // Indicate a successful request
  312. rdata.Complete();
  313. // Send the response to the user. The body will be implicitly
  314. // constructed from the result of the XML writer.
  315. rdata.Respond(String.Format("Inventory {0} Normal completion", rdata.method));
  316. }
  317. /// <summary>
  318. /// In the case of the inventory, and probably in general,
  319. /// the distinction between PUT and POST is not always
  320. /// easy to discern. The standard is badly worded in places,
  321. /// and adding a node to a hierarchy can be viewed as
  322. /// an addition, or as a modification to the inventory as
  323. /// a whole. This is exacerbated by an unjustified lack of
  324. /// consistency across different implementations.
  325. ///
  326. /// For OpenSim PUT is an update and POST is an addition. This
  327. /// is the behavior required by the HTTP specification and
  328. /// therefore as required by REST.
  329. ///
  330. /// The best way to explain the distinction is to
  331. /// consider the relationship between the URI and the
  332. /// enclosed entity. For PUT, the URI identifies the
  333. /// actual entity to be modified or replaced, i.e. the
  334. /// enclosed entity.
  335. ///
  336. /// If the operation is POST,then the URI describes the
  337. /// context into which the new entity will be added.
  338. ///
  339. /// As an example, suppose the URI contains:
  340. /// /admin/inventory/Clothing
  341. ///
  342. /// A PUT request will normally result in some modification of
  343. /// the folder or item named "Clothing". Whereas a POST
  344. /// request will normally add some new information into the
  345. /// content identified by Clothing. It follows from this
  346. /// that for POST, the element identified by the URI MUST
  347. /// be a folder.
  348. /// </summary>
  349. /// <summary>
  350. /// POST adds new information to the inventory in the
  351. /// context identified by the URI.
  352. /// </summary>
  353. /// <param name=rdata>HTTP service request work area</param>
  354. private void DoExtend(InventoryRequestData rdata)
  355. {
  356. bool created = false;
  357. bool modified = false;
  358. string newnode = String.Empty;
  359. // Resolve the context node specified in the URI. Entity
  360. // data will be ADDED beneath this node. rdata already contains
  361. // information about the current content of the user's
  362. // inventory.
  363. Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill);
  364. // Processing depends upon the type of inventory node
  365. // identified in the URI. This is the CONTEXT for the
  366. // change. We either got a context or we threw an
  367. // exception.
  368. // It follows that we can only add information if the URI
  369. // has identified a folder. So only a type of folder is supported
  370. // in this case.
  371. if (typeof(InventoryFolderBase) == InventoryNode.GetType() ||
  372. typeof(InventoryFolderImpl) == InventoryNode.GetType())
  373. {
  374. // Cast the context node appropriately.
  375. InventoryFolderBase context = (InventoryFolderBase) InventoryNode;
  376. Rest.Log.DebugFormat("{0} {1}: Resource(s) will be added to folder {2}",
  377. MsgId, rdata.method, rdata.path);
  378. // Reconstitute the inventory sub-tree from the XML supplied in the entity.
  379. // The result is a stand-alone inventory subtree, not yet integrated into the
  380. // existing tree. An inventory collection consists of three components:
  381. // [1] A (possibly empty) set of folders.
  382. // [2] A (possibly empty) set of items.
  383. // [3] A (possibly empty) set of assets.
  384. // If all of these are empty, then the POST is a harmless no-operation.
  385. XmlInventoryCollection entity = ReconstituteEntity(rdata);
  386. // Inlined assets can be included in entity. These must be incorporated into
  387. // the asset database before we attempt to update the inventory. If anything
  388. // fails, return a failure to requestor.
  389. if (entity.Assets.Count > 0)
  390. {
  391. Rest.Log.DebugFormat("{0} Adding {1} assets to server",
  392. MsgId, entity.Assets.Count);
  393. foreach (AssetBase asset in entity.Assets)
  394. {
  395. Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}",
  396. MsgId, asset.ID, asset.Type, asset.Name);
  397. Rest.AssetServices.Store(asset);
  398. created = true;
  399. rdata.appendStatus(String.Format("<p> Created asset {0}, UUID {1} <p>",
  400. asset.Name, asset.ID));
  401. if (Rest.DEBUG && Rest.DumpAsset)
  402. {
  403. Rest.Dump(asset.Data);
  404. }
  405. }
  406. }
  407. // Modify the context using the collection of folders and items
  408. // returned in the XmlInventoryCollection.
  409. foreach (InventoryFolderBase folder in entity.Folders)
  410. {
  411. InventoryFolderBase found;
  412. // If the parentID is zero, then this folder is going
  413. // into the root folder identified by the URI. The requestor
  414. // may have already set the parent ID explicitly, in which
  415. // case we don't have to do it here.
  416. if (folder.ParentID == UUID.Zero || folder.ParentID == context.ID)
  417. {
  418. if (newnode != String.Empty)
  419. {
  420. Rest.Log.DebugFormat("{0} Too many resources", MsgId);
  421. rdata.Fail(Rest.HttpStatusCodeBadRequest, "only one root entity is allowed");
  422. }
  423. folder.ParentID = context.ID;
  424. newnode = folder.Name;
  425. }
  426. // Search the existing inventory for an existing entry. If
  427. // we have one, we need to decide if it has really changed.
  428. // It could just be present as (unnecessary) context, and we
  429. // don't want to waste time updating the database in that
  430. // case, OR, it could be being moved from another location
  431. // in which case an update is most certainly necessary.
  432. found = null;
  433. foreach (InventoryFolderBase xf in rdata.folders)
  434. {
  435. // Compare identifying attribute
  436. if (xf.ID == folder.ID)
  437. {
  438. found = xf;
  439. break;
  440. }
  441. }
  442. if (found != null && FolderHasChanged(folder,found))
  443. {
  444. Rest.Log.DebugFormat("{0} Updating existing folder", MsgId);
  445. Rest.InventoryServices.MoveFolder(folder);
  446. modified = true;
  447. rdata.appendStatus(String.Format("<p> Created folder {0}, UUID {1} <p>",
  448. folder.Name, folder.ID));
  449. }
  450. else
  451. {
  452. Rest.Log.DebugFormat("{0} Adding new folder", MsgId);
  453. Rest.InventoryServices.AddFolder(folder);
  454. created = true;
  455. rdata.appendStatus(String.Format("<p> Modified folder {0}, UUID {1} <p>",
  456. folder.Name, folder.ID));
  457. }
  458. }
  459. // Now we repeat a similar process for the items included
  460. // in the entity.
  461. foreach (InventoryItemBase item in entity.Items)
  462. {
  463. InventoryItemBase found = null;
  464. // If the parentID is zero, then this is going
  465. // directly into the root identified by the URI.
  466. if (item.Folder == UUID.Zero)
  467. {
  468. item.Folder = context.ID;
  469. }
  470. // Determine whether this is a new item or a
  471. // replacement definition.
  472. foreach (InventoryItemBase xi in rdata.items)
  473. {
  474. // Compare identifying attribute
  475. if (xi.ID == item.ID)
  476. {
  477. found = xi;
  478. break;
  479. }
  480. }
  481. if (found != null && ItemHasChanged(item, found))
  482. {
  483. Rest.Log.DebugFormat("{0} Updating item {1} {2} {3} {4} {5}",
  484. MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name);
  485. Rest.InventoryServices.UpdateItem(item);
  486. modified = true;
  487. rdata.appendStatus(String.Format("<p> Modified item {0}, UUID {1} <p>", item.Name, item.ID));
  488. }
  489. else
  490. {
  491. Rest.Log.DebugFormat("{0} Adding item {1} {2} {3} {4} {5}",
  492. MsgId, item.ID, item.AssetID, item.InvType, item.AssetType, item.Name);
  493. Rest.InventoryServices.AddItem(item);
  494. created = true;
  495. rdata.appendStatus(String.Format("<p> Created item {0}, UUID {1} <p>", item.Name, item.ID));
  496. }
  497. }
  498. if (created)
  499. {
  500. // Must include a location header with a URI that identifies the new resource.
  501. rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}/{3}",
  502. rdata.hostname, rdata.port,rdata.path,newnode));
  503. rdata.Complete(Rest.HttpStatusCodeCreated);
  504. }
  505. else
  506. {
  507. if (modified)
  508. {
  509. rdata.Complete(Rest.HttpStatusCodeOK);
  510. }
  511. else
  512. {
  513. rdata.Complete(Rest.HttpStatusCodeNoContent);
  514. }
  515. }
  516. rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method));
  517. }
  518. else
  519. {
  520. Rest.Log.DebugFormat("{0} {1}: Resource {2} is not a valid context: {3}",
  521. MsgId, rdata.method, rdata.path, InventoryNode.GetType());
  522. rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid resource context");
  523. }
  524. }
  525. /// <summary>
  526. /// PUT updates the URI-identified element in the inventory. This
  527. /// is actually far more flexible than it might at first sound. For
  528. /// PUT the URI serves two purposes:
  529. /// [1] It identifies the user whose inventory is to be
  530. /// processed.
  531. /// [2] It optionally specifies a subtree of the inventory
  532. /// that is to be used to resolve any relative subtree
  533. /// specifications in the entity. If nothing is specified
  534. /// then the whole of the private inventory is implied.
  535. /// Please note that the subtree specified by the URI is only relevant
  536. /// to an entity containing a URI relative specification, i.e. one or
  537. /// more elements do not specify parent folder information. These
  538. /// elements will be implicitly referenced within the context identified
  539. /// by the URI.
  540. /// If an element in the entity specifies an explicit parent folder, then
  541. /// that parent is effective, regardless of any value specified in the
  542. /// URI. If the parent does not exist, then the element, and any dependent
  543. /// elements, are ignored. This case is actually detected and handled
  544. /// during the reconstitution process.
  545. /// </summary>
  546. /// <param name=rdata>HTTP service request work area</param>
  547. private void DoUpdate(InventoryRequestData rdata)
  548. {
  549. int count = 0;
  550. bool created = false;
  551. bool modified = false;
  552. // Resolve the inventory node that is to be modified.
  553. // rdata already contains information about the current
  554. // content of the user's inventory.
  555. Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, Rest.Fill);
  556. // As long as we have a node, then we have something
  557. // meaningful to do, unlike POST. So we reconstitute the
  558. // subtree before doing anything else. Note that we
  559. // etiher got a valid node or we threw an exception.
  560. XmlInventoryCollection entity = ReconstituteEntity(rdata);
  561. // Incorporate any inlined assets first. Any failures
  562. // will terminate the request.
  563. if (entity.Assets.Count > 0)
  564. {
  565. Rest.Log.DebugFormat("{0} Adding {1} assets to server",
  566. MsgId, entity.Assets.Count);
  567. foreach (AssetBase asset in entity.Assets)
  568. {
  569. Rest.Log.DebugFormat("{0} Rest asset: {1} {2} {3}",
  570. MsgId, asset.ID, asset.Type, asset.Name);
  571. // The asset was validated during the collection process
  572. Rest.AssetServices.Store(asset);
  573. created = true;
  574. rdata.appendStatus(String.Format("<p> Created asset {0}, UUID {1} <p>", asset.Name, asset.ID));
  575. if (Rest.DEBUG && Rest.DumpAsset)
  576. {
  577. Rest.Dump(asset.Data);
  578. }
  579. }
  580. }
  581. // The URI specifies either a folder or an item to be updated.
  582. //
  583. // The root node in the entity will replace the node identified
  584. // by the URI. This means the parent will remain the same, but
  585. // any or all attributes associated with the named element
  586. // will change.
  587. //
  588. // If the inventory collection contains an element with a zero
  589. // parent ID, then this is taken to be the replacement for the
  590. // named node. The collection MAY also specify an explicit
  591. // parent ID, in this case it MAY identify the same parent as
  592. // the current node, or it MAY specify a different parent,
  593. // indicating that the folder is being moved in addition to any
  594. // other modifications being made.
  595. if (typeof(InventoryFolderBase) == InventoryNode.GetType() ||
  596. typeof(InventoryFolderImpl) == InventoryNode.GetType())
  597. {
  598. bool rfound = false;
  599. InventoryFolderBase uri = (InventoryFolderBase) InventoryNode;
  600. InventoryFolderBase xml = null;
  601. // If the entity to be replaced resolved to be the root
  602. // directory itself (My Inventory), then make sure that
  603. // the supplied data include as appropriately typed and
  604. // named folder. Note that we can;t rule out the possibility
  605. // of a sub-directory being called "My Inventory", so that
  606. // is anticipated.
  607. if (uri == rdata.root)
  608. {
  609. foreach (InventoryFolderBase folder in entity.Folders)
  610. {
  611. if ((rfound = (folder.Name == PRIVATE_ROOT_NAME)))
  612. {
  613. if ((rfound = (folder.ParentID == UUID.Zero)))
  614. break;
  615. }
  616. }
  617. if (!rfound)
  618. {
  619. Rest.Log.DebugFormat("{0} {1}: Path <{2}> will result in loss of inventory",
  620. MsgId, rdata.method, rdata.path);
  621. rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid inventory structure");
  622. }
  623. }
  624. // Scan the set of folders in the entity collection for an
  625. // entry that matches the context folder. It is assumed that
  626. // the only reliable indicator of this is a zero UUID (using
  627. // implicit context), or the parent's UUID matches that of the
  628. // URI designated node (explicit context). We don't allow
  629. // ambiguity in this case because this is POST and we are
  630. // supposed to be modifying a specific node.
  631. // We assign any element IDs required as an economy; we don't
  632. // want to iterate over the fodler set again if it can be
  633. // helped.
  634. foreach (InventoryFolderBase folder in entity.Folders)
  635. {
  636. if (folder.ParentID == uri.ParentID ||
  637. folder.ParentID == UUID.Zero)
  638. {
  639. folder.ParentID = uri.ParentID;
  640. xml = folder;
  641. count++;
  642. }
  643. }
  644. // More than one entry is ambiguous. Other folders should be
  645. // added using the POST verb.
  646. if (count > 1)
  647. {
  648. Rest.Log.DebugFormat("{0} {1}: Request for <{2}> is ambiguous",
  649. MsgId, rdata.method, rdata.path);
  650. rdata.Fail(Rest.HttpStatusCodeConflict, "context is ambiguous");
  651. }
  652. // Exactly one entry means we ARE replacing the node
  653. // identified by the URI. So we delete the old folder
  654. // by moving it to the trash and then purging it.
  655. // We then add all of the folders and items we
  656. // included in the entity. The subtree has been
  657. // modified.
  658. if (count == 1)
  659. {
  660. InventoryFolderBase TrashCan = GetTrashCan(rdata);
  661. // All went well, so we generate a UUID is one is
  662. // needed.
  663. if (xml.ID == UUID.Zero)
  664. {
  665. xml.ID = UUID.Random();
  666. }
  667. uri.ParentID = TrashCan.ID;
  668. Rest.InventoryServices.MoveFolder(uri);
  669. Rest.InventoryServices.PurgeFolder(TrashCan);
  670. modified = true;
  671. }
  672. // Now, regardelss of what they represent, we
  673. // integrate all of the elements in the entity.
  674. foreach (InventoryFolderBase f in entity.Folders)
  675. {
  676. rdata.appendStatus(String.Format("<p>Moving folder {0} UUID {1} <p>", f.Name, f.ID));
  677. Rest.InventoryServices.MoveFolder(f);
  678. }
  679. foreach (InventoryItemBase it in entity.Items)
  680. {
  681. rdata.appendStatus(String.Format("<p>Storing item {0} UUID {1} <p>", it.Name, it.ID));
  682. Rest.InventoryServices.AddItem(it);
  683. }
  684. }
  685. /// <summary>
  686. /// URI specifies an item to be updated
  687. /// </summary>
  688. /// <remarks>
  689. /// The entity must contain a single item node to be
  690. /// updated. ID and Folder ID must be correct.
  691. /// </remarks>
  692. else
  693. {
  694. InventoryItemBase uri = (InventoryItemBase) InventoryNode;
  695. InventoryItemBase xml = null;
  696. if (entity.Folders.Count != 0)
  697. {
  698. Rest.Log.DebugFormat("{0} {1}: Request should not contain any folders <{2}>",
  699. MsgId, rdata.method, rdata.path);
  700. rdata.Fail(Rest.HttpStatusCodeBadRequest, "folder is not allowed");
  701. }
  702. if (entity.Items.Count > 1)
  703. {
  704. Rest.Log.DebugFormat("{0} {1}: Entity contains too many items <{2}>",
  705. MsgId, rdata.method, rdata.path);
  706. rdata.Fail(Rest.HttpStatusCodeBadRequest, "too may items");
  707. }
  708. xml = entity.Items[0];
  709. if (xml.ID == UUID.Zero)
  710. {
  711. xml.ID = UUID.Random();
  712. }
  713. // If the folder reference has changed, then this item is
  714. // being moved. Otherwise we'll just delete the old, and
  715. // add in the new.
  716. // Delete the old item
  717. List<UUID> uuids = new List<UUID>();
  718. uuids.Add(uri.ID);
  719. Rest.InventoryServices.DeleteItems(uri.Owner, uuids);
  720. // Add the new item to the inventory
  721. Rest.InventoryServices.AddItem(xml);
  722. rdata.appendStatus(String.Format("<p>Storing item {0} UUID {1} <p>", xml.Name, xml.ID));
  723. }
  724. if (created)
  725. {
  726. rdata.Complete(Rest.HttpStatusCodeCreated);
  727. }
  728. else
  729. {
  730. if (modified)
  731. {
  732. rdata.Complete(Rest.HttpStatusCodeOK);
  733. }
  734. else
  735. {
  736. rdata.Complete(Rest.HttpStatusCodeNoContent);
  737. }
  738. }
  739. rdata.Respond(String.Format("Profile {0} : Normal completion", rdata.method));
  740. }
  741. /// <summary>
  742. /// Arguably the most damaging REST interface. It deletes the inventory
  743. /// item or folder identified by the URI.
  744. ///
  745. /// We only process if the URI identified node appears to exist
  746. /// We do not test for success because we either get a context,
  747. /// or an exception is thrown.
  748. ///
  749. /// Folders are deleted by moving them to another folder and then
  750. /// purging that folder. We'll do that by creating a temporary
  751. /// sub-folder in the TrashCan and purging that folder's
  752. /// contents. If we can't can it, we don't delete it...
  753. /// So, if no trashcan is available, the request does nothing.
  754. /// Items are summarily deleted.
  755. ///
  756. /// In the interests of safety, a delete request should normally
  757. /// be performed using UUID, as a name might identify several
  758. /// elements.
  759. /// </summary>
  760. /// <param name=rdata>HTTP service request work area</param>
  761. private void DoDelete(InventoryRequestData rdata)
  762. {
  763. Object InventoryNode = getInventoryNode(rdata, rdata.root, PARM_PATH, false);
  764. if (typeof(InventoryFolderBase) == InventoryNode.GetType() ||
  765. typeof(InventoryFolderImpl) == InventoryNode.GetType())
  766. {
  767. InventoryFolderBase TrashCan = GetTrashCan(rdata);
  768. InventoryFolderBase folder = (InventoryFolderBase) InventoryNode;
  769. Rest.Log.DebugFormat("{0} {1}: Folder {2} will be deleted",
  770. MsgId, rdata.method, rdata.path);
  771. folder.ParentID = TrashCan.ID;
  772. Rest.InventoryServices.MoveFolder(folder);
  773. Rest.InventoryServices.PurgeFolder(TrashCan);
  774. rdata.appendStatus(String.Format("<p>Deleted folder {0} UUID {1} <p>", folder.Name, folder.ID));
  775. }
  776. // Deleting items is much more straight forward.
  777. else
  778. {
  779. InventoryItemBase item = (InventoryItemBase) InventoryNode;
  780. Rest.Log.DebugFormat("{0} {1}: Item {2} will be deleted",
  781. MsgId, rdata.method, rdata.path);
  782. List<UUID> uuids = new List<UUID>();
  783. uuids.Add(item.ID);
  784. Rest.InventoryServices.DeleteItems(item.Owner, uuids);
  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, type);
  1612. asset.Description = desc;
  1613. asset.Local = local;
  1614. asset.Temporary = temp;
  1615. b64string = ic.xml.ReadElementContentAsString();
  1616. Rest.Log.DebugFormat("{0} Data length is {1}", MsgId, b64string.Length);
  1617. Rest.Log.DebugFormat("{0} Data content starts with: \n\t<{1}>", MsgId,
  1618. b64string.Substring(0, b64string.Length > 132 ? 132 : b64string.Length));
  1619. asset.Data = Convert.FromBase64String(b64string);
  1620. // Ensure the asset always has some kind of data component
  1621. if (asset.Data == null)
  1622. {
  1623. asset.Data = new byte[1];
  1624. }
  1625. // If this is in the context of an item, establish
  1626. // a link with the item in context.
  1627. if (ic.Item != null && ic.Item.AssetID == UUID.Zero)
  1628. {
  1629. ic.Item.AssetID = uuid;
  1630. }
  1631. ic.Push(asset);
  1632. }
  1633. }
  1634. /// <summary>
  1635. /// Store any permissions information provided by the request.
  1636. /// This overrides the default permissions set when the
  1637. /// XmlInventoryCollection object was created.
  1638. /// </summary>
  1639. private void CollectPermissions(XmlInventoryCollection ic)
  1640. {
  1641. if (ic.xml.HasAttributes)
  1642. {
  1643. for (int i = 0; i < ic.xml.AttributeCount; i++)
  1644. {
  1645. ic.xml.MoveToAttribute(i);
  1646. switch (ic.xml.Name)
  1647. {
  1648. case "current":
  1649. ic.CurrentPermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1650. break;
  1651. case "next":
  1652. ic.NextPermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1653. break;
  1654. case "group":
  1655. ic.GroupPermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1656. break;
  1657. case "everyone":
  1658. ic.EveryOnePermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1659. break;
  1660. case "base":
  1661. ic.BasePermissions = UInt32.Parse(ic.xml.Value, NumberStyles.HexNumber);
  1662. break;
  1663. default:
  1664. Rest.Log.DebugFormat("{0} Permissions: invalid attribute {1}:{2}",
  1665. MsgId,ic.xml.Name, ic.xml.Value);
  1666. ic.Fail(Rest.HttpStatusCodeBadRequest,
  1667. String.Format("invalid attribute <{0}>", ic.xml.Name));
  1668. break;
  1669. }
  1670. }
  1671. }
  1672. ic.xml.MoveToElement();
  1673. }
  1674. /// <summary>
  1675. /// This method is called whenever an Item has been successfully
  1676. /// reconstituted from the request's entity.
  1677. /// It uses the information curren tin the XmlInventoryCollection
  1678. /// to complete the item's specification, including any implied
  1679. /// context and asset associations.
  1680. /// It fails the request if any necessary item or asset information
  1681. /// is missing.
  1682. /// </summary>
  1683. private void Validate(XmlInventoryCollection ic)
  1684. {
  1685. // There really should be an item present if we've
  1686. // called validate. So fail if there is not.
  1687. if (ic.Item == null)
  1688. {
  1689. Rest.Log.ErrorFormat("{0} Unable to parse request", MsgId);
  1690. ic.Fail(Rest.HttpStatusCodeBadRequest, "request parse error");
  1691. }
  1692. // Every item is required to have a name (via REST anyway)
  1693. if (ic.Item.Name == String.Empty)
  1694. {
  1695. Rest.Log.ErrorFormat("{0} An item name MUST be specified", MsgId);
  1696. ic.Fail(Rest.HttpStatusCodeBadRequest, "item name required");
  1697. }
  1698. // An item MUST have an asset ID. AssetID should never be zero
  1699. // here. It should always get set from the information stored
  1700. // when the Asset element was processed.
  1701. if (ic.Item.AssetID == UUID.Zero)
  1702. {
  1703. Rest.Log.ErrorFormat("{0} Unable to complete request", MsgId);
  1704. Rest.Log.InfoFormat("{0} Asset information is missing", MsgId);
  1705. ic.Fail(Rest.HttpStatusCodeBadRequest, "asset information required");
  1706. }
  1707. // If the item is new, then assign it an ID
  1708. if (ic.Item.ID == UUID.Zero)
  1709. {
  1710. ic.Item.ID = UUID.Random();
  1711. }
  1712. // If the context is being implied, obtain the current
  1713. // folder item's ID. If it was specified explicitly, make
  1714. // sure that theparent folder exists.
  1715. if (ic.Item.Folder == UUID.Zero)
  1716. {
  1717. ic.Item.Folder = ic.Parent();
  1718. }
  1719. else
  1720. {
  1721. bool found = false;
  1722. foreach (InventoryFolderBase parent in ic.rdata.folders)
  1723. {
  1724. if (parent.ID == ic.Item.Folder)
  1725. {
  1726. found = true;
  1727. break;
  1728. }
  1729. }
  1730. if (!found)
  1731. {
  1732. Rest.Log.ErrorFormat("{0} Invalid parent ID ({1}) in item {2}",
  1733. MsgId, ic.Item.Folder, ic.Item.ID);
  1734. ic.Fail(Rest.HttpStatusCodeBadRequest, "parent information required");
  1735. }
  1736. }
  1737. // If this is an inline asset being constructed in the context
  1738. // of a new Item, then use the itm's name here too.
  1739. if (ic.Asset != null)
  1740. {
  1741. if (ic.Asset.Name == String.Empty)
  1742. ic.Asset.Name = ic.Item.Name;
  1743. if (ic.Asset.Description == String.Empty)
  1744. ic.Asset.Description = ic.Item.Description;
  1745. }
  1746. // Assign permissions
  1747. ic.Item.CurrentPermissions = ic.CurrentPermissions;
  1748. ic.Item.EveryOnePermissions = ic.EveryOnePermissions;
  1749. ic.Item.BasePermissions = ic.BasePermissions;
  1750. ic.Item.GroupPermissions = ic.GroupPermissions;
  1751. ic.Item.NextPermissions = ic.NextPermissions;
  1752. // If no type was specified for this item, we can attempt to
  1753. // infer something from the file type maybe. This is NOT as
  1754. // good as having type be specified in the XML.
  1755. if (ic.Item.AssetType == (int) AssetType.Unknown ||
  1756. ic.Item.InvType == (int) InventoryType.Unknown)
  1757. {
  1758. Rest.Log.DebugFormat("{0} Attempting to infer item type", MsgId);
  1759. string[] parts = ic.Item.Name.Split(Rest.CA_PERIOD);
  1760. if (Rest.DEBUG)
  1761. {
  1762. for (int i = 0; i < parts.Length; i++)
  1763. {
  1764. Rest.Log.DebugFormat("{0} Name part {1} : {2}",
  1765. MsgId, i, parts[i]);
  1766. }
  1767. }
  1768. // If the associated item name is multi-part, then maybe
  1769. // the last part will indicate the item type - if we're
  1770. // lucky.
  1771. if (parts.Length > 1)
  1772. {
  1773. Rest.Log.DebugFormat("{0} File type is {1}",
  1774. MsgId, parts[parts.Length - 1]);
  1775. switch (parts[parts.Length - 1])
  1776. {
  1777. case "jpeg2000" :
  1778. case "jpeg-2000" :
  1779. case "jpg2000" :
  1780. case "jpg-2000" :
  1781. Rest.Log.DebugFormat("{0} Type {1} inferred",
  1782. MsgId, parts[parts.Length-1]);
  1783. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1784. ic.Item.AssetType = (int) AssetType.ImageJPEG;
  1785. if (ic.Item.InvType == (int) InventoryType.Unknown)
  1786. ic.Item.InvType = (int) InventoryType.Texture;
  1787. break;
  1788. case "jpg" :
  1789. case "jpeg" :
  1790. Rest.Log.DebugFormat("{0} Type {1} inferred",
  1791. MsgId, parts[parts.Length - 1]);
  1792. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1793. ic.Item.AssetType = (int) AssetType.ImageJPEG;
  1794. if (ic.Item.InvType == (int) InventoryType.Unknown)
  1795. ic.Item.InvType = (int) InventoryType.Texture;
  1796. break;
  1797. case "tga" :
  1798. if (parts[parts.Length - 2].IndexOf("_texture") != -1)
  1799. {
  1800. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1801. ic.Item.AssetType = (int) AssetType.TextureTGA;
  1802. if (ic.Item.InvType == (int) AssetType.Unknown)
  1803. ic.Item.InvType = (int) InventoryType.Texture;
  1804. }
  1805. else
  1806. {
  1807. if (ic.Item.AssetType == (int) AssetType.Unknown)
  1808. ic.Item.AssetType = (int) AssetType.ImageTGA;
  1809. if (ic.Item.InvType == (int) InventoryType.Unknown)
  1810. ic.Item.InvType = (int) InventoryType.Snapshot;
  1811. }
  1812. break;
  1813. default :
  1814. Rest.Log.DebugFormat("{0} Asset/Inventory type could not be inferred for {1}",
  1815. MsgId,ic.Item.Name);
  1816. break;
  1817. }
  1818. }
  1819. }
  1820. /// If this is a TGA remember the fact
  1821. if (ic.Item.AssetType == (int) AssetType.TextureTGA ||
  1822. ic.Item.AssetType == (int) AssetType.ImageTGA)
  1823. {
  1824. Bitmap temp;
  1825. Stream tgadata = new MemoryStream(ic.Asset.Data);
  1826. temp = LoadTGAClass.LoadTGA(tgadata);
  1827. try
  1828. {
  1829. ic.Asset.Data = OpenJPEG.EncodeFromImage(temp, true);
  1830. }
  1831. catch (DllNotFoundException)
  1832. {
  1833. Rest.Log.ErrorFormat("OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", ic.Item.Name);
  1834. ic.Asset.Data = new Byte[0];
  1835. }
  1836. catch (IndexOutOfRangeException)
  1837. {
  1838. Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", ic.Item.Name);
  1839. ic.Asset.Data = new Byte[0];
  1840. }
  1841. catch (Exception)
  1842. {
  1843. Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", ic.Item.Name);
  1844. ic.Asset.Data = new Byte[0];
  1845. }
  1846. }
  1847. ic.reset();
  1848. }
  1849. #region Inventory RequestData extension
  1850. internal class InventoryRequestData : RequestData
  1851. {
  1852. /// <summary>
  1853. /// These are the inventory specific request/response state
  1854. /// extensions.
  1855. /// </summary>
  1856. internal UUID uuid = UUID.Zero;
  1857. internal bool HaveInventory = false;
  1858. internal ICollection<InventoryFolderImpl> folders = null;
  1859. internal ICollection<InventoryItemBase> items = null;
  1860. internal UserProfileData userProfile = null;
  1861. internal InventoryFolderBase root = null;
  1862. internal bool timeout = false;
  1863. internal Timer watchDog = new Timer();
  1864. internal InventoryRequestData(OSHttpRequest request, OSHttpResponse response, string prefix)
  1865. : base(request, response, prefix)
  1866. {
  1867. }
  1868. internal void startWD(double interval)
  1869. {
  1870. Rest.Log.DebugFormat("{0} Setting watchdog", MsgId);
  1871. watchDog.Elapsed += new ElapsedEventHandler(OnTimeOut);
  1872. watchDog.Interval = interval;
  1873. watchDog.AutoReset = false;
  1874. watchDog.Enabled = true;
  1875. lock (watchDog)
  1876. watchDog.Start();
  1877. }
  1878. internal void stopWD()
  1879. {
  1880. Rest.Log.DebugFormat("{0} Reset watchdog", MsgId);
  1881. lock (watchDog)
  1882. watchDog.Stop();
  1883. }
  1884. /// <summary>
  1885. /// This is the callback method required by the inventory watchdog. The
  1886. /// requestor issues an inventory request and then blocks until the
  1887. /// request completes, or this method signals the monitor.
  1888. /// </summary>
  1889. private void OnTimeOut(object sender, ElapsedEventArgs args)
  1890. {
  1891. Rest.Log.DebugFormat("{0} Asynchronous inventory update timed-out", MsgId);
  1892. // InventoryRequestData rdata = (InventoryRequestData) sender;
  1893. lock (this)
  1894. {
  1895. this.folders = null;
  1896. this.items = null;
  1897. this.HaveInventory = false;
  1898. this.timeout = true;
  1899. Monitor.Pulse(this);
  1900. }
  1901. }
  1902. /// <summary>
  1903. /// This is the callback method required by inventory services. The
  1904. /// requestor issues an inventory request and then blocks until this
  1905. /// method signals the monitor.
  1906. /// </summary>
  1907. internal void GetUserInventory(ICollection<InventoryFolderImpl> folders, ICollection<InventoryItemBase> items)
  1908. {
  1909. Rest.Log.DebugFormat("{0} Asynchronously updating inventory data", MsgId);
  1910. lock (this)
  1911. {
  1912. if (watchDog.Enabled)
  1913. {
  1914. this.stopWD();
  1915. }
  1916. this.folders = folders;
  1917. this.items = items;
  1918. this.HaveInventory = true;
  1919. this.timeout = false;
  1920. Monitor.Pulse(this);
  1921. }
  1922. }
  1923. }
  1924. #endregion Inventory RequestData extension
  1925. /// <summary>
  1926. /// This class is used to record and manage the hierarchy
  1927. /// constructed from the entity supplied in the request for
  1928. /// PUT and POST.
  1929. /// </summary>
  1930. internal class XmlInventoryCollection : InventoryCollection
  1931. {
  1932. internal InventoryRequestData rdata;
  1933. private Stack<InventoryFolderBase> stk;
  1934. internal List<AssetBase> Assets;
  1935. internal InventoryItemBase Item;
  1936. internal AssetBase Asset;
  1937. internal XmlReader xml;
  1938. internal /*static*/ const uint DefaultCurrent = 0x7FFFFFFF;
  1939. internal /*static*/ const uint DefaultNext = 0x82000;
  1940. internal /*static*/ const uint DefaultBase = 0x7FFFFFFF;
  1941. internal /*static*/ const uint DefaultEveryOne = 0x0;
  1942. internal /*static*/ const uint DefaultGroup = 0x0;
  1943. internal uint CurrentPermissions = 0x00;
  1944. internal uint NextPermissions = 0x00;
  1945. internal uint BasePermissions = 0x00;
  1946. internal uint EveryOnePermissions = 0x00;
  1947. internal uint GroupPermissions = 0x00;
  1948. internal XmlInventoryCollection()
  1949. {
  1950. Folders = new List<InventoryFolderBase>();
  1951. Items = new List<InventoryItemBase>();
  1952. Assets = new List<AssetBase>();
  1953. }
  1954. internal void init(InventoryRequestData p_rdata)
  1955. {
  1956. rdata = p_rdata;
  1957. UserID = rdata.uuid;
  1958. stk = new Stack<InventoryFolderBase>();
  1959. rdata.initXmlReader();
  1960. xml = rdata.reader;
  1961. initPermissions();
  1962. }
  1963. internal void initPermissions()
  1964. {
  1965. CurrentPermissions = DefaultCurrent;
  1966. NextPermissions = DefaultNext;
  1967. BasePermissions = DefaultBase;
  1968. GroupPermissions = DefaultGroup;
  1969. EveryOnePermissions = DefaultEveryOne;
  1970. }
  1971. internal UUID Parent()
  1972. {
  1973. if (stk.Count != 0)
  1974. {
  1975. return stk.Peek().ID;
  1976. }
  1977. else
  1978. {
  1979. return UUID.Zero;
  1980. }
  1981. }
  1982. internal void Push(InventoryFolderBase folder)
  1983. {
  1984. stk.Push(folder);
  1985. Folders.Add(folder);
  1986. reset();
  1987. }
  1988. internal void Push(InventoryItemBase item)
  1989. {
  1990. Item = item;
  1991. Items.Add(item);
  1992. }
  1993. internal void Push(AssetBase asset)
  1994. {
  1995. Asset = asset;
  1996. Assets.Add(asset);
  1997. }
  1998. internal void Pop()
  1999. {
  2000. stk.Pop();
  2001. reset();
  2002. }
  2003. internal void reset()
  2004. {
  2005. Item = null;
  2006. Asset = null;
  2007. initPermissions();
  2008. }
  2009. internal void Fail(int code, string addendum)
  2010. {
  2011. rdata.Fail(code, addendum);
  2012. }
  2013. }
  2014. }
  2015. }