LLUDPServer.cs 22 KB

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