LLUDPServer.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 OpenSim 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.Collections.Generic;
  29. using System.Net;
  30. using System.Net.Sockets;
  31. using System.Reflection;
  32. using libsecondlife.Packets;
  33. using log4net;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Communications.Cache;
  36. using OpenSim.Region.ClientStack.LindenUDP;
  37. using OpenSim.Region.Environment.Scenes;
  38. namespace OpenSim.Region.ClientStack.LindenUDP
  39. {
  40. public class LLUDPServer : LLClientStackNetworkHandler, IClientNetworkServer
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. protected Dictionary<EndPoint, uint> clientCircuits = new Dictionary<EndPoint, uint>();
  44. public Dictionary<uint, EndPoint> clientCircuits_reverse = new Dictionary<uint, EndPoint>();
  45. protected Dictionary<uint, EndPoint> proxyCircuits = new Dictionary<uint, EndPoint>();
  46. private Socket m_socket;
  47. protected IPEndPoint ServerIncoming;
  48. protected byte[] RecvBuffer = new byte[4096];
  49. protected byte[] ZeroBuffer = new byte[8192];
  50. protected IPEndPoint ipeSender;
  51. protected EndPoint epSender;
  52. protected EndPoint epProxy;
  53. protected int proxyPortOffset;
  54. protected AsyncCallback ReceivedData;
  55. protected LLPacketServer m_packetServer;
  56. protected Location m_location;
  57. protected uint listenPort;
  58. protected bool Allow_Alternate_Port;
  59. protected IPAddress listenIP = IPAddress.Parse("0.0.0.0");
  60. protected IScene m_localScene;
  61. protected AssetCache m_assetCache;
  62. protected AgentCircuitManager m_authenticateSessionsClass;
  63. public LLPacketServer PacketServer
  64. {
  65. get { return m_packetServer; }
  66. set { m_packetServer = value; }
  67. }
  68. public IScene LocalScene
  69. {
  70. set
  71. {
  72. m_localScene = value;
  73. m_packetServer.LocalScene = m_localScene;
  74. m_location = new Location(m_localScene.RegionInfo.RegionHandle);
  75. }
  76. }
  77. public ulong RegionHandle
  78. {
  79. get { return m_location.RegionHandle; }
  80. }
  81. Socket IClientNetworkServer.Server
  82. {
  83. get { return m_socket; }
  84. }
  85. public bool HandlesRegion(Location x)
  86. {
  87. return x == m_location;
  88. }
  89. public void AddScene(Scene x)
  90. {
  91. LocalScene = x;
  92. }
  93. public void Start()
  94. {
  95. ServerListener();
  96. }
  97. public void Stop()
  98. {
  99. m_socket.Close();
  100. }
  101. public LLUDPServer()
  102. {
  103. }
  104. public LLUDPServer(IPAddress _listenIP, ref uint port, int proxyPortOffset, bool allow_alternate_port, AssetCache assetCache, AgentCircuitManager authenticateClass)
  105. {
  106. this.proxyPortOffset = proxyPortOffset;
  107. listenPort = (uint) (port + proxyPortOffset);
  108. listenIP = _listenIP;
  109. Allow_Alternate_Port = allow_alternate_port;
  110. m_assetCache = assetCache;
  111. m_authenticateSessionsClass = authenticateClass;
  112. CreatePacketServer();
  113. // Return new port
  114. // This because in Grid mode it is not really important what port the region listens to as long as it is correctly registered.
  115. // So the option allow_alternate_ports="true" was added to default.xml
  116. port = (uint)(listenPort - proxyPortOffset);
  117. }
  118. protected virtual void CreatePacketServer()
  119. {
  120. new LLPacketServer(this);
  121. }
  122. protected virtual void OnReceivedData(IAsyncResult result)
  123. {
  124. ipeSender = new IPEndPoint(listenIP, 0);
  125. epSender = (EndPoint) ipeSender;
  126. Packet packet = null;
  127. int numBytes = 1;
  128. try
  129. {
  130. numBytes = m_socket.EndReceiveFrom(result, ref epSender);
  131. }
  132. catch (SocketException e)
  133. {
  134. // TODO : Actually only handle those states that we have control over, re-throw everything else,
  135. // TODO: implement cases as we encounter them.
  136. //m_log.Error("[UDPSERVER]: Connection Error! - " + e.ToString());
  137. switch (e.SocketErrorCode)
  138. {
  139. case SocketError.AlreadyInProgress:
  140. case SocketError.NetworkReset:
  141. case SocketError.ConnectionReset:
  142. try
  143. {
  144. CloseEndPoint(epSender);
  145. }
  146. catch (Exception a)
  147. {
  148. m_log.Info("[UDPSERVER]: " + a.ToString());
  149. }
  150. try
  151. {
  152. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender,
  153. ReceivedData, null);
  154. // Ter: For some stupid reason ConnectionReset basically kills our async event structure..
  155. // so therefore.. we've got to tell the server to BeginReceiveFrom again.
  156. // This will happen over and over until we've gone through all packets
  157. // sent to and from this particular user.
  158. // Stupid I know..
  159. // but Flusing the buffer would be even more stupid... so, we're stuck with this ugly method.
  160. }
  161. catch (SocketException)
  162. {
  163. }
  164. break;
  165. default:
  166. try
  167. {
  168. CloseEndPoint(epSender);
  169. }
  170. catch (Exception)
  171. {
  172. //m_log.Info("[UDPSERVER]" + a.ToString());
  173. }
  174. try
  175. {
  176. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender,
  177. ReceivedData, null);
  178. // Ter: For some stupid reason ConnectionReset basically kills our async event structure..
  179. // so therefore.. we've got to tell the server to BeginReceiveFrom again.
  180. // This will happen over and over until we've gone through all packets
  181. // sent to and from this particular user.
  182. // Stupid I know..
  183. // but Flusing the buffer would be even more stupid... so, we're stuck with this ugly method.
  184. }
  185. catch (SocketException e2)
  186. {
  187. m_log.Error("[UDPSERVER]: " + e2.ToString());
  188. }
  189. // Here's some reference code! :D
  190. // Shutdown and restart the UDP listener! hehe
  191. // Shiny
  192. //Server.Shutdown(SocketShutdown.Both);
  193. //CloseEndPoint(epSender);
  194. //ServerListener();
  195. break;
  196. }
  197. //return;
  198. }
  199. catch (ObjectDisposedException e)
  200. {
  201. m_log.Debug("[UDPSERVER]: " + e.ToString());
  202. try
  203. {
  204. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender,
  205. ReceivedData, null);
  206. // Ter: For some stupid reason ConnectionReset basically kills our async event structure..
  207. // so therefore.. we've got to tell the server to BeginReceiveFrom again.
  208. // This will happen over and over until we've gone through all packets
  209. // sent to and from this particular user.
  210. // Stupid I know..
  211. // but Flusing the buffer would be even more stupid... so, we're stuck with this ugly method.
  212. }
  213. catch (SocketException e2)
  214. {
  215. m_log.Error("[UDPSERVER]: " + e2.ToString());
  216. }
  217. catch (ObjectDisposedException)
  218. {
  219. }
  220. //return;
  221. }
  222. //System.Console.WriteLine("UDPServer : recieved message from {0}", epSender.ToString());
  223. epProxy = epSender;
  224. if (proxyPortOffset != 0)
  225. {
  226. epSender = PacketPool.DecodeProxyMessage(RecvBuffer, ref numBytes);
  227. }
  228. int packetEnd = numBytes - 1;
  229. try
  230. {
  231. packet = PacketPool.Instance.GetPacket(RecvBuffer, ref packetEnd, ZeroBuffer);
  232. }
  233. catch (Exception e)
  234. {
  235. m_log.Debug("[UDPSERVER]: " + e.ToString());
  236. }
  237. try
  238. {
  239. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
  240. }
  241. catch (SocketException)
  242. {
  243. try
  244. {
  245. CloseEndPoint(epSender);
  246. }
  247. catch (Exception a)
  248. {
  249. m_log.Info("[UDPSERVER]: " + a.ToString());
  250. }
  251. try
  252. {
  253. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender,
  254. ReceivedData, null);
  255. // Ter: For some stupid reason ConnectionReset basically kills our async event structure..
  256. // so therefore.. we've got to tell the server to BeginReceiveFrom again.
  257. // This will happen over and over until we've gone through all packets
  258. // sent to and from this particular user.
  259. // Stupid I know..
  260. // but Flusing the buffer would be even more stupid... so, we're stuck with this ugly method.
  261. }
  262. catch (SocketException e5)
  263. {
  264. m_log.Error("[UDPSERVER]: " + e5.ToString());
  265. }
  266. }
  267. catch (ObjectDisposedException)
  268. {
  269. }
  270. if (packet != null)
  271. {
  272. try
  273. {
  274. // do we already have a circuit for this endpoint
  275. uint circuit;
  276. bool ret = false;
  277. lock (clientCircuits)
  278. {
  279. ret = clientCircuits.TryGetValue(epSender, out circuit);
  280. }
  281. if (ret)
  282. {
  283. //if so then send packet to the packetserver
  284. //m_log.Warn("[UDPSERVER]: ALREADY HAVE Circuit!");
  285. m_packetServer.InPacket(circuit, packet);
  286. }
  287. else if (packet.Type == PacketType.UseCircuitCode)
  288. {
  289. // new client
  290. m_log.Debug("[UDPSERVER]: Adding New Client");
  291. AddNewClient(packet);
  292. UseCircuitCodePacket p = (UseCircuitCodePacket)packet;
  293. // Ack the first UseCircuitCode packet
  294. PacketAckPacket ack_it = (PacketAckPacket)PacketPool.Instance.GetPacket(PacketType.PacketAck);
  295. // TODO: don't create new blocks if recycling an old packet
  296. ack_it.Packets = new PacketAckPacket.PacketsBlock[1];
  297. ack_it.Packets[0] = new PacketAckPacket.PacketsBlock();
  298. ack_it.Packets[0].ID = packet.Header.Sequence;
  299. ack_it.Header.Reliable = false;
  300. SendPacketTo(ack_it.ToBytes(),ack_it.ToBytes().Length,SocketFlags.None,p.CircuitCode.Code);
  301. }
  302. }
  303. catch (Exception)
  304. {
  305. m_log.Error("[UDPSERVER]: Exception in processing packet.");
  306. m_log.Debug("[UDPSERVER]: Adding New Client");
  307. try
  308. {
  309. AddNewClient(packet);
  310. }
  311. catch (Exception e3)
  312. {
  313. m_log.Error("[UDPSERVER]: Adding New Client threw exception " + e3.ToString());
  314. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender,
  315. ReceivedData, null);
  316. }
  317. }
  318. }
  319. }
  320. private void CloseEndPoint(EndPoint sender)
  321. {
  322. uint circuit;
  323. lock (clientCircuits)
  324. {
  325. if (clientCircuits.TryGetValue(sender, out circuit))
  326. {
  327. m_packetServer.CloseCircuit(circuit);
  328. }
  329. }
  330. }
  331. protected virtual void AddNewClient(Packet packet)
  332. {
  333. //Slave regions don't accept new clients
  334. if (m_localScene.Region_Status != RegionStatus.SlaveScene)
  335. {
  336. UseCircuitCodePacket useCircuit = (UseCircuitCodePacket) packet;
  337. lock (clientCircuits)
  338. {
  339. if (!clientCircuits.ContainsKey(epSender))
  340. clientCircuits.Add(epSender, useCircuit.CircuitCode.Code);
  341. else
  342. m_log.Error("[UDPSERVER]: clientCircuits already contans entry for user " + useCircuit.CircuitCode.Code.ToString() + ". NOT adding.");
  343. }
  344. lock (clientCircuits_reverse)
  345. {
  346. if (!clientCircuits_reverse.ContainsKey(useCircuit.CircuitCode.Code))
  347. clientCircuits_reverse.Add(useCircuit.CircuitCode.Code, epSender);
  348. else
  349. m_log.Error("[UDPSERVER]: clientCurcuits_reverse already contains entry for user " + useCircuit.CircuitCode.Code.ToString() + ". NOT adding.");
  350. }
  351. lock (proxyCircuits)
  352. {
  353. if (!proxyCircuits.ContainsKey(useCircuit.CircuitCode.Code))
  354. proxyCircuits.Add(useCircuit.CircuitCode.Code, epProxy);
  355. else
  356. m_log.Error("[UDPSERVER]: proxyCircuits already contains entry for user " + useCircuit.CircuitCode.Code.ToString() + ". NOT adding.");
  357. }
  358. PacketServer.AddNewClient(epSender, useCircuit, m_assetCache, m_authenticateSessionsClass, epProxy);
  359. }
  360. PacketPool.Instance.ReturnPacket(packet);
  361. }
  362. public void ServerListener()
  363. {
  364. uint newPort = listenPort;
  365. m_log.Info("[SERVER]: Opening UDP socket on " + listenIP.ToString() + " " + newPort + ".");
  366. ServerIncoming = new IPEndPoint(listenIP, (int)newPort);
  367. m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  368. m_socket.Bind(ServerIncoming);
  369. listenPort = newPort;
  370. m_log.Info("[SERVER]: UDP socket bound, getting ready to listen");
  371. ipeSender = new IPEndPoint(listenIP, 0);
  372. epSender = (EndPoint)ipeSender;
  373. ReceivedData = new AsyncCallback(OnReceivedData);
  374. m_socket.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
  375. m_log.Info("[SERVER]: Listening on port " + newPort);
  376. }
  377. public virtual void RegisterPacketServer(LLPacketServer server)
  378. {
  379. m_packetServer = server;
  380. }
  381. public virtual void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode)
  382. //EndPoint packetSender)
  383. {
  384. // find the endpoint for this circuit
  385. EndPoint sendto = null;
  386. lock (clientCircuits_reverse)
  387. {
  388. if (clientCircuits_reverse.TryGetValue(circuitcode, out sendto))
  389. {
  390. //we found the endpoint so send the packet to it
  391. if (proxyPortOffset != 0)
  392. {
  393. //MainLog.Instance.Verbose("UDPSERVER", "SendPacketTo proxy " + proxyCircuits[circuitcode].ToString() + ": client " + sendto.ToString());
  394. PacketPool.EncodeProxyMessage(buffer, ref size, sendto);
  395. m_socket.SendTo(buffer, size, flags, proxyCircuits[circuitcode]);
  396. }
  397. else
  398. {
  399. //MainLog.Instance.Verbose("UDPSERVER", "SendPacketTo : client " + sendto.ToString());
  400. m_socket.SendTo(buffer, size, flags, sendto);
  401. }
  402. }
  403. }
  404. }
  405. public virtual void RemoveClientCircuit(uint circuitcode)
  406. {
  407. EndPoint sendto = null;
  408. lock (clientCircuits_reverse)
  409. {
  410. if (clientCircuits_reverse.TryGetValue(circuitcode, out sendto))
  411. {
  412. clientCircuits.Remove(sendto);
  413. clientCircuits_reverse.Remove(circuitcode);
  414. proxyCircuits.Remove(circuitcode);
  415. }
  416. }
  417. }
  418. public void RestoreClient(AgentCircuitData circuit, EndPoint userEP, EndPoint proxyEP)
  419. {
  420. //MainLog.Instance.Verbose("UDPSERVER", "RestoreClient");
  421. UseCircuitCodePacket useCircuit = new UseCircuitCodePacket();
  422. useCircuit.CircuitCode.Code = circuit.circuitcode;
  423. useCircuit.CircuitCode.ID = circuit.AgentID;
  424. useCircuit.CircuitCode.SessionID = circuit.SessionID;
  425. lock (clientCircuits)
  426. {
  427. if (!clientCircuits.ContainsKey(userEP))
  428. clientCircuits.Add(userEP, useCircuit.CircuitCode.Code);
  429. else
  430. m_log.Error("[UDPSERVER]: clientCircuits already contans entry for user " + useCircuit.CircuitCode.Code.ToString() + ". NOT adding.");
  431. }
  432. lock (clientCircuits_reverse)
  433. {
  434. if (!clientCircuits_reverse.ContainsKey(useCircuit.CircuitCode.Code))
  435. clientCircuits_reverse.Add(useCircuit.CircuitCode.Code, userEP);
  436. else
  437. m_log.Error("[UDPSERVER]: clientCurcuits_reverse already contains entry for user " + useCircuit.CircuitCode.Code.ToString() + ". NOT adding.");
  438. }
  439. lock (proxyCircuits)
  440. {
  441. if (!proxyCircuits.ContainsKey(useCircuit.CircuitCode.Code))
  442. {
  443. proxyCircuits.Add(useCircuit.CircuitCode.Code, proxyEP);
  444. }
  445. else
  446. {
  447. // re-set proxy endpoint
  448. proxyCircuits.Remove(useCircuit.CircuitCode.Code);
  449. proxyCircuits.Add(useCircuit.CircuitCode.Code, proxyEP);
  450. }
  451. }
  452. PacketServer.AddNewClient(userEP, useCircuit, m_assetCache, m_authenticateSessionsClass, proxyEP);
  453. }
  454. }
  455. }