OpenSimMain.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. /*
  2. Copyright (c) OpenSim project, http://osgrid.org/
  3. * All rights reserved.
  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 <organization> 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 <copyright holder> ``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 <copyright holder> 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.Text;
  29. using System.IO;
  30. using System.Threading;
  31. using System.Net;
  32. using System.Net.Sockets;
  33. using System.Timers;
  34. using System.Reflection;
  35. using System.Collections;
  36. using System.Collections.Generic;
  37. using libsecondlife;
  38. using libsecondlife.Packets;
  39. using OpenSim.world;
  40. using OpenSim.Terrain;
  41. using OpenSim.Framework.Interfaces;
  42. using OpenSim.Framework.Types;
  43. using OpenSim.UserServer;
  44. using OpenSim.Assets;
  45. using OpenSim.CAPS;
  46. using OpenSim.Framework.Console;
  47. using OpenSim.Physics.Manager;
  48. using Nwc.XmlRpc;
  49. using OpenSim.Servers;
  50. using OpenSim.GenericConfig;
  51. namespace OpenSim
  52. {
  53. public class OpenSimMain : OpenSimNetworkHandler, conscmd_callback
  54. {
  55. //private SimConfig Cfg;
  56. private IGenericConfig localConfig;
  57. //private IGenericConfig remoteConfig;
  58. private PhysicsManager physManager;
  59. private Grid GridServers;
  60. private PacketServer _packetServer;
  61. private World LocalWorld;
  62. private AssetCache AssetCache;
  63. private InventoryCache InventoryCache;
  64. //private Dictionary<uint, SimClient> ClientThreads = new Dictionary<uint, SimClient>();
  65. private Dictionary<EndPoint, uint> clientCircuits = new Dictionary<EndPoint, uint>();
  66. private DateTime startuptime;
  67. private RegionInfo regionData;
  68. public Socket Server;
  69. private IPEndPoint ServerIncoming;
  70. private byte[] RecvBuffer = new byte[4096];
  71. private byte[] ZeroBuffer = new byte[8192];
  72. private IPEndPoint ipeSender;
  73. private EndPoint epSender;
  74. private AsyncCallback ReceivedData;
  75. private System.Timers.Timer m_heartbeatTimer = new System.Timers.Timer();
  76. //private string ConfigDll = "OpenSim.Config.SimConfigDb4o.dll";
  77. public string m_physicsEngine;
  78. public bool m_sandbox = false;
  79. public bool m_loginserver;
  80. public OpenGridProtocolServer OGSServer;
  81. public bool user_accounts = false;
  82. public bool gridLocalAsset = false;
  83. private bool configFileSetup = false;
  84. public string m_config;
  85. protected ConsoleBase m_console;
  86. public OpenSimMain(bool sandBoxMode, bool startLoginServer, string physicsEngine, bool useConfigFile, bool verbose, string configFile)
  87. {
  88. this.configFileSetup = useConfigFile;
  89. m_sandbox = sandBoxMode;
  90. m_loginserver = startLoginServer;
  91. m_physicsEngine = physicsEngine;
  92. m_config = configFile;
  93. m_console = new ConsoleBase("region-console" + m_config + ".log", "Region", this, verbose);
  94. OpenSim.Framework.Console.MainConsole.Instance = m_console;
  95. }
  96. /// <summary>
  97. /// Performs initialisation of the world, such as loading configuration from disk.
  98. /// </summary>
  99. public virtual void StartUp()
  100. {
  101. this.regionData = new RegionInfo();
  102. try
  103. {
  104. this.localConfig = new XmlConfig(m_config);
  105. this.localConfig.LoadData();
  106. }
  107. catch (Exception e)
  108. {
  109. Console.WriteLine(e.Message);
  110. }
  111. if (this.configFileSetup)
  112. {
  113. this.SetupFromConfigFile(this.localConfig);
  114. }
  115. m_console.WriteLine("Main.cs:Startup() - Loading configuration");
  116. this.regionData.InitConfig(this.m_sandbox, this.localConfig);
  117. this.localConfig.Close();//for now we can close it as no other classes read from it , but this should change
  118. GridServers = new Grid();
  119. if (m_sandbox)
  120. {
  121. GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll";
  122. GridServers.GridDll = "OpenSim.GridInterfaces.Local.dll";
  123. m_console.WriteLine("Starting in Sandbox mode");
  124. }
  125. else
  126. {
  127. if (this.gridLocalAsset)
  128. {
  129. GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll";
  130. }
  131. else
  132. {
  133. GridServers.AssetDll = "OpenSim.GridInterfaces.Remote.dll";
  134. }
  135. GridServers.GridDll = "OpenSim.GridInterfaces.Remote.dll";
  136. m_console.WriteLine("Starting in Grid mode");
  137. }
  138. try
  139. {
  140. GridServers.Initialise();
  141. }
  142. catch (Exception e)
  143. {
  144. m_console.WriteLine(e.Message + "\nSorry, could not setup the grid interface");
  145. Environment.Exit(1);
  146. }
  147. startuptime = DateTime.Now;
  148. try
  149. {
  150. AssetCache = new AssetCache(GridServers.AssetServer);
  151. InventoryCache = new InventoryCache();
  152. }
  153. catch (Exception e)
  154. {
  155. m_console.WriteLine(e.Message + "\nSorry, could not setup local cache");
  156. Environment.Exit(1);
  157. }
  158. PacketServer packetServer = new PacketServer(this);
  159. //should be passing a IGenericConfig object to these so they can read the config data they want from it
  160. GridServers.AssetServer.SetServerInfo(regionData.AssetURL, regionData.AssetSendKey);
  161. IGridServer gridServer = GridServers.GridServer;
  162. gridServer.SetServerInfo(regionData.GridURL, regionData.GridSendKey, regionData.GridRecvKey);
  163. if (!m_sandbox)
  164. {
  165. if (GridServers.GridServer.RequestConnection(regionData.SimUUID, regionData.IPListenAddr, (uint)regionData.IPListenPort))
  166. {
  167. m_console.WriteLine("Main.cs:Startup() - Success: Got a grid connection OK!");
  168. }
  169. else
  170. {
  171. m_console.WriteLine("Main.cs:Startup() - FAILED: Unable to get connection to grid. Shutting down.");
  172. Shutdown();
  173. }
  174. GridServers.AssetServer.SetServerInfo((string)((RemoteGridBase)GridServers.GridServer).GridData["asset_url"], (string)((RemoteGridBase)GridServers.GridServer).GridData["asset_sendkey"]);
  175. // If we are being told to load a file, load it.
  176. if (((string)((RemoteGridBase)GridServers.GridServer).GridData["data_uri"]) != "")
  177. {
  178. this.LocalWorld.m_datastore = ((string)((RemoteGridBase)GridServers.GridServer).GridData["data_uri"]);
  179. }
  180. if (((RemoteGridBase)(GridServers.GridServer)).GridData["regionname"].ToString() != "")
  181. {
  182. // The grid server has told us who we are
  183. // We must obey the grid server.
  184. try
  185. {
  186. regionData.RegionLocX = Convert.ToUInt32(((RemoteGridBase)(GridServers.GridServer)).GridData["region_locx"].ToString());
  187. regionData.RegionLocY = Convert.ToUInt32(((RemoteGridBase)(GridServers.GridServer)).GridData["region_locy"].ToString());
  188. regionData.RegionName = ((RemoteGridBase)(GridServers.GridServer)).GridData["regionname"].ToString();
  189. }
  190. catch (Exception e)
  191. {
  192. m_console.WriteLine(e.Message + "\nBAD ERROR! THIS SHOULD NOT HAPPEN! Bad GridData from the grid interface!!!! ZOMG!!!");
  193. Environment.Exit(1);
  194. }
  195. }
  196. }
  197. m_console.WriteLine("Main.cs:Startup() - We are " + regionData.RegionName + " at " + regionData.RegionLocX.ToString() + "," + regionData.RegionLocY.ToString());
  198. m_console.WriteLine("Initialising world");
  199. LocalWorld = new World(this._packetServer.ClientThreads, regionData.RegionHandle, regionData.RegionName);
  200. LocalWorld.InventoryCache = InventoryCache;
  201. LocalWorld.AssetCache = AssetCache;
  202. this._packetServer.LocalWorld = LocalWorld;
  203. this._packetServer.RegisterClientPacketHandlers();
  204. this.physManager = new OpenSim.Physics.Manager.PhysicsManager();
  205. this.physManager.LoadPlugins();
  206. LocalWorld.m_datastore = this.regionData.DataStore;
  207. LocalWorld.LoadStorageDLL("OpenSim.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded.
  208. LocalWorld.LoadWorldMap();
  209. m_console.WriteLine("Main.cs:Startup() - Starting up messaging system");
  210. LocalWorld.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); //should be reading from the config file what physics engine to use
  211. LocalWorld.PhysScene.SetTerrain(LocalWorld.Terrain.getHeights1D());
  212. LocalWorld.LoadPrimsFromStorage();
  213. if (m_sandbox)
  214. {
  215. AssetCache.LoadDefaultTextureSet();
  216. }
  217. m_console.WriteLine("Main.cs:Startup() - Initialising HTTP server");
  218. // HttpServer = new SimCAPSHTTPServer(GridServers.GridServer, Cfg.IPListenPort);
  219. BaseHttpServer httpServer = new BaseHttpServer(regionData.IPListenPort);
  220. if (gridServer.GetName() == "Remote")
  221. {
  222. // should startup the OGS protocol server here
  223. // Are we actually using this?
  224. OGSServer = new OpenGridProtocolServer(this.regionData.IPListenPort - 500); // Changed so we can have more than one OGSServer per machine.
  225. // we are in Grid mode so set a XmlRpc handler to handle "expect_user" calls from the user server
  226. httpServer.AddXmlRPCHandler("expect_user",
  227. delegate(XmlRpcRequest request)
  228. {
  229. Hashtable requestData = (Hashtable)request.Params[0];
  230. AgentCircuitData agent_data = new AgentCircuitData();
  231. agent_data.SessionID = new LLUUID((string)requestData["session_id"]);
  232. agent_data.SecureSessionID = new LLUUID((string)requestData["secure_session_id"]);
  233. agent_data.firstname = (string)requestData["firstname"];
  234. agent_data.lastname = (string)requestData["lastname"];
  235. agent_data.AgentID = new LLUUID((string)requestData["agent_id"]);
  236. agent_data.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
  237. if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
  238. {
  239. agent_data.child = true;
  240. }
  241. else
  242. {
  243. agent_data.startpos = new LLVector3(Convert.ToUInt32(requestData["startpos_x"]), Convert.ToUInt32(requestData["startpos_y"]), Convert.ToUInt32(requestData["startpos_z"]));
  244. agent_data.child = false;
  245. }
  246. if (((RemoteGridBase)gridServer).agentcircuits.ContainsKey((uint)agent_data.circuitcode))
  247. {
  248. ((RemoteGridBase)gridServer).agentcircuits[(uint)agent_data.circuitcode] = agent_data;
  249. }
  250. else
  251. {
  252. ((RemoteGridBase)gridServer).agentcircuits.Add((uint)agent_data.circuitcode, agent_data);
  253. }
  254. return new XmlRpcResponse();
  255. });
  256. httpServer.AddXmlRPCHandler("agent_crossing",
  257. delegate(XmlRpcRequest request)
  258. {
  259. Hashtable requestData = (Hashtable)request.Params[0];
  260. AgentCircuitData agent_data = new AgentCircuitData();
  261. agent_data.firstname = (string)requestData["firstname"];
  262. agent_data.lastname = (string)requestData["lastname"];
  263. agent_data.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
  264. agent_data.startpos = new LLVector3(Single.Parse((string)requestData["pos_x"]), Single.Parse((string)requestData["pos_y"]), Single.Parse((string)requestData["pos_z"]));
  265. if (((RemoteGridBase)gridServer).agentcircuits.ContainsKey((uint)agent_data.circuitcode))
  266. {
  267. ((RemoteGridBase)gridServer).agentcircuits[(uint)agent_data.circuitcode].firstname = agent_data.firstname;
  268. ((RemoteGridBase)gridServer).agentcircuits[(uint)agent_data.circuitcode].lastname = agent_data.lastname;
  269. ((RemoteGridBase)gridServer).agentcircuits[(uint)agent_data.circuitcode].startpos = agent_data.startpos;
  270. }
  271. return new XmlRpcResponse();
  272. });
  273. httpServer.AddRestHandler("GET", "/simstatus/",
  274. delegate(string request, string path, string param)
  275. {
  276. return "OK";
  277. });
  278. }
  279. LoginServer loginServer = null;
  280. LoginServer adminLoginServer = null;
  281. bool sandBoxWithLoginServer = m_loginserver && m_sandbox;
  282. if (sandBoxWithLoginServer)
  283. {
  284. loginServer = new LoginServer(gridServer, regionData.IPListenAddr, regionData.IPListenPort, this.user_accounts);
  285. loginServer.Startup();
  286. if (user_accounts)
  287. {
  288. //sandbox mode with loginserver using accounts
  289. this.GridServers.UserServer = loginServer;
  290. adminLoginServer = loginServer;
  291. httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.LocalUserManager.XmlRpcLoginMethod);
  292. }
  293. else
  294. {
  295. //sandbox mode with loginserver not using accounts
  296. httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.XmlRpcLoginMethod);
  297. }
  298. }
  299. AdminWebFront adminWebFront = new AdminWebFront("Admin", LocalWorld, InventoryCache, adminLoginServer);
  300. adminWebFront.LoadMethods(httpServer);
  301. m_console.WriteLine("Main.cs:Startup() - Starting HTTP server");
  302. httpServer.Start();
  303. if (gridServer.GetName() == "Remote")
  304. {
  305. m_console.WriteLine("Main.cs:Startup() - Starting up OGS protocol server");
  306. OGSServer.Start();
  307. }
  308. MainServerListener();
  309. m_heartbeatTimer.Enabled = true;
  310. m_heartbeatTimer.Interval = 100;
  311. m_heartbeatTimer.Elapsed += new ElapsedEventHandler(this.Heartbeat);
  312. }
  313. private void SetupFromConfigFile(IGenericConfig configData)
  314. {
  315. try
  316. {
  317. // SandBoxMode
  318. string attri = "";
  319. attri = configData.GetAttribute("SandBox");
  320. if ((attri == "") || ((attri != "false") && (attri != "true")))
  321. {
  322. this.m_sandbox = false;
  323. configData.SetAttribute("SandBox", "false");
  324. }
  325. else
  326. {
  327. this.m_sandbox = Convert.ToBoolean(attri);
  328. }
  329. // LoginServer
  330. attri = "";
  331. attri = configData.GetAttribute("LoginServer");
  332. if ((attri == "") || ((attri != "false") && (attri != "true")))
  333. {
  334. this.m_loginserver = false;
  335. configData.SetAttribute("LoginServer", "false");
  336. }
  337. else
  338. {
  339. this.m_loginserver = Convert.ToBoolean(attri);
  340. }
  341. // Sandbox User accounts
  342. attri = "";
  343. attri = configData.GetAttribute("UserAccount");
  344. if ((attri == "") || ((attri != "false") && (attri != "true")))
  345. {
  346. this.user_accounts = false;
  347. configData.SetAttribute("UserAccounts", "false");
  348. }
  349. else if (attri == "true")
  350. {
  351. this.user_accounts = Convert.ToBoolean(attri);
  352. }
  353. // Grid mode hack to use local asset server
  354. attri = "";
  355. attri = configData.GetAttribute("LocalAssets");
  356. if ((attri == "") || ((attri != "false") && (attri != "true")))
  357. {
  358. this.gridLocalAsset = false;
  359. configData.SetAttribute("LocalAssets", "false");
  360. }
  361. else if (attri == "true")
  362. {
  363. this.gridLocalAsset = Convert.ToBoolean(attri);
  364. }
  365. attri = "";
  366. attri = configData.GetAttribute("PhysicsEngine");
  367. switch (attri)
  368. {
  369. default:
  370. m_console.WriteLine("Main.cs: SetupFromConfig() - Invalid value for PhysicsEngine attribute, terminating");
  371. Environment.Exit(1);
  372. break;
  373. case "":
  374. this.m_physicsEngine = "basicphysics";
  375. configData.SetAttribute("PhysicsEngine", "basicphysics");
  376. OpenSim.world.Avatar.PhysicsEngineFlying = false;
  377. break;
  378. case "basicphysics":
  379. this.m_physicsEngine = "basicphysics";
  380. configData.SetAttribute("PhysicsEngine", "basicphysics");
  381. OpenSim.world.Avatar.PhysicsEngineFlying = false;
  382. break;
  383. case "RealPhysX":
  384. this.m_physicsEngine = "RealPhysX";
  385. OpenSim.world.Avatar.PhysicsEngineFlying = true;
  386. break;
  387. case "OpenDynamicsEngine":
  388. this.m_physicsEngine = "OpenDynamicsEngine";
  389. OpenSim.world.Avatar.PhysicsEngineFlying = true;
  390. break;
  391. }
  392. configData.Commit();
  393. }
  394. catch (Exception e)
  395. {
  396. Console.WriteLine(e.Message);
  397. Console.WriteLine("\nSorry, a fatal error occurred while trying to initialise the configuration data");
  398. Console.WriteLine("Can not continue starting up");
  399. Environment.Exit(1);
  400. }
  401. }
  402. private SimConfig LoadConfigDll(string dllName)
  403. {
  404. try
  405. {
  406. Assembly pluginAssembly = Assembly.LoadFrom(dllName);
  407. SimConfig config = null;
  408. foreach (Type pluginType in pluginAssembly.GetTypes())
  409. {
  410. if (pluginType.IsPublic)
  411. {
  412. if (!pluginType.IsAbstract)
  413. {
  414. Type typeInterface = pluginType.GetInterface("ISimConfig", true);
  415. if (typeInterface != null)
  416. {
  417. ISimConfig plug = (ISimConfig)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
  418. config = plug.GetConfigObject();
  419. break;
  420. }
  421. typeInterface = null;
  422. }
  423. }
  424. }
  425. pluginAssembly = null;
  426. return config;
  427. }
  428. catch (Exception e)
  429. {
  430. m_console.WriteLine(e.Message + "\nSorry, a fatal error occurred while trying to load the config DLL");
  431. m_console.WriteLine("Can not continue starting up");
  432. Environment.Exit(1);
  433. return null;
  434. }
  435. }
  436. private void OnReceivedData(IAsyncResult result)
  437. {
  438. ipeSender = new IPEndPoint(IPAddress.Any, 0);
  439. epSender = (EndPoint)ipeSender;
  440. Packet packet = null;
  441. int numBytes = Server.EndReceiveFrom(result, ref epSender);
  442. int packetEnd = numBytes - 1;
  443. packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer);
  444. // This is either a new client or a packet to send to an old one
  445. // if (OpenSimRoot.Instance.ClientThreads.ContainsKey(epSender))
  446. // do we already have a circuit for this endpoint
  447. if (this.clientCircuits.ContainsKey(epSender))
  448. {
  449. //ClientThreads[this.clientCircuits[epSender]].InPacket(packet);
  450. this._packetServer.ClientInPacket(this.clientCircuits[epSender], packet);
  451. }
  452. else if (packet.Type == PacketType.UseCircuitCode)
  453. { // new client
  454. UseCircuitCodePacket useCircuit = (UseCircuitCodePacket)packet;
  455. this.clientCircuits.Add(epSender, useCircuit.CircuitCode.Code);
  456. bool isChildAgent = false;
  457. if (this.GridServers.GridServer.GetName() == "Remote")
  458. {
  459. isChildAgent = ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].child;
  460. }
  461. SimClient newuser = new SimClient(epSender, useCircuit, LocalWorld, _packetServer.ClientThreads, AssetCache, GridServers.GridServer, this, InventoryCache, m_sandbox, isChildAgent, this.regionData);
  462. if ((this.GridServers.UserServer != null) && (user_accounts))
  463. {
  464. newuser.UserServer = this.GridServers.UserServer;
  465. }
  466. //OpenSimRoot.Instance.ClientThreads.Add(epSender, newuser);
  467. this._packetServer.ClientThreads.Add(useCircuit.CircuitCode.Code, newuser);
  468. //if (!((RemoteGridBase)GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].child)
  469. if ((this.GridServers.GridServer.GetName() == "Remote") && (!isChildAgent))
  470. {
  471. Hashtable SimParams;
  472. ArrayList SendParams;
  473. XmlRpcRequest GridReq;
  474. XmlRpcResponse GridResp;
  475. foreach (Hashtable neighbour in ((RemoteGridBase)this.GridServers.GridServer).neighbours)
  476. {
  477. m_console.WriteLine("http://" + neighbour["sim_ip"] + ":" + neighbour["sim_port"]);
  478. SimParams = new Hashtable();
  479. SimParams["session_id"] = ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].SessionID.ToString();
  480. SimParams["secure_session_id"] = ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].SecureSessionID.ToString();
  481. SimParams["firstname"] = ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].firstname;
  482. SimParams["lastname"] = ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].lastname;
  483. SimParams["agent_id"] = ((RemoteGridBase)this.GridServers.GridServer).agentcircuits[useCircuit.CircuitCode.Code].AgentID.ToString();
  484. SimParams["circuit_code"] = (Int32)useCircuit.CircuitCode.Code;
  485. SimParams["child_agent"] = "1";
  486. SendParams = new ArrayList();
  487. SendParams.Add(SimParams);
  488. GridReq = new XmlRpcRequest("expect_user", SendParams);
  489. GridResp = GridReq.Send("http://" + neighbour["sim_ip"] + ":" + neighbour["sim_port"], 3000);
  490. EnableSimulatorPacket enablesimpacket = new EnableSimulatorPacket();
  491. enablesimpacket.SimulatorInfo = new EnableSimulatorPacket.SimulatorInfoBlock();
  492. enablesimpacket.SimulatorInfo.Handle = Helpers.UIntsToLong((uint)(Convert.ToInt32(neighbour["region_locx"]) * 256), (uint)(Convert.ToInt32(neighbour["region_locy"]) * 256));
  493. System.Net.IPAddress neighbourIP = System.Net.IPAddress.Parse((string)neighbour["sim_ip"]);
  494. byte[] byteIP = neighbourIP.GetAddressBytes();
  495. enablesimpacket.SimulatorInfo.IP = (uint)byteIP[3] << 24;
  496. enablesimpacket.SimulatorInfo.IP += (uint)byteIP[2] << 16;
  497. enablesimpacket.SimulatorInfo.IP += (uint)byteIP[1] << 8;
  498. enablesimpacket.SimulatorInfo.IP += (uint)byteIP[0];
  499. enablesimpacket.SimulatorInfo.Port = (ushort)Convert.ToInt32(neighbour["sim_port"]);
  500. Thread.Sleep(3000);
  501. _packetServer.ClientThreads[useCircuit.CircuitCode.Code].OutPacket(enablesimpacket);
  502. }
  503. }
  504. }
  505. else
  506. { // invalid client
  507. Console.Error.WriteLine("Main.cs:OnReceivedData() - WARNING: Got a packet from an invalid client - " + epSender.ToString());
  508. }
  509. Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
  510. }
  511. private void MainServerListener()
  512. {
  513. m_console.WriteLine("Main.cs:MainServerListener() - New thread started");
  514. m_console.WriteLine("Main.cs:MainServerListener() - Opening UDP socket on " + regionData.IPListenAddr + ":" + regionData.IPListenPort);
  515. ServerIncoming = new IPEndPoint(IPAddress.Any, regionData.IPListenPort);
  516. Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  517. Server.Bind(ServerIncoming);
  518. m_console.WriteLine("Main.cs:MainServerListener() - UDP socket bound, getting ready to listen");
  519. ipeSender = new IPEndPoint(IPAddress.Any, 0);
  520. epSender = (EndPoint)ipeSender;
  521. ReceivedData = new AsyncCallback(this.OnReceivedData);
  522. Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
  523. m_console.WriteLine("Main.cs:MainServerListener() - Listening...");
  524. }
  525. public void RegisterPacketServer(PacketServer server)
  526. {
  527. this._packetServer = server;
  528. }
  529. public virtual void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode)//EndPoint packetSender)
  530. {
  531. // find the endpoint for this circuit
  532. EndPoint sendto = null;
  533. foreach (KeyValuePair<EndPoint, uint> p in this.clientCircuits)
  534. {
  535. if (p.Value == circuitcode)
  536. {
  537. sendto = p.Key;
  538. break;
  539. }
  540. }
  541. if (sendto != null)
  542. {
  543. //we found the endpoint so send the packet to it
  544. this.Server.SendTo(buffer, size, flags, sendto);
  545. }
  546. }
  547. public virtual void RemoveClientCircuit(uint circuitcode)
  548. {
  549. foreach (KeyValuePair<EndPoint, uint> p in this.clientCircuits)
  550. {
  551. if (p.Value == circuitcode)
  552. {
  553. this.clientCircuits.Remove(p.Key);
  554. break;
  555. }
  556. }
  557. }
  558. /// <summary>
  559. /// Performs any last-minute sanity checking and shuts down the region server
  560. /// </summary>
  561. public virtual void Shutdown()
  562. {
  563. m_console.WriteLine("Main.cs:Shutdown() - Closing all threads");
  564. m_console.WriteLine("Main.cs:Shutdown() - Killing listener thread");
  565. m_console.WriteLine("Main.cs:Shutdown() - Killing clients");
  566. // IMPLEMENT THIS
  567. m_console.WriteLine("Main.cs:Shutdown() - Closing console and terminating");
  568. LocalWorld.Close();
  569. GridServers.Close();
  570. m_console.Close();
  571. Environment.Exit(0);
  572. }
  573. /// <summary>
  574. /// Performs per-frame updates regularly
  575. /// </summary>
  576. /// <param name="sender"></param>
  577. /// <param name="e"></param>
  578. void Heartbeat(object sender, System.EventArgs e)
  579. {
  580. LocalWorld.Update();
  581. }
  582. /// <summary>
  583. /// Runs commands issued by the server console from the operator
  584. /// </summary>
  585. /// <param name="command">The first argument of the parameter (the command)</param>
  586. /// <param name="cmdparams">Additional arguments passed to the command</param>
  587. public void RunCmd(string command, string[] cmdparams)
  588. {
  589. switch (command)
  590. {
  591. case "help":
  592. m_console.WriteLine("show users - show info about connected users");
  593. m_console.WriteLine("shutdown - disconnect all clients and shutdown");
  594. break;
  595. case "show":
  596. Show(cmdparams[0]);
  597. break;
  598. case "terrain":
  599. string result = "";
  600. if (!LocalWorld.Terrain.RunTerrainCmd(cmdparams, ref result))
  601. {
  602. m_console.WriteLine(result);
  603. }
  604. break;
  605. case "shutdown":
  606. Shutdown();
  607. break;
  608. default:
  609. m_console.WriteLine("Unknown command");
  610. break;
  611. }
  612. }
  613. /// <summary>
  614. /// Outputs to the console information about the region
  615. /// </summary>
  616. /// <param name="ShowWhat">What information to display (valid arguments are "uptime", "users")</param>
  617. public void Show(string ShowWhat)
  618. {
  619. switch (ShowWhat)
  620. {
  621. case "uptime":
  622. m_console.WriteLine("OpenSim has been running since " + startuptime.ToString());
  623. m_console.WriteLine("That is " + (DateTime.Now - startuptime).ToString());
  624. break;
  625. case "users":
  626. OpenSim.world.Avatar TempAv;
  627. m_console.WriteLine(String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}", "Firstname", "Lastname", "Agent ID", "Session ID", "Circuit", "IP"));
  628. foreach (libsecondlife.LLUUID UUID in LocalWorld.Entities.Keys)
  629. {
  630. if (LocalWorld.Entities[UUID].ToString() == "OpenSim.world.Avatar")
  631. {
  632. TempAv = (OpenSim.world.Avatar)LocalWorld.Entities[UUID];
  633. m_console.WriteLine(String.Format("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}", TempAv.firstname, TempAv.lastname, UUID, TempAv.ControllingClient.SessionID, TempAv.ControllingClient.CircuitCode, TempAv.ControllingClient.userEP.ToString()));
  634. }
  635. }
  636. break;
  637. }
  638. }
  639. }
  640. }