AssetXferUploader.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 System.Collections.Generic;
  31. using log4net;
  32. using OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.Framework.Scenes;
  36. using OpenSim.Services.Interfaces;
  37. using PermissionMask = OpenSim.Framework.PermissionMask;
  38. namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
  39. {
  40. public class AssetXferUploader
  41. {
  42. private List<UUID> defaultIDs = new List<UUID> {
  43. // Viewer's notion of the default texture
  44. new UUID("5748decc-f629-461c-9a36-a35a221fe21f"), // others == default blank
  45. new UUID("7ca39b4c-bd19-4699-aff7-f93fd03d3e7b"), // hair
  46. new UUID("6522e74d-1660-4e7f-b601-6f48c1659a77"), // eyes
  47. new UUID("c228d1cf-4b5d-4ba8-84f4-899a0796aa97"), // skin
  48. new UUID("8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"), // transparency for alpha
  49. // opensim assets textures possibly obsolete now
  50. new UUID("00000000-0000-1111-9999-000000000010"),
  51. new UUID("00000000-0000-1111-9999-000000000011"),
  52. new UUID("00000000-0000-1111-9999-000000000012"),
  53. // other transparency defined in assets
  54. new UUID("3a367d1c-bef1-6d43-7595-e88c1e3aadb3"),
  55. new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594"),
  56. };
  57. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  58. /// <summary>
  59. /// Upload state.
  60. /// </summary>
  61. /// <remarks>
  62. /// New -> Uploading -> Complete
  63. /// </remarks>
  64. private enum UploadState
  65. {
  66. New,
  67. Uploading,
  68. Complete
  69. }
  70. /// <summary>
  71. /// Reference to the object that holds this uploader. Used to remove ourselves from it's list if we
  72. /// are performing a delayed update.
  73. /// </summary>
  74. AgentAssetTransactions m_transactions;
  75. private UploadState m_uploadState = UploadState.New;
  76. private AssetBase m_asset;
  77. private UUID InventFolder = UUID.Zero;
  78. private sbyte invType = 0;
  79. private bool m_createItem;
  80. private uint m_createItemCallback;
  81. private bool m_updateItem;
  82. private InventoryItemBase m_updateItemData;
  83. private bool m_updateTaskItem;
  84. private TaskInventoryItem m_updateTaskItemData;
  85. private string m_description = String.Empty;
  86. private bool m_dumpAssetToFile;
  87. private string m_name = String.Empty;
  88. // private bool m_storeLocal;
  89. private uint nextPerm = 0;
  90. private IClientAPI ourClient;
  91. private UUID m_transactionID;
  92. private sbyte type = 0;
  93. private byte wearableType = 0;
  94. private byte[] m_oldData = null;
  95. public ulong XferID;
  96. private Scene m_Scene;
  97. /// <summary>
  98. /// AssetXferUploader constructor
  99. /// </summary>
  100. /// <param name='transactions'>/param>
  101. /// <param name='scene'></param>
  102. /// <param name='transactionID'></param>
  103. /// <param name='dumpAssetToFile'>
  104. /// If true then when the asset is uploaded it is dumped to a file with the format
  105. /// String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat",
  106. /// now.Year, now.Month, now.Day, now.Hour, now.Minute,
  107. /// now.Second, m_asset.Name, m_asset.Type);
  108. /// for debugging purposes.
  109. /// </param>
  110. public AssetXferUploader(
  111. AgentAssetTransactions transactions, Scene scene, UUID transactionID, bool dumpAssetToFile)
  112. {
  113. m_asset = new AssetBase();
  114. m_transactions = transactions;
  115. m_transactionID = transactionID;
  116. m_Scene = scene;
  117. m_dumpAssetToFile = dumpAssetToFile;
  118. }
  119. /// <summary>
  120. /// Process transfer data received from the client.
  121. /// </summary>
  122. /// <param name="xferID"></param>
  123. /// <param name="packetID"></param>
  124. /// <param name="data"></param>
  125. /// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns>
  126. public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data)
  127. {
  128. // m_log.DebugFormat(
  129. // "[ASSET XFER UPLOADER]: Received packet {0} for xfer {1} (data length {2})",
  130. // packetID, xferID, data.Length);
  131. if (XferID == xferID)
  132. {
  133. lock (this)
  134. {
  135. int assetLength = m_asset.Data.Length;
  136. int dataLength = data.Length;
  137. if (m_asset.Data.Length > 1)
  138. {
  139. byte[] destinationArray = new byte[assetLength + dataLength];
  140. Array.Copy(m_asset.Data, 0, destinationArray, 0, assetLength);
  141. Array.Copy(data, 0, destinationArray, assetLength, dataLength);
  142. m_asset.Data = destinationArray;
  143. }
  144. else
  145. {
  146. if (dataLength > 4)
  147. {
  148. byte[] buffer2 = new byte[dataLength - 4];
  149. Array.Copy(data, 4, buffer2, 0, dataLength - 4);
  150. m_asset.Data = buffer2;
  151. }
  152. }
  153. }
  154. ourClient.SendConfirmXfer(xferID, packetID);
  155. if ((packetID & 0x80000000) != 0)
  156. {
  157. SendCompleteMessage();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// <summary>
  164. /// Start asset transfer from the client
  165. /// </summary>
  166. /// <param name="remoteClient"></param>
  167. /// <param name="assetID"></param>
  168. /// <param name="transaction"></param>
  169. /// <param name="type"></param>
  170. /// <param name="data">
  171. /// Optional data. If present then the asset is created immediately with this data
  172. /// rather than requesting an upload from the client. The data must be longer than 2 bytes.
  173. /// </param>
  174. /// <param name="storeLocal"></param>
  175. /// <param name="tempFile"></param>
  176. public void StartUpload(
  177. IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal,
  178. bool tempFile)
  179. {
  180. // m_log.DebugFormat(
  181. // "[ASSET XFER UPLOADER]: Initialised xfer from {0}, asset {1}, transaction {2}, type {3}, storeLocal {4}, tempFile {5}, already received data length {6}",
  182. // remoteClient.Name, assetID, transaction, type, storeLocal, tempFile, data.Length);
  183. lock (this)
  184. {
  185. if (m_uploadState != UploadState.New)
  186. {
  187. m_log.WarnFormat(
  188. "[ASSET XFER UPLOADER]: Tried to start upload of asset {0}, transaction {1} for {2} but this is already in state {3}. Aborting.",
  189. assetID, transaction, remoteClient.Name, m_uploadState);
  190. return;
  191. }
  192. m_uploadState = UploadState.Uploading;
  193. }
  194. ourClient = remoteClient;
  195. m_asset.FullID = assetID;
  196. m_asset.Type = type;
  197. m_asset.CreatorID = remoteClient.AgentId.ToString();
  198. m_asset.Data = data;
  199. m_asset.Local = storeLocal;
  200. m_asset.Temporary = tempFile;
  201. // m_storeLocal = storeLocal;
  202. if (m_asset.Data.Length > 2)
  203. {
  204. SendCompleteMessage();
  205. }
  206. else
  207. {
  208. RequestStartXfer();
  209. }
  210. }
  211. protected void RequestStartXfer()
  212. {
  213. XferID = Util.GetNextXferID();
  214. // m_log.DebugFormat(
  215. // "[ASSET XFER UPLOADER]: Requesting Xfer of asset {0}, type {1}, transfer id {2} from {3}",
  216. // m_asset.FullID, m_asset.Type, XferID, ourClient.Name);
  217. ourClient.SendXferRequest(XferID, m_asset.Type, m_asset.FullID, 0, new byte[0]);
  218. }
  219. protected void SendCompleteMessage()
  220. {
  221. // We must lock in order to avoid a race with a separate thread dealing with an inventory item or create
  222. // message from other client UDP.
  223. lock (this)
  224. {
  225. m_uploadState = UploadState.Complete;
  226. ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID);
  227. if (m_createItem)
  228. {
  229. CompleteCreateItem(m_createItemCallback);
  230. }
  231. else if (m_updateItem)
  232. {
  233. CompleteItemUpdate(m_updateItemData);
  234. }
  235. else if (m_updateTaskItem)
  236. {
  237. CompleteTaskItemUpdate(m_updateTaskItemData);
  238. }
  239. else if (m_asset.Local)
  240. {
  241. m_Scene.AssetService.Store(m_asset);
  242. }
  243. }
  244. m_log.DebugFormat(
  245. "[ASSET XFER UPLOADER]: Uploaded asset {0} for transaction {1}",
  246. m_asset.FullID, m_transactionID);
  247. if (m_dumpAssetToFile)
  248. {
  249. DateTime now = DateTime.Now;
  250. string filename =
  251. String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat",
  252. now.Year, now.Month, now.Day, now.Hour, now.Minute,
  253. now.Second, m_asset.Name, m_asset.Type);
  254. SaveAssetToFile(filename, m_asset.Data);
  255. }
  256. }
  257. private void SaveAssetToFile(string filename, byte[] data)
  258. {
  259. string assetPath = "UserAssets";
  260. if (!Directory.Exists(assetPath))
  261. {
  262. Directory.CreateDirectory(assetPath);
  263. }
  264. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  265. BinaryWriter bw = new BinaryWriter(fs);
  266. bw.Write(data);
  267. bw.Close();
  268. fs.Close();
  269. }
  270. public void RequestCreateInventoryItem(IClientAPI remoteClient,
  271. UUID folderID, uint callbackID,
  272. string description, string name, sbyte invType,
  273. sbyte type, byte wearableType, uint nextOwnerMask)
  274. {
  275. InventFolder = folderID;
  276. m_name = name;
  277. m_description = description;
  278. this.type = type;
  279. this.invType = invType;
  280. this.wearableType = wearableType;
  281. nextPerm = nextOwnerMask;
  282. m_asset.Name = name;
  283. m_asset.Description = description;
  284. m_asset.Type = type;
  285. // We must lock to avoid a race with a separate thread uploading the asset.
  286. lock (this)
  287. {
  288. if (m_uploadState == UploadState.Complete)
  289. {
  290. CompleteCreateItem(callbackID);
  291. }
  292. else
  293. {
  294. m_createItem = true; //set flag so the inventory item is created when upload is complete
  295. m_createItemCallback = callbackID;
  296. }
  297. }
  298. }
  299. public void RequestUpdateInventoryItem(IClientAPI remoteClient, InventoryItemBase item)
  300. {
  301. // We must lock to avoid a race with a separate thread uploading the asset.
  302. lock (this)
  303. {
  304. m_asset.Name = item.Name;
  305. m_asset.Description = item.Description;
  306. m_asset.Type = (sbyte)item.AssetType;
  307. // remove redundante m_Scene.InventoryService.UpdateItem
  308. // if uploadState == UploadState.Complete)
  309. // if (m_asset.FullID != UUID.Zero)
  310. // {
  311. // We must always store the item at this point even if the asset hasn't finished uploading, in order
  312. // to avoid a race condition when the appearance module retrieves the item to set the asset id in
  313. // the AvatarAppearance structure.
  314. // item.AssetID = m_asset.FullID;
  315. // m_Scene.InventoryService.UpdateItem(item);
  316. // }
  317. if (m_uploadState == UploadState.Complete)
  318. {
  319. CompleteItemUpdate(item);
  320. }
  321. else
  322. {
  323. // do it here to avoid the eventual race condition
  324. if (m_asset.FullID != UUID.Zero)
  325. {
  326. // We must always store the item at this point even if the asset hasn't finished uploading, in order
  327. // to avoid a race condition when the appearance module retrieves the item to set the asset id in
  328. // the AvatarAppearance structure.
  329. item.AssetID = m_asset.FullID;
  330. m_Scene.InventoryService.UpdateItem(item);
  331. }
  332. // m_log.DebugFormat(
  333. // "[ASSET XFER UPLOADER]: Holding update inventory item request {0} for {1} pending completion of asset xfer for transaction {2}",
  334. // item.Name, remoteClient.Name, transactionID);
  335. m_updateItem = true;
  336. m_updateItemData = item;
  337. }
  338. }
  339. }
  340. public void RequestUpdateTaskInventoryItem(IClientAPI remoteClient, TaskInventoryItem taskItem)
  341. {
  342. // We must lock to avoid a race with a separate thread uploading the asset.
  343. lock (this)
  344. {
  345. m_asset.Name = taskItem.Name;
  346. m_asset.Description = taskItem.Description;
  347. m_asset.Type = (sbyte)taskItem.Type;
  348. taskItem.AssetID = m_asset.FullID;
  349. if (m_uploadState == UploadState.Complete)
  350. {
  351. CompleteTaskItemUpdate(taskItem);
  352. }
  353. else
  354. {
  355. m_updateTaskItem = true;
  356. m_updateTaskItemData = taskItem;
  357. }
  358. }
  359. }
  360. /// <summary>
  361. /// Store the asset for the given item when it has been uploaded.
  362. /// </summary>
  363. /// <param name="item"></param>
  364. private void CompleteItemUpdate(InventoryItemBase item)
  365. {
  366. // m_log.DebugFormat(
  367. // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier item update for {1} for {2}",
  368. // m_asset.FullID, item.Name, ourClient.Name);
  369. ValidateAssets();
  370. m_Scene.AssetService.Store(m_asset);
  371. if (m_asset.FullID != UUID.Zero)
  372. {
  373. item.AssetID = m_asset.FullID;
  374. m_Scene.InventoryService.UpdateItem(item);
  375. }
  376. ourClient.SendInventoryItemCreateUpdate(item, m_transactionID, 0);
  377. m_transactions.RemoveXferUploader(m_transactionID);
  378. m_Scene.EventManager.TriggerOnNewInventoryItemUploadComplete(item, 0);
  379. }
  380. /// <summary>
  381. /// Store the asset for the given task item when it has been uploaded.
  382. /// </summary>
  383. /// <param name="taskItem"></param>
  384. private void CompleteTaskItemUpdate(TaskInventoryItem taskItem)
  385. {
  386. // m_log.DebugFormat(
  387. // "[ASSET XFER UPLOADER]: Storing asset {0} for earlier task item update for {1} for {2}",
  388. // m_asset.FullID, taskItem.Name, ourClient.Name);
  389. ValidateAssets();
  390. m_Scene.AssetService.Store(m_asset);
  391. m_transactions.RemoveXferUploader(m_transactionID);
  392. }
  393. private void CompleteCreateItem(uint callbackID)
  394. {
  395. ValidateAssets();
  396. m_Scene.AssetService.Store(m_asset);
  397. InventoryItemBase item = new InventoryItemBase();
  398. item.Owner = ourClient.AgentId;
  399. item.CreatorId = ourClient.AgentId.ToString();
  400. item.ID = UUID.Random();
  401. item.AssetID = m_asset.FullID;
  402. item.Description = m_description;
  403. item.Name = m_name;
  404. item.AssetType = type;
  405. item.InvType = invType;
  406. item.Folder = InventFolder;
  407. item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
  408. item.CurrentPermissions = item.BasePermissions;
  409. item.GroupPermissions=0;
  410. item.EveryOnePermissions=0;
  411. item.NextPermissions = nextPerm;
  412. item.Flags = (uint) wearableType;
  413. item.CreationDate = Util.UnixTimeSinceEpoch();
  414. m_log.DebugFormat("[XFER]: Created item {0} with asset {1}",
  415. item.ID, item.AssetID);
  416. if (m_Scene.AddInventoryItem(item))
  417. ourClient.SendInventoryItemCreateUpdate(item, m_transactionID, callbackID);
  418. else
  419. ourClient.SendAlertMessage("Unable to create inventory item");
  420. m_transactions.RemoveXferUploader(m_transactionID);
  421. }
  422. private void ValidateAssets()
  423. {
  424. if (m_asset.Type == (sbyte)CustomAssetType.AnimationSet)
  425. {
  426. AnimationSet animSet = new AnimationSet(m_asset.Data);
  427. bool allOk = animSet.Validate(x => {
  428. int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, x);
  429. int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
  430. if ((perms & required) != required)
  431. return false;
  432. return true;
  433. });
  434. if (!allOk)
  435. m_asset.Data = animSet.ToBytes();
  436. }
  437. if (m_asset.Type == (sbyte)AssetType.Clothing ||
  438. m_asset.Type == (sbyte)AssetType.Bodypart)
  439. {
  440. string content = System.Text.Encoding.ASCII.GetString(m_asset.Data);
  441. string[] lines = content.Split(new char[] {'\n'});
  442. List<string> validated = new List<string>();
  443. Dictionary<int, UUID> allowed = ExtractTexturesFromOldData();
  444. int textures = 0;
  445. foreach (string line in lines)
  446. {
  447. try
  448. {
  449. if (line.StartsWith("textures "))
  450. {
  451. textures = Convert.ToInt32(line.Substring(9));
  452. validated.Add(line);
  453. }
  454. else if (textures > 0)
  455. {
  456. string[] parts = line.Split(new char[] {' '});
  457. UUID tx = new UUID(parts[1]);
  458. int id = Convert.ToInt32(parts[0]);
  459. if (defaultIDs.Contains(tx) || tx == UUID.Zero ||
  460. (allowed.ContainsKey(id) && allowed[id] == tx))
  461. {
  462. validated.Add(parts[0] + " " + tx.ToString());
  463. }
  464. else
  465. {
  466. int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, tx);
  467. int full = (int)(PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Copy);
  468. if ((perms & full) != full)
  469. {
  470. m_log.ErrorFormat("[ASSET UPLOADER]: REJECTED update with texture {0} from {1} because they do not own the texture", tx, ourClient.AgentId);
  471. validated.Add(parts[0] + " " + UUID.Zero.ToString());
  472. }
  473. else
  474. {
  475. validated.Add(line);
  476. }
  477. }
  478. textures--;
  479. }
  480. else
  481. {
  482. validated.Add(line);
  483. }
  484. }
  485. catch
  486. {
  487. // If it's malformed, skip it
  488. }
  489. }
  490. string final = String.Join("\n", validated.ToArray());
  491. m_asset.Data = System.Text.Encoding.ASCII.GetBytes(final);
  492. }
  493. }
  494. /// <summary>
  495. /// Get the asset data uploaded in this transfer.
  496. /// </summary>
  497. /// <returns>null if the asset has not finished uploading</returns>
  498. public AssetBase GetAssetData()
  499. {
  500. if (m_uploadState == UploadState.Complete)
  501. {
  502. ValidateAssets();
  503. return m_asset;
  504. }
  505. return null;
  506. }
  507. public void SetOldData(byte[] d)
  508. {
  509. m_oldData = d;
  510. }
  511. private Dictionary<int,UUID> ExtractTexturesFromOldData()
  512. {
  513. Dictionary<int,UUID> result = new Dictionary<int,UUID>();
  514. if (m_oldData == null)
  515. return result;
  516. string content = System.Text.Encoding.ASCII.GetString(m_oldData);
  517. string[] lines = content.Split(new char[] {'\n'});
  518. int textures = 0;
  519. foreach (string line in lines)
  520. {
  521. try
  522. {
  523. if (line.StartsWith("textures "))
  524. {
  525. textures = Convert.ToInt32(line.Substring(9));
  526. }
  527. else if (textures > 0)
  528. {
  529. string[] parts = line.Split(new char[] {' '});
  530. UUID tx = new UUID(parts[1]);
  531. int id = Convert.ToInt32(parts[0]);
  532. result[id] = tx;
  533. textures--;
  534. }
  535. }
  536. catch
  537. {
  538. // If it's malformed, skip it
  539. }
  540. }
  541. return result;
  542. }
  543. }
  544. }