AssetXferUploader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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.IO;
  29. using System.Reflection;
  30. using log4net;
  31. using OpenMetaverse;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework.Scenes;
  34. using OpenSim.Services.Interfaces;
  35. using PermissionMask = OpenSim.Framework.PermissionMask;
  36. namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
  37. {
  38. public class AssetXferUploader
  39. {
  40. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. /// <summary>
  42. /// Upload state.
  43. /// </summary>
  44. /// <remarks>
  45. /// New -> Uploading -> Complete
  46. /// </remarks>
  47. private enum UploadState
  48. {
  49. New,
  50. Uploading,
  51. Complete
  52. }
  53. /// <summary>
  54. /// Reference to the object that holds this uploader. Used to remove ourselves from it's list if we
  55. /// are performing a delayed update.
  56. /// </summary>
  57. AgentAssetTransactions m_transactions;
  58. private UploadState m_uploadState = UploadState.New;
  59. private AssetBase m_asset;
  60. private UUID InventFolder = UUID.Zero;
  61. private sbyte invType = 0;
  62. private bool m_createItem;
  63. private uint m_createItemCallback;
  64. private bool m_updateItem;
  65. private InventoryItemBase m_updateItemData;
  66. private bool m_updateTaskItem;
  67. private TaskInventoryItem m_updateTaskItemData;
  68. private string m_description = String.Empty;
  69. private bool m_dumpAssetToFile;
  70. private string m_name = String.Empty;
  71. // private bool m_storeLocal;
  72. private uint nextPerm = 0;
  73. private IClientAPI ourClient;
  74. private UUID m_transactionID;
  75. private sbyte type = 0;
  76. private byte wearableType = 0;
  77. public ulong XferID;
  78. private Scene m_Scene;
  79. /// <summary>
  80. /// AssetXferUploader constructor
  81. /// </summary>
  82. /// <param name='transactions'>/param>
  83. /// <param name='scene'></param>
  84. /// <param name='transactionID'></param>
  85. /// <param name='dumpAssetToFile'>
  86. /// If true then when the asset is uploaded it is dumped to a file with the format
  87. /// String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat",
  88. /// now.Year, now.Month, now.Day, now.Hour, now.Minute,
  89. /// now.Second, m_asset.Name, m_asset.Type);
  90. /// for debugging purposes.
  91. /// </param>
  92. public AssetXferUploader(
  93. AgentAssetTransactions transactions, Scene scene, UUID transactionID, bool dumpAssetToFile)
  94. {
  95. m_asset = new AssetBase();
  96. m_transactions = transactions;
  97. m_transactionID = transactionID;
  98. m_Scene = scene;
  99. m_dumpAssetToFile = dumpAssetToFile;
  100. }
  101. /// <summary>
  102. /// Process transfer data received from the client.
  103. /// </summary>
  104. /// <param name="xferID"></param>
  105. /// <param name="packetID"></param>
  106. /// <param name="data"></param>
  107. /// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns>
  108. public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data)
  109. {
  110. // m_log.DebugFormat(
  111. // "[ASSET XFER UPLOADER]: Received packet {0} for xfer {1} (data length {2})",
  112. // packetID, xferID, data.Length);
  113. if (XferID == xferID)
  114. {
  115. if (m_asset.Data.Length > 1)
  116. {
  117. byte[] destinationArray = new byte[m_asset.Data.Length + data.Length];
  118. Array.Copy(m_asset.Data, 0, destinationArray, 0, m_asset.Data.Length);
  119. Array.Copy(data, 0, destinationArray, m_asset.Data.Length, data.Length);
  120. m_asset.Data = destinationArray;
  121. }
  122. else
  123. {
  124. byte[] buffer2 = new byte[data.Length - 4];
  125. Array.Copy(data, 4, buffer2, 0, data.Length - 4);
  126. m_asset.Data = buffer2;
  127. }
  128. ourClient.SendConfirmXfer(xferID, packetID);
  129. if ((packetID & 0x80000000) != 0)
  130. {
  131. SendCompleteMessage();
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. /// <summary>
  138. /// Start asset transfer from the client
  139. /// </summary>
  140. /// <param name="remoteClient"></param>
  141. /// <param name="assetID"></param>
  142. /// <param name="transaction"></param>
  143. /// <param name="type"></param>
  144. /// <param name="data">
  145. /// Optional data. If present then the asset is created immediately with this data
  146. /// rather than requesting an upload from the client. The data must be longer than 2 bytes.
  147. /// </param>
  148. /// <param name="storeLocal"></param>
  149. /// <param name="tempFile"></param>
  150. public void StartUpload(
  151. IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal,
  152. bool tempFile)
  153. {
  154. // m_log.DebugFormat(
  155. // "[ASSET XFER UPLOADER]: Initialised xfer from {0}, asset {1}, transaction {2}, type {3}, storeLocal {4}, tempFile {5}, already received data length {6}",
  156. // remoteClient.Name, assetID, transaction, type, storeLocal, tempFile, data.Length);
  157. lock (this)
  158. {
  159. if (m_uploadState != UploadState.New)
  160. {
  161. m_log.WarnFormat(
  162. "[ASSET XFER UPLOADER]: Tried to start upload of asset {0}, transaction {1} for {2} but this is already in state {3}. Aborting.",
  163. assetID, transaction, remoteClient.Name, m_uploadState);
  164. return;
  165. }
  166. m_uploadState = UploadState.Uploading;
  167. }
  168. ourClient = remoteClient;
  169. m_asset.FullID = assetID;
  170. m_asset.Type = type;
  171. m_asset.CreatorID = remoteClient.AgentId.ToString();
  172. m_asset.Data = data;
  173. m_asset.Local = storeLocal;
  174. m_asset.Temporary = tempFile;
  175. // m_storeLocal = storeLocal;
  176. if (m_asset.Data.Length > 2)
  177. {
  178. SendCompleteMessage();
  179. }
  180. else
  181. {
  182. RequestStartXfer();
  183. }
  184. }
  185. protected void RequestStartXfer()
  186. {
  187. XferID = Util.GetNextXferID();
  188. // m_log.DebugFormat(
  189. // "[ASSET XFER UPLOADER]: Requesting Xfer of asset {0}, type {1}, transfer id {2} from {3}",
  190. // m_asset.FullID, m_asset.Type, XferID, ourClient.Name);
  191. ourClient.SendXferRequest(XferID, m_asset.Type, m_asset.FullID, 0, new byte[0]);
  192. }
  193. protected void SendCompleteMessage()
  194. {
  195. // We must lock in order to avoid a race with a separate thread dealing with an inventory item or create
  196. // message from other client UDP.
  197. lock (this)
  198. {
  199. m_uploadState = UploadState.Complete;
  200. ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID);
  201. if (m_createItem)
  202. {
  203. CompleteCreateItem(m_createItemCallback);
  204. }
  205. else if (m_updateItem)
  206. {
  207. CompleteItemUpdate(m_updateItemData);
  208. }
  209. else if (m_updateTaskItem)
  210. {
  211. CompleteTaskItemUpdate(m_updateTaskItemData);
  212. }
  213. // else if (m_storeLocal)
  214. // {
  215. // m_Scene.AssetService.Store(m_asset);
  216. // }
  217. }
  218. m_log.DebugFormat(
  219. "[ASSET XFER UPLOADER]: Uploaded asset {0} for transaction {1}",
  220. m_asset.FullID, m_transactionID);
  221. if (m_dumpAssetToFile)
  222. {
  223. DateTime now = DateTime.Now;
  224. string filename =
  225. String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat",
  226. now.Year, now.Month, now.Day, now.Hour, now.Minute,
  227. now.Second, m_asset.Name, m_asset.Type);
  228. SaveAssetToFile(filename, m_asset.Data);
  229. }
  230. }
  231. private void SaveAssetToFile(string filename, byte[] data)
  232. {
  233. string assetPath = "UserAssets";
  234. if (!Directory.Exists(assetPath))
  235. {
  236. Directory.CreateDirectory(assetPath);
  237. }
  238. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  239. BinaryWriter bw = new BinaryWriter(fs);
  240. bw.Write(data);
  241. bw.Close();
  242. fs.Close();
  243. }
  244. public void RequestCreateInventoryItem(IClientAPI remoteClient,
  245. UUID folderID, uint callbackID,
  246. string description, string name, sbyte invType,
  247. sbyte type, byte wearableType, uint nextOwnerMask)
  248. {
  249. InventFolder = folderID;
  250. m_name = name;
  251. m_description = description;
  252. this.type = type;
  253. this.invType = invType;
  254. this.wearableType = wearableType;
  255. nextPerm = nextOwnerMask;
  256. m_asset.Name = name;
  257. m_asset.Description = description;
  258. m_asset.Type = type;
  259. // We must lock to avoid a race with a separate thread uploading the asset.
  260. lock (this)
  261. {
  262. if (m_uploadState == UploadState.Complete)
  263. {
  264. CompleteCreateItem(callbackID);
  265. }
  266. else
  267. {
  268. m_createItem = true; //set flag so the inventory item is created when upload is complete
  269. m_createItemCallback = callbackID;
  270. }
  271. }
  272. }
  273. public void RequestUpdateInventoryItem(IClientAPI remoteClient, InventoryItemBase item)
  274. {
  275. // We must lock to avoid a race with a separate thread uploading the asset.
  276. lock (this)
  277. {
  278. m_asset.Name = item.Name;
  279. m_asset.Description = item.Description;
  280. m_asset.Type = (sbyte)item.AssetType;
  281. // We must always store the item at this point even if the asset hasn't finished uploading, in order
  282. // to avoid a race condition when the appearance module retrieves the item to set the asset id in
  283. // the AvatarAppearance structure.
  284. item.AssetID = m_asset.FullID;
  285. if (item.AssetID != UUID.Zero)
  286. m_Scene.InventoryService.UpdateItem(item);
  287. if (m_uploadState == UploadState.Complete)
  288. {
  289. CompleteItemUpdate(item);
  290. }
  291. else
  292. {
  293. // m_log.DebugFormat(
  294. // "[ASSET XFER UPLOADER]: Holding update inventory item request {0} for {1} pending completion of asset xfer for transaction {2}",
  295. // item.Name, remoteClient.Name, transactionID);
  296. m_updateItem = true;
  297. m_updateItemData = item;
  298. }
  299. }
  300. }
  301. public void RequestUpdateTaskInventoryItem(IClientAPI remoteClient, TaskInventoryItem taskItem)
  302. {
  303. // We must lock to avoid a race with a separate thread uploading the asset.
  304. lock (this)
  305. {
  306. m_asset.Name = taskItem.Name;
  307. m_asset.Description = taskItem.Description;
  308. m_asset.Type = (sbyte)taskItem.Type;
  309. taskItem.AssetID = m_asset.FullID;
  310. if (m_uploadState == UploadState.Complete)
  311. {
  312. CompleteTaskItemUpdate(taskItem);
  313. }
  314. else
  315. {
  316. m_updateTaskItem = true;
  317. m_updateTaskItemData = taskItem;
  318. }
  319. }
  320. }
  321. /// <summary>
  322. /// Store the asset for the given item when it has been uploaded.
  323. /// </summary>
  324. /// <param name="item"></param>
  325. private void CompleteItemUpdate(InventoryItemBase item)
  326. {
  327. // m_log.DebugFormat(
  328. // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier item update for {1} for {2}",
  329. // m_asset.FullID, item.Name, ourClient.Name);
  330. m_Scene.AssetService.Store(m_asset);
  331. m_transactions.RemoveXferUploader(m_transactionID);
  332. }
  333. /// <summary>
  334. /// Store the asset for the given task item when it has been uploaded.
  335. /// </summary>
  336. /// <param name="taskItem"></param>
  337. private void CompleteTaskItemUpdate(TaskInventoryItem taskItem)
  338. {
  339. // m_log.DebugFormat(
  340. // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier task item update for {1} for {2}",
  341. // m_asset.FullID, taskItem.Name, ourClient.Name);
  342. m_Scene.AssetService.Store(m_asset);
  343. m_transactions.RemoveXferUploader(m_transactionID);
  344. }
  345. private void CompleteCreateItem(uint callbackID)
  346. {
  347. m_Scene.AssetService.Store(m_asset);
  348. InventoryItemBase item = new InventoryItemBase();
  349. item.Owner = ourClient.AgentId;
  350. item.CreatorId = ourClient.AgentId.ToString();
  351. item.ID = UUID.Random();
  352. item.AssetID = m_asset.FullID;
  353. item.Description = m_description;
  354. item.Name = m_name;
  355. item.AssetType = type;
  356. item.InvType = invType;
  357. item.Folder = InventFolder;
  358. item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
  359. item.CurrentPermissions = item.BasePermissions;
  360. item.GroupPermissions=0;
  361. item.EveryOnePermissions=0;
  362. item.NextPermissions = nextPerm;
  363. item.Flags = (uint) wearableType;
  364. item.CreationDate = Util.UnixTimeSinceEpoch();
  365. if (m_Scene.AddInventoryItem(item))
  366. ourClient.SendInventoryItemCreateUpdate(item, callbackID);
  367. else
  368. ourClient.SendAlertMessage("Unable to create inventory item");
  369. m_transactions.RemoveXferUploader(m_transactionID);
  370. }
  371. }
  372. }