OpenSimClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.GridServers;
  37. namespace OpenSim
  38. {
  39. /// <summary>
  40. /// Handles new client connections
  41. /// Constructor takes a single Packet and authenticates everything
  42. /// </summary>
  43. public class OpenSimClient {
  44. public LLUUID AgentID;
  45. public LLUUID SessionID;
  46. public uint CircuitCode;
  47. public world.Avatar ClientAvatar;
  48. private UseCircuitCodePacket cirpack;
  49. private Thread ClientThread;
  50. private EndPoint userEP;
  51. private BlockingQueue<QueItem> PacketQueue;
  52. private Dictionary<uint, uint> PendingAcks = new Dictionary<uint, uint>();
  53. private Dictionary<uint, Packet> NeedAck = new Dictionary<uint, Packet>();
  54. private System.Timers.Timer AckTimer;
  55. private uint Sequence = 0;
  56. private object SequenceLock = new object();
  57. private const int MAX_APPENDED_ACKS = 10;
  58. private const int RESEND_TIMEOUT = 4000;
  59. private const int MAX_SEQUENCE = 0xFFFFFF;
  60. public void ack_pack(Packet Pack) {
  61. //libsecondlife.Packets.PacketAckPacket ack_it = new PacketAckPacket();
  62. //ack_it.Packets = new PacketAckPacket.PacketsBlock[1];
  63. //ack_it.Packets[0] = new PacketAckPacket.PacketsBlock();
  64. //ack_it.Packets[0].ID = Pack.Header.ID;
  65. //ack_it.Header.Reliable = false;
  66. //OutPacket(ack_it);
  67. if (Pack.Header.Reliable) {
  68. lock (PendingAcks) {
  69. uint sequence = (uint)Pack.Header.Sequence;
  70. if (!PendingAcks.ContainsKey(sequence)) { PendingAcks[sequence] = sequence; }
  71. }
  72. }
  73. }
  74. public void ProcessInPacket(Packet Pack) {
  75. ack_pack(Pack);
  76. switch(Pack.Type) {
  77. case PacketType.CompleteAgentMovement:
  78. ClientAvatar.CompleteMovement(OpenSim_Main.local_world);
  79. ClientAvatar.SendInitialPosition();
  80. break;
  81. case PacketType.RegionHandshakeReply:
  82. OpenSim_Main.local_world.SendLayerData(this);
  83. break;
  84. case PacketType.AgentWearablesRequest:
  85. ClientAvatar.SendInitialAppearance();
  86. break;
  87. case PacketType.TransferRequest:
  88. //Console.WriteLine("OpenSimClient.cs:ProcessInPacket() - Got transfer request");
  89. TransferRequestPacket transfer = (TransferRequestPacket)Pack;
  90. OpenSim_Main.assetCache.AddAssetRequest(this, transfer);
  91. break;
  92. case PacketType.AgentUpdate:
  93. ClientAvatar.HandleUpdate((AgentUpdatePacket)Pack);
  94. break;
  95. case PacketType.ChatFromViewer:
  96. ChatFromViewerPacket inchatpack = (ChatFromViewerPacket)Pack;
  97. if(Helpers.FieldToString(inchatpack.ChatData.Message)=="") break;
  98. System.Text.Encoding _enc = System.Text.Encoding.ASCII;
  99. libsecondlife.Packets.ChatFromSimulatorPacket reply = new ChatFromSimulatorPacket();
  100. reply.ChatData.Audible = 1;
  101. reply.ChatData.Message = inchatpack.ChatData.Message;
  102. reply.ChatData.ChatType = 1;
  103. reply.ChatData.SourceType = 1;
  104. reply.ChatData.Position = this.ClientAvatar.position;
  105. reply.ChatData.FromName = _enc.GetBytes(this.ClientAvatar.firstname + " " + this.ClientAvatar.lastname + "\0");
  106. reply.ChatData.OwnerID = this.AgentID;
  107. reply.ChatData.SourceID = this.AgentID;
  108. foreach(OpenSimClient client in OpenSim_Main.sim.ClientThreads.Values) {
  109. client.OutPacket(reply);
  110. }
  111. break;
  112. }
  113. }
  114. private void ResendUnacked()
  115. {
  116. int now = Environment.TickCount;
  117. lock (NeedAck)
  118. {
  119. foreach (Packet packet in NeedAck.Values)
  120. {
  121. if (now - packet.TickCount > RESEND_TIMEOUT)
  122. {
  123. Console.WriteLine("Resending " + packet.Type.ToString() + " packet, " +
  124. (now - packet.TickCount) + "ms have passed", Helpers.LogLevel.Info);
  125. packet.Header.Resent = true;
  126. OutPacket(packet);
  127. }
  128. }
  129. }
  130. }
  131. private void SendAcks()
  132. {
  133. lock (PendingAcks)
  134. {
  135. if (PendingAcks.Count > 0)
  136. {
  137. if (PendingAcks.Count > 250)
  138. {
  139. // FIXME: Handle the odd case where we have too many pending ACKs queued up
  140. Console.WriteLine("Too many ACKs queued up!", Helpers.LogLevel.Error);
  141. return;
  142. }
  143. Console.WriteLine("Sending PacketAck");
  144. int i = 0;
  145. PacketAckPacket acks = new PacketAckPacket();
  146. acks.Packets = new PacketAckPacket.PacketsBlock[PendingAcks.Count];
  147. foreach (uint ack in PendingAcks.Values)
  148. {
  149. acks.Packets[i] = new PacketAckPacket.PacketsBlock();
  150. acks.Packets[i].ID = ack;
  151. i++;
  152. }
  153. acks.Header.Reliable = false;
  154. OutPacket(acks);
  155. PendingAcks.Clear();
  156. }
  157. }
  158. }
  159. private void AckTimer_Elapsed(object sender, ElapsedEventArgs ea)
  160. {
  161. SendAcks();
  162. ResendUnacked();
  163. }
  164. public void ProcessOutPacket(Packet Pack) {
  165. // Keep track of when this packet was sent out
  166. Pack.TickCount = Environment.TickCount;
  167. if (!Pack.Header.Resent)
  168. {
  169. // Set the sequence number
  170. lock (SequenceLock)
  171. {
  172. if (Sequence >= MAX_SEQUENCE)
  173. Sequence = 1;
  174. else
  175. Sequence++;
  176. Pack.Header.Sequence = Sequence;
  177. }
  178. if (Pack.Header.Reliable) //DIRTY HACK
  179. {
  180. lock (NeedAck)
  181. {
  182. if (!NeedAck.ContainsKey(Pack.Header.Sequence))
  183. {
  184. NeedAck.Add(Pack.Header.Sequence, Pack);
  185. }
  186. else
  187. {
  188. // Client.Log("Attempted to add a duplicate sequence number (" +
  189. // packet.Header.Sequence + ") to the NeedAck dictionary for packet type " +
  190. // packet.Type.ToString(), Helpers.LogLevel.Warning);
  191. }
  192. }
  193. // Don't append ACKs to resent packets, in case that's what was causing the
  194. // delivery to fail
  195. if (!Pack.Header.Resent)
  196. {
  197. // Append any ACKs that need to be sent out to this packet
  198. lock (PendingAcks)
  199. {
  200. if (PendingAcks.Count > 0 && PendingAcks.Count < MAX_APPENDED_ACKS &&
  201. Pack.Type != PacketType.PacketAck &&
  202. Pack.Type != PacketType.LogoutRequest)
  203. {
  204. Pack.Header.AckList = new uint[PendingAcks.Count];
  205. int i = 0;
  206. foreach (uint ack in PendingAcks.Values)
  207. {
  208. Pack.Header.AckList[i] = ack;
  209. i++;
  210. }
  211. PendingAcks.Clear();
  212. Pack.Header.AppendedAcks = true;
  213. }
  214. }
  215. }
  216. }
  217. }
  218. Console.WriteLine("OUT: \n" + Pack.ToString());
  219. byte[] ZeroOutBuffer = new byte[4096];
  220. byte[] sendbuffer;
  221. sendbuffer = Pack.ToBytes();
  222. try {
  223. if (Pack.Header.Zerocoded) {
  224. int packetsize = Helpers.ZeroEncode(sendbuffer, sendbuffer.Length, ZeroOutBuffer);
  225. OpenSim_Main.Server.SendTo(ZeroOutBuffer, packetsize, SocketFlags.None,userEP);
  226. } else {
  227. OpenSim_Main.Server.SendTo(sendbuffer, sendbuffer.Length, SocketFlags.None,userEP);
  228. }
  229. } catch (Exception) {
  230. Console.WriteLine("OpenSimClient.cs:ProcessOutPacket() - WARNING: Socket exception occurred on connection " + userEP.ToString() + " - killing thread");
  231. ClientThread.Abort();
  232. }
  233. }
  234. public void InPacket(Packet NewPack) {
  235. // Handle appended ACKs
  236. if (NewPack.Header.AppendedAcks)
  237. {
  238. lock (NeedAck)
  239. {
  240. foreach (uint ack in NewPack.Header.AckList)
  241. {
  242. NeedAck.Remove(ack);
  243. }
  244. }
  245. }
  246. // Handle PacketAck packets
  247. if (NewPack.Type == PacketType.PacketAck)
  248. {
  249. PacketAckPacket ackPacket = (PacketAckPacket)NewPack;
  250. lock (NeedAck)
  251. {
  252. foreach (PacketAckPacket.PacketsBlock block in ackPacket.Packets)
  253. {
  254. NeedAck.Remove(block.ID);
  255. }
  256. }
  257. } else if( ( NewPack.Type == PacketType.StartPingCheck ) ) {
  258. //reply to pingcheck
  259. libsecondlife.Packets.StartPingCheckPacket startPing = (libsecondlife.Packets.StartPingCheckPacket)NewPack;
  260. libsecondlife.Packets.CompletePingCheckPacket endPing = new CompletePingCheckPacket();
  261. endPing.PingID.PingID = startPing.PingID.PingID;
  262. OutPacket(endPing);
  263. }
  264. else
  265. {
  266. QueItem item = new QueItem();
  267. item.Packet = NewPack;
  268. item.Incoming = true;
  269. this.PacketQueue.Enqueue(item);
  270. }
  271. }
  272. public void OutPacket(Packet NewPack) {
  273. QueItem item = new QueItem();
  274. item.Packet = NewPack;
  275. item.Incoming = false;
  276. this.PacketQueue.Enqueue(item);
  277. }
  278. public OpenSimClient(EndPoint remoteEP, UseCircuitCodePacket initialcirpack) {
  279. Console.WriteLine("OpenSimClient.cs - Started up new client thread to handle incoming request");
  280. cirpack = initialcirpack;
  281. userEP = remoteEP;
  282. PacketQueue = new BlockingQueue<QueItem>();
  283. AckTimer = new System.Timers.Timer(500);
  284. AckTimer.Elapsed += new ElapsedEventHandler(AckTimer_Elapsed);
  285. AckTimer.Start();
  286. ClientThread = new Thread(new ThreadStart(AuthUser));
  287. ClientThread.IsBackground = true;
  288. ClientThread.Start();
  289. }
  290. private void ClientLoop() {
  291. Console.WriteLine("OpenSimClient.cs:ClientLoop() - Entered loop");
  292. while(true) {
  293. QueItem nextPacket = PacketQueue.Dequeue();
  294. if(nextPacket.Incoming)
  295. {
  296. //is a incoming packet
  297. ProcessInPacket(nextPacket.Packet);
  298. }
  299. else
  300. {
  301. //is a out going packet
  302. ProcessOutPacket(nextPacket.Packet);
  303. }
  304. }
  305. }
  306. private void InitNewClient() {
  307. Console.WriteLine("OpenSimClient.cs:InitNewClient() - Adding viewer agent to world");
  308. OpenSim_Main.local_world.AddViewerAgent(this);
  309. world.Entity tempent=OpenSim_Main.local_world.Entities[this.AgentID];
  310. this.ClientAvatar=(world.Avatar)tempent;
  311. }
  312. private void AuthUser()
  313. {
  314. AuthenticateResponse sessionInfo = OpenSim_Main.gridServers.GridServer.AuthenticateSession(cirpack.CircuitCode.SessionID, cirpack.CircuitCode.ID, cirpack.CircuitCode.Code);
  315. if(!sessionInfo.Authorised)
  316. {
  317. //session/circuit not authorised
  318. Console.WriteLine("OpenSimClient.cs:AuthUser() - New user request denied to " + userEP.ToString());
  319. ClientThread.Abort();
  320. }
  321. else
  322. {
  323. Console.WriteLine("OpenSimClient.cs:AuthUser() - Got authenticated connection from " + userEP.ToString());
  324. //session is authorised
  325. this.AgentID=cirpack.CircuitCode.ID;
  326. this.SessionID=cirpack.CircuitCode.SessionID;
  327. this.CircuitCode=cirpack.CircuitCode.Code;
  328. InitNewClient();
  329. this.ClientAvatar.firstname = sessionInfo.LoginInfo.First;
  330. this.ClientAvatar.lastname = sessionInfo.LoginInfo.Last;
  331. ClientLoop();
  332. }
  333. }
  334. }
  335. }