AssetXferUploader.cs 16 KB

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