OpenSimMain.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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.UserServer;
  43. using OpenSim.Assets;
  44. using OpenSim.CAPS;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Physics.Manager;
  47. using OpenSim.GenericConfig;
  48. using Nwc.XmlRpc;
  49. using OpenSim.Servers;
  50. namespace OpenSim
  51. {
  52. public class OpenSimMain : OpenSimNetworkHandler, conscmd_callback
  53. {
  54. //private SimConfig Cfg;
  55. private IGenericConfig localConfig;
  56. //private IGenericConfig remoteConfig;
  57. private PhysicsManager physManager;
  58. private Grid GridServers;
  59. private BaseHttpServer _httpServer;
  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 bool user_accounts = false;
  81. protected ConsoleBase m_console;
  82. public OpenSimMain(bool sandBoxMode, bool startLoginServer, string physicsEngine)
  83. {
  84. m_sandbox = sandBoxMode;
  85. m_loginserver = startLoginServer;
  86. m_physicsEngine = physicsEngine;
  87. m_console = new ConsoleBase("region-console.log", "Region", this);
  88. OpenSim.Framework.Console.MainConsole.Instance = m_console;
  89. }
  90. /// <summary>
  91. /// Performs initialisation of the world, such as loading configuration from disk.
  92. /// </summary>
  93. public virtual void StartUp()
  94. {
  95. this.regionData = new RegionInfo();
  96. try
  97. {
  98. this.localConfig = new XmlConfig("simconfig.xml");
  99. this.localConfig.LoadData();
  100. }
  101. catch (Exception e)
  102. {
  103. Console.WriteLine(e.Message);
  104. }
  105. m_console.WriteLine("Main.cs:Startup() - Loading configuration");
  106. this.regionData.InitConfig(this.m_sandbox, this.localConfig);
  107. //regionData.SimUUID = new LLUUID(localConfig.GetAttribute("SimUUID")); //don't need as regionData.SimUUID is already set through the above line
  108. this.localConfig.Close();//for now we can close it as no other classes read from it , but this should change
  109. GridServers = new Grid();
  110. if (m_sandbox)
  111. {
  112. GridServers.AssetDll = "OpenSim.GridInterfaces.Local.dll";
  113. GridServers.GridDll = "OpenSim.GridInterfaces.Local.dll";
  114. m_console.WriteLine("Starting in Sandbox mode");
  115. }
  116. else
  117. {
  118. GridServers.AssetDll = "OpenSim.GridInterfaces.Remote.dll";
  119. GridServers.GridDll = "OpenSim.GridInterfaces.Remote.dll";
  120. m_console.WriteLine("Starting in Grid mode");
  121. }
  122. GridServers.Initialise();
  123. startuptime = DateTime.Now;
  124. AssetCache = new AssetCache(GridServers.AssetServer);
  125. InventoryCache = new InventoryCache();
  126. PacketServer packetServer = new PacketServer(this);
  127. m_console.WriteLine("Main.cs:Startup() - We are " + regionData.RegionName + " at " + regionData.RegionLocX.ToString() + "," + regionData.RegionLocY.ToString());
  128. m_console.WriteLine("Initialising world");
  129. LocalWorld = new World(this._packetServer.ClientThreads, regionData.RegionHandle, regionData.RegionName);
  130. LocalWorld.InventoryCache = InventoryCache;
  131. LocalWorld.AssetCache = AssetCache;
  132. this._packetServer.LocalWorld = LocalWorld;
  133. this._packetServer.RegisterClientPacketHandlers();
  134. this.physManager = new OpenSim.Physics.Manager.PhysicsManager();
  135. this.physManager.LoadPlugins();
  136. LocalWorld.LoadStorageDLL("OpenSim.Storage.LocalStorageDb4o.dll"); //all these dll names shouldn't be hard coded.
  137. LocalWorld.LoadWorldMap();
  138. m_console.WriteLine("Main.cs:Startup() - Starting up messaging system");
  139. LocalWorld.PhysScene = this.physManager.GetPhysicsScene(this.m_physicsEngine); //should be reading from the config file what physics engine to use
  140. LocalWorld.PhysScene.SetTerrain(LocalWorld.Terrain.getHeights1D());
  141. //should be passing a IGenericConfig object to these so they can read the config data they want from it
  142. GridServers.AssetServer.SetServerInfo(regionData.AssetURL, regionData.AssetSendKey);
  143. IGridServer gridServer = GridServers.GridServer;
  144. gridServer.SetServerInfo(regionData.GridURL, regionData.GridSendKey, regionData.GridRecvKey);
  145. LocalWorld.LoadPrimsFromStorage();
  146. if (m_sandbox)
  147. {
  148. AssetCache.LoadDefaultTextureSet();
  149. }
  150. m_console.WriteLine("Main.cs:Startup() - Initialising HTTP server");
  151. // HttpServer = new SimCAPSHTTPServer(GridServers.GridServer, Cfg.IPListenPort);
  152. _httpServer = new BaseHttpServer(regionData.IPListenPort);
  153. if (gridServer.GetName() == "Remote")
  154. {
  155. //we are in Grid mode so set a XmlRpc handler to handle "expect_user" calls from the user server
  156. _httpServer.AddXmlRPCHandler("expect_user",
  157. delegate(XmlRpcRequest request)
  158. {
  159. Hashtable requestData = (Hashtable)request.Params[0];
  160. AgentCircuitData agent_data = new AgentCircuitData();
  161. agent_data.SessionID = new LLUUID((string)requestData["session_id"]);
  162. agent_data.SecureSessionID = new LLUUID((string)requestData["secure_session_id"]);
  163. agent_data.firstname = (string)requestData["firstname"];
  164. agent_data.lastname = (string)requestData["lastname"];
  165. agent_data.AgentID = new LLUUID((string)requestData["agent_id"]);
  166. agent_data.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
  167. ((RemoteGridBase)gridServer).agentcircuits.Add((uint)agent_data.circuitcode, agent_data);
  168. return new XmlRpcResponse();
  169. });
  170. _httpServer.AddRestHandler("GET", "/simstatus/",
  171. delegate(string request, string path)
  172. {
  173. return "OK";
  174. });
  175. }
  176. LoginServer loginServer = null;
  177. LoginServer adminLoginServer = null;
  178. bool sandBoxWithLoginServer = m_loginserver && m_sandbox;
  179. if (sandBoxWithLoginServer)
  180. {
  181. loginServer = new LoginServer(gridServer, regionData.IPListenAddr, regionData.IPListenPort, this.user_accounts);
  182. loginServer.Startup();
  183. if (user_accounts)
  184. {
  185. //sandbox mode with loginserver using accounts
  186. this.GridServers.UserServer = loginServer;
  187. adminLoginServer = loginServer;
  188. _httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.LocalUserManager.XmlRpcLoginMethod);
  189. }
  190. else
  191. {
  192. //sandbox mode with loginserver not using accounts
  193. _httpServer.AddXmlRPCHandler("login_to_simulator", loginServer.XmlRpcLoginMethod);
  194. }
  195. }
  196. AdminWebFront adminWebFront = new AdminWebFront("Admin", LocalWorld, InventoryCache, adminLoginServer);
  197. adminWebFront.LoadMethods(_httpServer);
  198. m_console.WriteLine("Main.cs:Startup() - Starting HTTP server");
  199. _httpServer.Start();
  200. MainServerListener();
  201. m_heartbeatTimer.Enabled = true;
  202. m_heartbeatTimer.Interval = 100;
  203. m_heartbeatTimer.Elapsed += new ElapsedEventHandler(this.Heartbeat);
  204. }
  205. private SimConfig LoadConfigDll(string dllName)
  206. {
  207. Assembly pluginAssembly = Assembly.LoadFrom(dllName);
  208. SimConfig config = null;
  209. foreach (Type pluginType in pluginAssembly.GetTypes())
  210. {
  211. if (pluginType.IsPublic)
  212. {
  213. if (!pluginType.IsAbstract)
  214. {
  215. Type typeInterface = pluginType.GetInterface("ISimConfig", true);
  216. if (typeInterface != null)
  217. {
  218. ISimConfig plug = (ISimConfig)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
  219. config = plug.GetConfigObject();
  220. break;
  221. }
  222. typeInterface = null;
  223. }
  224. }
  225. }
  226. pluginAssembly = null;
  227. return config;
  228. }
  229. private void OnReceivedData(IAsyncResult result)
  230. {
  231. ipeSender = new IPEndPoint(IPAddress.Any, 0);
  232. epSender = (EndPoint)ipeSender;
  233. Packet packet = null;
  234. int numBytes = Server.EndReceiveFrom(result, ref epSender);
  235. int packetEnd = numBytes - 1;
  236. packet = Packet.BuildPacket(RecvBuffer, ref packetEnd, ZeroBuffer);
  237. // This is either a new client or a packet to send to an old one
  238. // if (OpenSimRoot.Instance.ClientThreads.ContainsKey(epSender))
  239. // do we already have a circuit for this endpoint
  240. if (this.clientCircuits.ContainsKey(epSender))
  241. {
  242. //ClientThreads[this.clientCircuits[epSender]].InPacket(packet);
  243. this._packetServer.ClientInPacket(this.clientCircuits[epSender], packet);
  244. }
  245. else if (packet.Type == PacketType.UseCircuitCode)
  246. { // new client
  247. UseCircuitCodePacket useCircuit = (UseCircuitCodePacket)packet;
  248. this.clientCircuits.Add(epSender, useCircuit.CircuitCode.Code);
  249. SimClient newuser = new SimClient(epSender, useCircuit, LocalWorld, _packetServer.ClientThreads, AssetCache, GridServers.GridServer, this, InventoryCache, m_sandbox);
  250. if ((this.GridServers.UserServer != null) && (user_accounts))
  251. {
  252. newuser.UserServer = this.GridServers.UserServer;
  253. }
  254. //OpenSimRoot.Instance.ClientThreads.Add(epSender, newuser);
  255. this._packetServer.ClientThreads.Add(useCircuit.CircuitCode.Code, newuser);
  256. }
  257. else
  258. { // invalid client
  259. Console.Error.WriteLine("Main.cs:OnReceivedData() - WARNING: Got a packet from an invalid client - " + epSender.ToString());
  260. }
  261. Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
  262. }
  263. private void MainServerListener()
  264. {
  265. m_console.WriteLine("Main.cs:MainServerListener() - New thread started");
  266. m_console.WriteLine("Main.cs:MainServerListener() - Opening UDP socket on " + regionData.IPListenAddr + ":" + regionData.IPListenPort);
  267. ServerIncoming = new IPEndPoint(IPAddress.Any, regionData.IPListenPort);
  268. Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  269. Server.Bind(ServerIncoming);
  270. m_console.WriteLine("Main.cs:MainServerListener() - UDP socket bound, getting ready to listen");
  271. ipeSender = new IPEndPoint(IPAddress.Any, 0);
  272. epSender = (EndPoint)ipeSender;
  273. ReceivedData = new AsyncCallback(this.OnReceivedData);
  274. Server.BeginReceiveFrom(RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref epSender, ReceivedData, null);
  275. m_console.WriteLine("Main.cs:MainServerListener() - Listening...");
  276. }
  277. public void RegisterPacketServer(PacketServer server)
  278. {
  279. this._packetServer = server;
  280. }
  281. public virtual void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode)//EndPoint packetSender)
  282. {
  283. // find the endpoint for this circuit
  284. EndPoint sendto = null;
  285. foreach (KeyValuePair<EndPoint, uint> p in this.clientCircuits)
  286. {
  287. if (p.Value == circuitcode)
  288. {
  289. sendto = p.Key;
  290. break;
  291. }
  292. }
  293. if (sendto != null)
  294. {
  295. //we found the endpoint so send the packet to it
  296. this.Server.SendTo(buffer, size, flags, sendto);
  297. }
  298. }
  299. public virtual void RemoveClientCircuit(uint circuitcode)
  300. {
  301. foreach (KeyValuePair<EndPoint, uint> p in this.clientCircuits)
  302. {
  303. if (p.Value == circuitcode)
  304. {
  305. this.clientCircuits.Remove(p.Key);
  306. break;
  307. }
  308. }
  309. }
  310. /// <summary>
  311. /// Performs any last-minute sanity checking and shuts down the region server
  312. /// </summary>
  313. public virtual void Shutdown()
  314. {
  315. m_console.WriteLine("Main.cs:Shutdown() - Closing all threads");
  316. m_console.WriteLine("Main.cs:Shutdown() - Killing listener thread");
  317. m_console.WriteLine("Main.cs:Shutdown() - Killing clients");
  318. // IMPLEMENT THIS
  319. m_console.WriteLine("Main.cs:Shutdown() - Closing console and terminating");
  320. LocalWorld.Close();
  321. GridServers.Close();
  322. m_console.Close();
  323. Environment.Exit(0);
  324. }
  325. /// <summary>
  326. /// Performs per-frame updates regularly
  327. /// </summary>
  328. /// <param name="sender"></param>
  329. /// <param name="e"></param>
  330. void Heartbeat(object sender, System.EventArgs e)
  331. {
  332. LocalWorld.Update();
  333. }
  334. /// <summary>
  335. /// Runs commands issued by the server console from the operator
  336. /// </summary>
  337. /// <param name="command">The first argument of the parameter (the command)</param>
  338. /// <param name="cmdparams">Additional arguments passed to the command</param>
  339. public void RunCmd(string command, string[] cmdparams)
  340. {
  341. switch (command)
  342. {
  343. case "help":
  344. m_console.WriteLine("show users - show info about connected users");
  345. m_console.WriteLine("shutdown - disconnect all clients and shutdown");
  346. m_console.WriteLine("regenerate - regenerate the sim's terrain");
  347. break;
  348. case "show":
  349. Show(cmdparams[0]);
  350. break;
  351. case "regenerate":
  352. LocalWorld.RegenerateTerrain();
  353. break;
  354. case "shutdown":
  355. Shutdown();
  356. break;
  357. }
  358. }
  359. /// <summary>
  360. /// Outputs to the console information about the region
  361. /// </summary>
  362. /// <param name="ShowWhat">What information to display (valid arguments are "uptime", "users")</param>
  363. public void Show(string ShowWhat)
  364. {
  365. switch (ShowWhat)
  366. {
  367. case "uptime":
  368. m_console.WriteLine("OpenSim has been running since " + startuptime.ToString());
  369. m_console.WriteLine("That is " + (DateTime.Now - startuptime).ToString());
  370. break;
  371. case "users":
  372. OpenSim.world.Avatar TempAv;
  373. 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"));
  374. foreach (libsecondlife.LLUUID UUID in LocalWorld.Entities.Keys)
  375. {
  376. if (LocalWorld.Entities[UUID].ToString() == "OpenSim.world.Avatar")
  377. {
  378. TempAv = (OpenSim.world.Avatar)LocalWorld.Entities[UUID];
  379. 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()));
  380. }
  381. }
  382. break;
  383. }
  384. }
  385. }
  386. }