1
0

SimClient.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. /*
  2. Copyright (c) OpenSim project, http://osgrid.org/
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. * * Neither the name of the <organization> nor the
  12. * names of its contributors may be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY <copyright holder> ``AS IS'' AND ANY
  16. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
  19. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. using System;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using libsecondlife;
  30. using libsecondlife.Packets;
  31. using System.Net;
  32. using System.Net.Sockets;
  33. using System.IO;
  34. using System.Threading;
  35. using System.Timers;
  36. using OpenSim.Framework.Interfaces;
  37. using OpenSim.Framework.Assets;
  38. using OpenSim.Framework.Inventory;
  39. using OpenSim.Framework.Utilities;
  40. using OpenSim.world;
  41. using OpenSim.Assets;
  42. namespace OpenSim
  43. {
  44. public delegate bool PacketMethod(SimClient simClient, Packet packet);
  45. /// <summary>
  46. /// Handles new client connections
  47. /// Constructor takes a single Packet and authenticates everything
  48. /// </summary>
  49. public class SimClient
  50. {
  51. public LLUUID AgentID;
  52. public LLUUID SessionID;
  53. public LLUUID SecureSessionID = LLUUID.Zero;
  54. public uint CircuitCode;
  55. public world.Avatar ClientAvatar;
  56. private UseCircuitCodePacket cirpack;
  57. private Thread ClientThread;
  58. public EndPoint userEP;
  59. private BlockingQueue<QueItem> PacketQueue;
  60. private Dictionary<uint, uint> PendingAcks = new Dictionary<uint, uint>();
  61. private Dictionary<uint, Packet> NeedAck = new Dictionary<uint, Packet>();
  62. //private Dictionary<LLUUID, AssetBase> UploadedAssets = new Dictionary<LLUUID, AssetBase>();
  63. private System.Timers.Timer AckTimer;
  64. private uint Sequence = 0;
  65. private object SequenceLock = new object();
  66. private const int MAX_APPENDED_ACKS = 10;
  67. private const int RESEND_TIMEOUT = 4000;
  68. private const int MAX_SEQUENCE = 0xFFFFFF;
  69. private AgentAssetUpload UploadAssets;
  70. private LLUUID newAssetFolder = LLUUID.Zero;
  71. private bool debug = false;
  72. private World m_world;
  73. private Dictionary<uint, SimClient> m_clientThreads;
  74. private AssetCache m_assetCache;
  75. private IGridServer m_gridServer;
  76. private IUserServer m_userServer = null;
  77. private OpenSimNetworkHandler m_application;
  78. private InventoryCache m_inventoryCache;
  79. private bool m_sandboxMode;
  80. private int cachedtextureserial = 0;
  81. protected static Dictionary<PacketType, PacketMethod> PacketHandlers = new Dictionary<PacketType, PacketMethod>(); //Global/static handlers for all clients
  82. protected Dictionary<PacketType, PacketMethod> m_packetHandlers = new Dictionary<PacketType, PacketMethod>(); //local handlers for this instance
  83. public IUserServer UserServer
  84. {
  85. set
  86. {
  87. this.m_userServer = value;
  88. }
  89. }
  90. public SimClient(EndPoint remoteEP, UseCircuitCodePacket initialcirpack, World world, Dictionary<uint, SimClient> clientThreads, AssetCache assetCache, IGridServer gridServer, OpenSimNetworkHandler application, InventoryCache inventoryCache, bool sandboxMode)
  91. {
  92. m_world = world;
  93. m_clientThreads = clientThreads;
  94. m_assetCache = assetCache;
  95. m_gridServer = gridServer;
  96. m_application = application;
  97. m_inventoryCache = inventoryCache;
  98. m_sandboxMode = sandboxMode;
  99. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs - Started up new client thread to handle incoming request");
  100. cirpack = initialcirpack;
  101. userEP = remoteEP;
  102. PacketQueue = new BlockingQueue<QueItem>();
  103. this.UploadAssets = new AgentAssetUpload(this, m_assetCache, m_inventoryCache);
  104. AckTimer = new System.Timers.Timer(500);
  105. AckTimer.Elapsed += new ElapsedEventHandler(AckTimer_Elapsed);
  106. AckTimer.Start();
  107. this.RegisterLocalPacketHandlers();
  108. ClientThread = new Thread(new ThreadStart(AuthUser));
  109. ClientThread.IsBackground = true;
  110. ClientThread.Start();
  111. }
  112. protected virtual void RegisterLocalPacketHandlers()
  113. {
  114. this.AddLocalPacketHandler(PacketType.LogoutRequest, this.Logout);
  115. this.AddLocalPacketHandler(PacketType.AgentCachedTexture, this.AgentTextureCached);
  116. this.AddLocalPacketHandler(PacketType.MultipleObjectUpdate, this.MultipleObjUpdate);
  117. }
  118. public static bool AddPacketHandler(PacketType packetType, PacketMethod handler)
  119. {
  120. bool result = false;
  121. lock (PacketHandlers)
  122. {
  123. if (!PacketHandlers.ContainsKey(packetType))
  124. {
  125. PacketHandlers.Add(packetType, handler);
  126. result = true;
  127. }
  128. }
  129. return result;
  130. }
  131. public bool AddLocalPacketHandler(PacketType packetType, PacketMethod handler)
  132. {
  133. bool result = false;
  134. lock (m_packetHandlers)
  135. {
  136. if (!m_packetHandlers.ContainsKey(packetType))
  137. {
  138. m_packetHandlers.Add(packetType, handler);
  139. result = true;
  140. }
  141. }
  142. return result;
  143. }
  144. protected virtual bool ProcessPacketMethod(Packet packet)
  145. {
  146. bool result = false;
  147. bool found = false;
  148. PacketMethod method;
  149. if (m_packetHandlers.TryGetValue(packet.Type, out method))
  150. {
  151. //there is a local handler for this packet type
  152. result = method(this, packet);
  153. }
  154. else
  155. {
  156. //there is not a local handler so see if there is a Global handler
  157. lock (PacketHandlers)
  158. {
  159. found = PacketHandlers.TryGetValue(packet.Type, out method);
  160. }
  161. if (found)
  162. {
  163. result = method(this, packet);
  164. }
  165. }
  166. return result;
  167. }
  168. private void ack_pack(Packet Pack)
  169. {
  170. if (Pack.Header.Reliable)
  171. {
  172. libsecondlife.Packets.PacketAckPacket ack_it = new PacketAckPacket();
  173. ack_it.Packets = new PacketAckPacket.PacketsBlock[1];
  174. ack_it.Packets[0] = new PacketAckPacket.PacketsBlock();
  175. ack_it.Packets[0].ID = Pack.Header.Sequence;
  176. ack_it.Header.Reliable = false;
  177. OutPacket(ack_it);
  178. }
  179. /*
  180. if (Pack.Header.Reliable)
  181. {
  182. lock (PendingAcks)
  183. {
  184. uint sequence = (uint)Pack.Header.Sequence;
  185. if (!PendingAcks.ContainsKey(sequence)) { PendingAcks[sequence] = sequence; }
  186. }
  187. }*/
  188. }
  189. protected virtual void ProcessInPacket(Packet Pack)
  190. {
  191. ack_pack(Pack);
  192. if (debug)
  193. {
  194. if (Pack.Type != PacketType.AgentUpdate)
  195. {
  196. Console.WriteLine(Pack.Type.ToString());
  197. }
  198. }
  199. if (this.ProcessPacketMethod(Pack))
  200. {
  201. //there is a handler registered that handled this packet type
  202. return;
  203. }
  204. else
  205. {
  206. System.Text.Encoding _enc = System.Text.Encoding.ASCII;
  207. switch (Pack.Type)
  208. {
  209. case PacketType.CompleteAgentMovement:
  210. ClientAvatar.CompleteMovement(m_world);
  211. ClientAvatar.SendInitialPosition();
  212. break;
  213. case PacketType.RegionHandshakeReply:
  214. m_world.SendLayerData(this);
  215. break;
  216. case PacketType.AgentWearablesRequest:
  217. ClientAvatar.SendInitialAppearance();
  218. foreach (SimClient client in m_clientThreads.Values)
  219. {
  220. if (client.AgentID != this.AgentID)
  221. {
  222. ObjectUpdatePacket objupdate = client.ClientAvatar.CreateUpdatePacket();
  223. this.OutPacket(objupdate);
  224. client.ClientAvatar.SendAppearanceToOtherAgent(this);
  225. }
  226. }
  227. m_world.GetInitialPrims(this);
  228. break;
  229. case PacketType.AgentIsNowWearing:
  230. AgentIsNowWearingPacket wear = (AgentIsNowWearingPacket)Pack;
  231. //Console.WriteLine(Pack.ToString());
  232. break;
  233. case PacketType.AgentSetAppearance:
  234. AgentSetAppearancePacket appear = (AgentSetAppearancePacket)Pack;
  235. // Console.WriteLine(appear.ToString());
  236. this.ClientAvatar.SetAppearance(appear);
  237. break;
  238. case PacketType.ObjectAdd:
  239. m_world.AddNewPrim((ObjectAddPacket)Pack, this);
  240. break;
  241. case PacketType.ObjectLink:
  242. OpenSim.Framework.Console.MainConsole.Instance.WriteLine(Pack.ToString());
  243. ObjectLinkPacket link = (ObjectLinkPacket)Pack;
  244. uint parentprimid = 0;
  245. OpenSim.world.Primitive parentprim = null;
  246. if (link.ObjectData.Length > 1)
  247. {
  248. parentprimid = link.ObjectData[0].ObjectLocalID;
  249. foreach (Entity ent in m_world.Entities.Values)
  250. {
  251. if (ent.localid == parentprimid)
  252. {
  253. parentprim = (OpenSim.world.Primitive)ent;
  254. }
  255. }
  256. for (int i = 1; i < link.ObjectData.Length; i++)
  257. {
  258. foreach (Entity ent in m_world.Entities.Values)
  259. {
  260. if (ent.localid == link.ObjectData[i].ObjectLocalID)
  261. {
  262. ((OpenSim.world.Primitive)ent).MakeParent(parentprim);
  263. }
  264. }
  265. }
  266. }
  267. break;
  268. case PacketType.ObjectScale:
  269. OpenSim.Framework.Console.MainConsole.Instance.WriteLine(Pack.ToString());
  270. break;
  271. case PacketType.ObjectShape:
  272. ObjectShapePacket shape = (ObjectShapePacket)Pack;
  273. for (int i = 0; i < shape.ObjectData.Length; i++)
  274. {
  275. foreach (Entity ent in m_world.Entities.Values)
  276. {
  277. if (ent.localid == shape.ObjectData[i].ObjectLocalID)
  278. {
  279. ((OpenSim.world.Primitive)ent).UpdateShape(shape.ObjectData[i]);
  280. }
  281. }
  282. }
  283. break;
  284. case PacketType.RequestImage:
  285. RequestImagePacket imageRequest = (RequestImagePacket)Pack;
  286. for (int i = 0; i < imageRequest.RequestImage.Length; i++)
  287. {
  288. m_assetCache.AddTextureRequest(this, imageRequest.RequestImage[i].Image);
  289. }
  290. break;
  291. case PacketType.TransferRequest:
  292. //Console.WriteLine("OpenSimClient.cs:ProcessInPacket() - Got transfer request");
  293. TransferRequestPacket transfer = (TransferRequestPacket)Pack;
  294. m_assetCache.AddAssetRequest(this, transfer);
  295. break;
  296. case PacketType.AgentUpdate:
  297. ClientAvatar.HandleUpdate((AgentUpdatePacket)Pack);
  298. break;
  299. case PacketType.ObjectImage:
  300. ObjectImagePacket imagePack = (ObjectImagePacket)Pack;
  301. for (int i = 0; i < imagePack.ObjectData.Length; i++)
  302. {
  303. foreach (Entity ent in m_world.Entities.Values)
  304. {
  305. if (ent.localid == imagePack.ObjectData[i].ObjectLocalID)
  306. {
  307. ((OpenSim.world.Primitive)ent).UpdateTexture(imagePack.ObjectData[i].TextureEntry);
  308. }
  309. }
  310. }
  311. break;
  312. case PacketType.ObjectFlagUpdate:
  313. ObjectFlagUpdatePacket flags = (ObjectFlagUpdatePacket)Pack;
  314. foreach (Entity ent in m_world.Entities.Values)
  315. {
  316. if (ent.localid == flags.AgentData.ObjectLocalID)
  317. {
  318. ((OpenSim.world.Primitive)ent).UpdateObjectFlags(flags);
  319. }
  320. }
  321. break;
  322. case PacketType.AssetUploadRequest:
  323. AssetUploadRequestPacket request = (AssetUploadRequestPacket)Pack;
  324. this.UploadAssets.HandleUploadPacket(request, request.AssetBlock.TransactionID.Combine(this.SecureSessionID));
  325. break;
  326. case PacketType.RequestXfer:
  327. //Console.WriteLine(Pack.ToString());
  328. break;
  329. case PacketType.SendXferPacket:
  330. this.UploadAssets.HandleXferPacket((SendXferPacketPacket)Pack);
  331. break;
  332. case PacketType.CreateInventoryFolder:
  333. CreateInventoryFolderPacket invFolder = (CreateInventoryFolderPacket)Pack;
  334. m_inventoryCache.CreateNewInventoryFolder(this, invFolder.FolderData.FolderID, (ushort)invFolder.FolderData.Type, Helpers.FieldToString(invFolder.FolderData.Name), invFolder.FolderData.ParentID);
  335. //Console.WriteLine(Pack.ToString());
  336. break;
  337. case PacketType.CreateInventoryItem:
  338. //Console.WriteLine(Pack.ToString());
  339. CreateInventoryItemPacket createItem = (CreateInventoryItemPacket)Pack;
  340. if (createItem.InventoryBlock.TransactionID != LLUUID.Zero)
  341. {
  342. this.UploadAssets.CreateInventoryItem(createItem);
  343. }
  344. else
  345. {
  346. // Console.Write(Pack.ToString());
  347. this.CreateInventoryItem(createItem);
  348. }
  349. break;
  350. case PacketType.FetchInventory:
  351. //Console.WriteLine("fetch item packet");
  352. FetchInventoryPacket FetchInventory = (FetchInventoryPacket)Pack;
  353. m_inventoryCache.FetchInventory(this, FetchInventory);
  354. break;
  355. case PacketType.FetchInventoryDescendents:
  356. FetchInventoryDescendentsPacket Fetch = (FetchInventoryDescendentsPacket)Pack;
  357. m_inventoryCache.FetchInventoryDescendents(this, Fetch);
  358. break;
  359. case PacketType.UpdateInventoryItem:
  360. UpdateInventoryItemPacket update = (UpdateInventoryItemPacket)Pack;
  361. //Console.WriteLine(Pack.ToString());
  362. for (int i = 0; i < update.InventoryData.Length; i++)
  363. {
  364. if (update.InventoryData[i].TransactionID != LLUUID.Zero)
  365. {
  366. AssetBase asset = m_assetCache.GetAsset(update.InventoryData[i].TransactionID.Combine(this.SecureSessionID));
  367. if (asset != null)
  368. {
  369. // Console.WriteLine("updating inventory item, found asset" + asset.FullID.ToStringHyphenated() + " already in cache");
  370. m_inventoryCache.UpdateInventoryItemAsset(this, update.InventoryData[i].ItemID, asset);
  371. }
  372. else
  373. {
  374. asset = this.UploadAssets.AddUploadToAssetCache(update.InventoryData[i].TransactionID);
  375. if (asset != null)
  376. {
  377. //Console.WriteLine("updating inventory item, adding asset" + asset.FullID.ToStringHyphenated() + " to cache");
  378. m_inventoryCache.UpdateInventoryItemAsset(this, update.InventoryData[i].ItemID, asset);
  379. }
  380. else
  381. {
  382. //Console.WriteLine("trying to update inventory item, but asset is null");
  383. }
  384. }
  385. }
  386. else
  387. {
  388. m_inventoryCache.UpdateInventoryItemDetails(this, update.InventoryData[i].ItemID, update.InventoryData[i]); ;
  389. }
  390. }
  391. break;
  392. case PacketType.ViewerEffect:
  393. ViewerEffectPacket viewer = (ViewerEffectPacket)Pack;
  394. foreach (SimClient client in m_clientThreads.Values)
  395. {
  396. if (client.AgentID != this.AgentID)
  397. {
  398. viewer.AgentData.AgentID = client.AgentID;
  399. viewer.AgentData.SessionID = client.SessionID;
  400. client.OutPacket(viewer);
  401. }
  402. }
  403. break;
  404. case PacketType.RequestTaskInventory:
  405. // Console.WriteLine(Pack.ToString());
  406. RequestTaskInventoryPacket requesttask = (RequestTaskInventoryPacket)Pack;
  407. ReplyTaskInventoryPacket replytask = new ReplyTaskInventoryPacket();
  408. bool foundent = false;
  409. foreach (Entity ent in m_world.Entities.Values)
  410. {
  411. if (ent.localid == requesttask.InventoryData.LocalID)
  412. {
  413. replytask.InventoryData.TaskID = ent.uuid;
  414. replytask.InventoryData.Serial = 0;
  415. replytask.InventoryData.Filename = new byte[0];
  416. foundent = true;
  417. }
  418. }
  419. if (foundent)
  420. {
  421. this.OutPacket(replytask);
  422. }
  423. break;
  424. case PacketType.UpdateTaskInventory:
  425. // Console.WriteLine(Pack.ToString());
  426. UpdateTaskInventoryPacket updatetask = (UpdateTaskInventoryPacket)Pack;
  427. AgentInventory myinventory = this.m_inventoryCache.GetAgentsInventory(this.AgentID);
  428. if (myinventory != null)
  429. {
  430. if (updatetask.UpdateData.Key == 0)
  431. {
  432. if (myinventory.InventoryItems[updatetask.InventoryData.ItemID] != null)
  433. {
  434. if (myinventory.InventoryItems[updatetask.InventoryData.ItemID].Type == 7)
  435. {
  436. LLUUID noteaid = myinventory.InventoryItems[updatetask.InventoryData.ItemID].AssetID;
  437. AssetBase assBase = this.m_assetCache.GetAsset(noteaid);
  438. if (assBase != null)
  439. {
  440. foreach (Entity ent in m_world.Entities.Values)
  441. {
  442. if (ent.localid == updatetask.UpdateData.LocalID)
  443. {
  444. if (ent is OpenSim.world.Primitive)
  445. {
  446. this.m_world.AddScript(ent, Helpers.FieldToString(assBase.Data));
  447. }
  448. }
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. break;
  456. case PacketType.AgentAnimation:
  457. AgentAnimationPacket AgentAni = (AgentAnimationPacket)Pack;
  458. for (int i = 0; i < AgentAni.AnimationList.Length; i++)
  459. {
  460. if (AgentAni.AnimationList[i].StartAnim)
  461. {
  462. ClientAvatar.current_anim = AgentAni.AnimationList[i].AnimID;
  463. ClientAvatar.anim_seq = 1;
  464. ClientAvatar.SendAnimPack();
  465. }
  466. }
  467. break;
  468. case PacketType.ObjectSelect:
  469. ObjectSelectPacket incomingselect = (ObjectSelectPacket)Pack;
  470. for (int i = 0; i < incomingselect.ObjectData.Length; i++)
  471. {
  472. foreach (Entity ent in m_world.Entities.Values)
  473. {
  474. if (ent.localid == incomingselect.ObjectData[i].ObjectLocalID)
  475. {
  476. ((OpenSim.world.Primitive)ent).GetProperites(this);
  477. break;
  478. }
  479. }
  480. }
  481. break;
  482. }
  483. }
  484. }
  485. private void ResendUnacked()
  486. {
  487. int now = Environment.TickCount;
  488. lock (NeedAck)
  489. {
  490. foreach (Packet packet in NeedAck.Values)
  491. {
  492. if ((now - packet.TickCount > RESEND_TIMEOUT) && (!packet.Header.Resent))
  493. {
  494. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Resending " + packet.Type.ToString() + " packet, " +
  495. (now - packet.TickCount) + "ms have passed");
  496. packet.Header.Resent = true;
  497. OutPacket(packet);
  498. }
  499. }
  500. }
  501. }
  502. private void SendAcks()
  503. {
  504. lock (PendingAcks)
  505. {
  506. if (PendingAcks.Count > 0)
  507. {
  508. if (PendingAcks.Count > 250)
  509. {
  510. // FIXME: Handle the odd case where we have too many pending ACKs queued up
  511. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Too many ACKs queued up!");
  512. return;
  513. }
  514. //OpenSim.Framework.Console.MainConsole.Instance.WriteLine("Sending PacketAck");
  515. int i = 0;
  516. PacketAckPacket acks = new PacketAckPacket();
  517. acks.Packets = new PacketAckPacket.PacketsBlock[PendingAcks.Count];
  518. foreach (uint ack in PendingAcks.Values)
  519. {
  520. acks.Packets[i] = new PacketAckPacket.PacketsBlock();
  521. acks.Packets[i].ID = ack;
  522. i++;
  523. }
  524. acks.Header.Reliable = false;
  525. OutPacket(acks);
  526. PendingAcks.Clear();
  527. }
  528. }
  529. }
  530. private void AckTimer_Elapsed(object sender, ElapsedEventArgs ea)
  531. {
  532. SendAcks();
  533. ResendUnacked();
  534. }
  535. protected virtual void ProcessOutPacket(Packet Pack)
  536. {
  537. // Keep track of when this packet was sent out
  538. Pack.TickCount = Environment.TickCount;
  539. if (!Pack.Header.Resent)
  540. {
  541. // Set the sequence number
  542. lock (SequenceLock)
  543. {
  544. if (Sequence >= MAX_SEQUENCE)
  545. Sequence = 1;
  546. else
  547. Sequence++;
  548. Pack.Header.Sequence = Sequence;
  549. }
  550. if (Pack.Header.Reliable) //DIRTY HACK
  551. {
  552. lock (NeedAck)
  553. {
  554. if (!NeedAck.ContainsKey(Pack.Header.Sequence))
  555. {
  556. NeedAck.Add(Pack.Header.Sequence, Pack);
  557. }
  558. else
  559. {
  560. // Client.Log("Attempted to add a duplicate sequence number (" +
  561. // packet.Header.Sequence + ") to the NeedAck dictionary for packet type " +
  562. // packet.Type.ToString(), Helpers.LogLevel.Warning);
  563. }
  564. }
  565. // Don't append ACKs to resent packets, in case that's what was causing the
  566. // delivery to fail
  567. if (!Pack.Header.Resent)
  568. {
  569. // Append any ACKs that need to be sent out to this packet
  570. lock (PendingAcks)
  571. {
  572. if (PendingAcks.Count > 0 && PendingAcks.Count < MAX_APPENDED_ACKS &&
  573. Pack.Type != PacketType.PacketAck &&
  574. Pack.Type != PacketType.LogoutRequest)
  575. {
  576. Pack.Header.AckList = new uint[PendingAcks.Count];
  577. int i = 0;
  578. foreach (uint ack in PendingAcks.Values)
  579. {
  580. Pack.Header.AckList[i] = ack;
  581. i++;
  582. }
  583. PendingAcks.Clear();
  584. Pack.Header.AppendedAcks = true;
  585. }
  586. }
  587. }
  588. }
  589. }
  590. byte[] ZeroOutBuffer = new byte[4096];
  591. byte[] sendbuffer;
  592. sendbuffer = Pack.ToBytes();
  593. try
  594. {
  595. if (Pack.Header.Zerocoded)
  596. {
  597. int packetsize = Helpers.ZeroEncode(sendbuffer, sendbuffer.Length, ZeroOutBuffer);
  598. m_application.SendPacketTo(ZeroOutBuffer, packetsize, SocketFlags.None, CircuitCode);//userEP);
  599. }
  600. else
  601. {
  602. m_application.SendPacketTo(sendbuffer, sendbuffer.Length, SocketFlags.None, CircuitCode); //userEP);
  603. }
  604. }
  605. catch (Exception)
  606. {
  607. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs:ProcessOutPacket() - WARNING: Socket exception occurred on connection " + userEP.ToString() + " - killing thread");
  608. ClientThread.Abort();
  609. }
  610. }
  611. public virtual void InPacket(Packet NewPack)
  612. {
  613. // Handle appended ACKs
  614. if (NewPack.Header.AppendedAcks)
  615. {
  616. lock (NeedAck)
  617. {
  618. foreach (uint ack in NewPack.Header.AckList)
  619. {
  620. NeedAck.Remove(ack);
  621. }
  622. }
  623. }
  624. // Handle PacketAck packets
  625. if (NewPack.Type == PacketType.PacketAck)
  626. {
  627. PacketAckPacket ackPacket = (PacketAckPacket)NewPack;
  628. lock (NeedAck)
  629. {
  630. foreach (PacketAckPacket.PacketsBlock block in ackPacket.Packets)
  631. {
  632. NeedAck.Remove(block.ID);
  633. }
  634. }
  635. }
  636. else if ((NewPack.Type == PacketType.StartPingCheck))
  637. {
  638. //reply to pingcheck
  639. libsecondlife.Packets.StartPingCheckPacket startPing = (libsecondlife.Packets.StartPingCheckPacket)NewPack;
  640. libsecondlife.Packets.CompletePingCheckPacket endPing = new CompletePingCheckPacket();
  641. endPing.PingID.PingID = startPing.PingID.PingID;
  642. OutPacket(endPing);
  643. }
  644. else
  645. {
  646. QueItem item = new QueItem();
  647. item.Packet = NewPack;
  648. item.Incoming = true;
  649. this.PacketQueue.Enqueue(item);
  650. }
  651. }
  652. public virtual void OutPacket(Packet NewPack)
  653. {
  654. QueItem item = new QueItem();
  655. item.Packet = NewPack;
  656. item.Incoming = false;
  657. this.PacketQueue.Enqueue(item);
  658. }
  659. protected virtual void ClientLoop()
  660. {
  661. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs:ClientLoop() - Entered loop");
  662. while (true)
  663. {
  664. QueItem nextPacket = PacketQueue.Dequeue();
  665. if (nextPacket.Incoming)
  666. {
  667. //is a incoming packet
  668. ProcessInPacket(nextPacket.Packet);
  669. }
  670. else
  671. {
  672. //is a out going packet
  673. ProcessOutPacket(nextPacket.Packet);
  674. }
  675. }
  676. }
  677. protected virtual void InitNewClient()
  678. {
  679. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs:InitNewClient() - Adding viewer agent to world");
  680. m_world.AddViewerAgent(this);
  681. world.Entity tempent = m_world.Entities[this.AgentID];
  682. this.ClientAvatar = (world.Avatar)tempent;
  683. }
  684. protected virtual void AuthUser()
  685. {
  686. AuthenticateResponse sessionInfo = m_gridServer.AuthenticateSession(cirpack.CircuitCode.SessionID, cirpack.CircuitCode.ID, cirpack.CircuitCode.Code);
  687. if (!sessionInfo.Authorised)
  688. {
  689. //session/circuit not authorised
  690. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs:AuthUser() - New user request denied to " + userEP.ToString());
  691. ClientThread.Abort();
  692. }
  693. else
  694. {
  695. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs:AuthUser() - Got authenticated connection from " + userEP.ToString());
  696. //session is authorised
  697. this.AgentID = cirpack.CircuitCode.ID;
  698. this.SessionID = cirpack.CircuitCode.SessionID;
  699. this.CircuitCode = cirpack.CircuitCode.Code;
  700. InitNewClient(); //shouldn't be called here as we might be a child agent and not want a full avatar
  701. this.ClientAvatar.firstname = sessionInfo.LoginInfo.First;
  702. this.ClientAvatar.lastname = sessionInfo.LoginInfo.Last;
  703. if (sessionInfo.LoginInfo.SecureSession != LLUUID.Zero)
  704. {
  705. this.SecureSessionID = sessionInfo.LoginInfo.SecureSession;
  706. }
  707. // Create Inventory, currently only works for sandbox mode
  708. if (m_sandboxMode)
  709. {
  710. AgentInventory inventory = null;
  711. if (sessionInfo.LoginInfo.InventoryFolder != null)
  712. {
  713. inventory = this.CreateInventory(sessionInfo.LoginInfo.InventoryFolder);
  714. if (sessionInfo.LoginInfo.BaseFolder != null)
  715. {
  716. if (!inventory.HasFolder(sessionInfo.LoginInfo.BaseFolder))
  717. {
  718. m_inventoryCache.CreateNewInventoryFolder(this, sessionInfo.LoginInfo.BaseFolder);
  719. }
  720. this.newAssetFolder = sessionInfo.LoginInfo.BaseFolder;
  721. AssetBase[] inventorySet = m_assetCache.CreateNewInventorySet(this.AgentID);
  722. if (inventorySet != null)
  723. {
  724. for (int i = 0; i < inventorySet.Length; i++)
  725. {
  726. if (inventorySet[i] != null)
  727. {
  728. m_inventoryCache.AddNewInventoryItem(this, sessionInfo.LoginInfo.BaseFolder, inventorySet[i]);
  729. }
  730. }
  731. }
  732. }
  733. }
  734. }
  735. ClientLoop();
  736. }
  737. }
  738. #region Packet handlers
  739. protected virtual bool Logout(SimClient simClient, Packet packet)
  740. {
  741. OpenSim.Framework.Console.MainConsole.Instance.WriteLine("OpenSimClient.cs:ProcessInPacket() - Got a logout request");
  742. //send reply to let the client logout
  743. LogoutReplyPacket logReply = new LogoutReplyPacket();
  744. logReply.AgentData.AgentID = this.AgentID;
  745. logReply.AgentData.SessionID = this.SessionID;
  746. logReply.InventoryData = new LogoutReplyPacket.InventoryDataBlock[1];
  747. logReply.InventoryData[0] = new LogoutReplyPacket.InventoryDataBlock();
  748. logReply.InventoryData[0].ItemID = LLUUID.Zero;
  749. OutPacket(logReply);
  750. //tell all clients to kill our object
  751. KillObjectPacket kill = new KillObjectPacket();
  752. kill.ObjectData = new KillObjectPacket.ObjectDataBlock[1];
  753. kill.ObjectData[0] = new KillObjectPacket.ObjectDataBlock();
  754. kill.ObjectData[0].ID = this.ClientAvatar.localid;
  755. foreach (SimClient client in m_clientThreads.Values)
  756. {
  757. client.OutPacket(kill);
  758. }
  759. if (this.m_userServer != null)
  760. {
  761. this.m_inventoryCache.ClientLeaving(this.AgentID, this.m_userServer);
  762. }
  763. else
  764. {
  765. this.m_inventoryCache.ClientLeaving(this.AgentID, null);
  766. }
  767. m_gridServer.LogoutSession(this.SessionID, this.AgentID, this.CircuitCode);
  768. /*lock (m_world.Entities)
  769. {
  770. m_world.Entities.Remove(this.AgentID);
  771. }*/
  772. m_world.RemoveViewerAgent(this);
  773. //need to do other cleaning up here too
  774. m_clientThreads.Remove(this.CircuitCode);
  775. m_application.RemoveClientCircuit(this.CircuitCode);
  776. this.ClientThread.Abort();
  777. return true;
  778. }
  779. protected bool AgentTextureCached(SimClient simclient, Packet packet)
  780. {
  781. // Console.WriteLine(packet.ToString());
  782. AgentCachedTexturePacket chechedtex = (AgentCachedTexturePacket)packet;
  783. AgentCachedTextureResponsePacket cachedresp = new AgentCachedTextureResponsePacket();
  784. cachedresp.AgentData.AgentID = this.AgentID;
  785. cachedresp.AgentData.SessionID = this.SessionID;
  786. cachedresp.AgentData.SerialNum = this.cachedtextureserial;
  787. this.cachedtextureserial++;
  788. cachedresp.WearableData = new AgentCachedTextureResponsePacket.WearableDataBlock[chechedtex.WearableData.Length];
  789. for (int i = 0; i < chechedtex.WearableData.Length; i++)
  790. {
  791. cachedresp.WearableData[i] = new AgentCachedTextureResponsePacket.WearableDataBlock();
  792. cachedresp.WearableData[i].TextureIndex = chechedtex.WearableData[i].TextureIndex;
  793. cachedresp.WearableData[i].TextureID = LLUUID.Zero;
  794. cachedresp.WearableData[i].HostName = new byte[0];
  795. }
  796. this.OutPacket(cachedresp);
  797. return true;
  798. }
  799. protected bool MultipleObjUpdate(SimClient simClient, Packet packet)
  800. {
  801. MultipleObjectUpdatePacket multipleupdate = (MultipleObjectUpdatePacket)packet;
  802. for (int i = 0; i < multipleupdate.ObjectData.Length; i++)
  803. {
  804. if (multipleupdate.ObjectData[i].Type == 9) //change position
  805. {
  806. libsecondlife.LLVector3 pos = new LLVector3(multipleupdate.ObjectData[i].Data, 0);
  807. foreach (Entity ent in m_world.Entities.Values)
  808. {
  809. if (ent.localid == multipleupdate.ObjectData[i].ObjectLocalID)
  810. {
  811. ((OpenSim.world.Primitive)ent).UpdatePosition(pos);
  812. }
  813. }
  814. //should update stored position of the prim
  815. }
  816. else if (multipleupdate.ObjectData[i].Type == 10)//rotation
  817. {
  818. libsecondlife.LLQuaternion rot = new LLQuaternion(multipleupdate.ObjectData[i].Data, 0, true);
  819. foreach (Entity ent in m_world.Entities.Values)
  820. {
  821. if (ent.localid == multipleupdate.ObjectData[i].ObjectLocalID)
  822. {
  823. ent.rotation = new Axiom.MathLib.Quaternion(rot.W, rot.X, rot.Y, rot.Z);
  824. ((OpenSim.world.Primitive)ent).UpdateFlag = true;
  825. }
  826. }
  827. }
  828. else if (multipleupdate.ObjectData[i].Type == 13)//scale
  829. {
  830. libsecondlife.LLVector3 scale = new LLVector3(multipleupdate.ObjectData[i].Data, 12);
  831. foreach (Entity ent in m_world.Entities.Values)
  832. {
  833. if (ent.localid == multipleupdate.ObjectData[i].ObjectLocalID)
  834. {
  835. ((OpenSim.world.Primitive)ent).Scale = scale;
  836. }
  837. }
  838. }
  839. }
  840. return true;
  841. }
  842. #endregion
  843. private AgentInventory CreateInventory(LLUUID baseFolder)
  844. {
  845. AgentInventory inventory = null;
  846. if (this.m_userServer != null)
  847. {
  848. // a user server is set so request the inventory from it
  849. Console.WriteLine("getting inventory from user server");
  850. inventory = m_inventoryCache.FetchAgentsInventory(this.AgentID, m_userServer);
  851. }
  852. else
  853. {
  854. inventory = new AgentInventory();
  855. inventory.AgentID = this.AgentID;
  856. inventory.CreateRootFolder(this.AgentID, false);
  857. m_inventoryCache.AddNewAgentsInventory(inventory);
  858. m_inventoryCache.CreateNewInventoryFolder(this, baseFolder);
  859. }
  860. return inventory;
  861. }
  862. private void CreateInventoryItem(CreateInventoryItemPacket packet)
  863. {
  864. if (packet.InventoryBlock.Type == 7)
  865. {
  866. //lets try this out with creating a notecard
  867. AssetBase asset = new AssetBase();
  868. asset.Name = Helpers.FieldToString(packet.InventoryBlock.Name);
  869. asset.Description = Helpers.FieldToString(packet.InventoryBlock.Description);
  870. asset.InvType = packet.InventoryBlock.InvType;
  871. asset.Type = packet.InventoryBlock.Type;
  872. asset.FullID = LLUUID.Random();
  873. asset.Data = new byte[0];
  874. m_assetCache.AddAsset(asset);
  875. m_inventoryCache.AddNewInventoryItem(this, packet.InventoryBlock.FolderID, asset);
  876. }
  877. }
  878. }
  879. }