aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Application/OpenSimBase.cs
blob: 11cacac38b86213bbf639611cf85ce050519bb9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.ClientStack;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Physics.Manager;
using OpenSim.Server.Base;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Services.UserAccountService;

namespace OpenSim
{
    /// <summary>
    /// Common OpenSimulator simulator code
    /// </summary>
    public class OpenSimBase : RegionApplicationBase
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        // These are the names of the plugin-points extended by this
        // class during system startup.
        //

        private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache";
        private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient";

        // OpenSim.ini Section name for ESTATES Settings
        public const string ESTATE_SECTION_NAME = "Estates";

        protected string proxyUrl;
        protected int proxyOffset = 0;
        
        public string userStatsURI = String.Empty;

        protected bool m_autoCreateClientStack = true;

        /// <value>
        /// The file used to load and save prim backup xml if no filename has been specified
        /// </value>
        protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml";

        public ConfigSettings ConfigurationSettings
        {
            get { return m_configSettings; }
            set { m_configSettings = value; }
        }

        protected ConfigSettings m_configSettings;

        protected ConfigurationLoader m_configLoader;

        public ConsoleCommand CreateAccount = null;

        protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>();

        private List<string> m_permsModules;

        private bool m_securePermissionsLoading = true;

        /// <value>
        /// The config information passed into the OpenSimulator region server.
        /// </value>
        public OpenSimConfigSource ConfigSource { get; private set; }

        public List<IClientNetworkServer> ClientServers
        {
            get { return m_clientServers; }
        }

        protected EnvConfigSource m_EnvConfigSource = new EnvConfigSource();

        public EnvConfigSource envConfigSource
        {
            get { return m_EnvConfigSource; }
        }

        protected List<IClientNetworkServer> m_clientServers = new List<IClientNetworkServer>();
       
        public uint HttpServerPort
        {
            get { return m_httpServerPort; }
        }

        protected IRegistryCore m_applicationRegistry = new RegistryCore();

        public IRegistryCore ApplicationRegistry
        {
            get { return m_applicationRegistry; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="configSource"></param>
        public OpenSimBase(IConfigSource configSource) : base()
        {
            LoadConfigSettings(configSource);
        }

        protected virtual void LoadConfigSettings(IConfigSource configSource)
        {
            m_configLoader = new ConfigurationLoader();
            ConfigSource = m_configLoader.LoadConfigSettings(configSource, envConfigSource, out m_configSettings, out m_networkServersInfo);
            Config = ConfigSource.Source;
            ReadExtraConfigSettings();
        }

        protected virtual void ReadExtraConfigSettings()
        {
            IConfig networkConfig = Config.Configs["Network"];
            if (networkConfig != null)
            {
                proxyUrl = networkConfig.GetString("proxy_url", "");
                proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0"));
            }
        }

        protected virtual void LoadPlugins()
        {
            using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this)))
            {
                loader.Load("/OpenSim/Startup");
                m_plugins = loader.Plugins;
            }
        }

        protected override List<string> GetHelpTopics()
        {
            List<string> topics = base.GetHelpTopics();
            Scene s = SceneManager.CurrentOrFirstScene;
            if (s != null && s.GetCommanders() != null)
                topics.AddRange(s.GetCommanders().Keys);

            return topics;
        }

        /// <summary>
        /// Performs startup specific to the region server, including initialization of the scene 
        /// such as loading configuration from disk.
        /// </summary>
        protected override void StartupSpecific()
        {
            IConfig startupConfig = Config.Configs["Startup"];
            if (startupConfig != null)
            {
                string pidFile = startupConfig.GetString("PIDFile", String.Empty);
                if (pidFile != String.Empty)
                    CreatePIDFile(pidFile);
                
                userStatsURI = startupConfig.GetString("Stats_URI", String.Empty);

                m_securePermissionsLoading = startupConfig.GetBoolean("SecurePermissionsLoading", true);

                string permissionModules = startupConfig.GetString("permissionmodules", "DefaultPermissionsModule");
                m_permsModules = new List<string>(permissionModules.Split(','));
            }

            // Load the simulation data service
            IConfig simDataConfig = Config.Configs["SimulationDataStore"];
            if (simDataConfig == null)
                throw new Exception("Configuration file is missing the [SimulationDataStore] section.  Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");

            string module = simDataConfig.GetString("LocalServiceModule", String.Empty);
            if (String.IsNullOrEmpty(module))
                throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section.");

            m_simulationDataService = ServerUtils.LoadPlugin<ISimulationDataService>(module, new object[] { Config });
            if (m_simulationDataService == null)
                throw new Exception(
                    string.Format(
                        "Could not load an ISimulationDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [SimulationDataStore] config section.", 
                        module));

            // Load the estate data service
            IConfig estateDataConfig = Config.Configs["EstateDataStore"];
            if (estateDataConfig == null)
                throw new Exception("Configuration file is missing the [EstateDataStore] section.  Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");

            module = estateDataConfig.GetString("LocalServiceModule", String.Empty);
            if (String.IsNullOrEmpty(module))
                throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] section");

            m_estateDataService = ServerUtils.LoadPlugin<IEstateDataService>(module, new object[] { Config });
            if (m_estateDataService == null)
                throw new Exception(
                    string.Format(
                        "Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.", 
                        module));

            base.StartupSpecific();

            LoadPlugins();

            if (m_plugins.Count == 0) // We failed to load any modules. Mono Addins glitch!
            {
                Environment.Exit(1);
            }

            foreach (IApplicationPlugin plugin in m_plugins)
            {
                plugin.PostInitialise();
            }

            if (m_console != null)
                AddPluginCommands(m_console);
        }

        protected virtual void AddPluginCommands(ICommandConsole console)
        {
            List<string> topics = GetHelpTopics();

            foreach (string topic in topics)
            {
                string capitalizedTopic = char.ToUpper(topic[0]) + topic.Substring(1);

                // This is a hack to allow the user to enter the help command in upper or lowercase.  This will go
                // away at some point.
                console.Commands.AddCommand(capitalizedTopic, false, "help " + topic,
                                              "help " + capitalizedTopic,
                                              "Get help on plugin command '" + topic + "'",
                                              HandleCommanderHelp);
//                console.Commands.AddCommand(capitalizedTopic, false, "help " + capitalizedTopic,
//                                              "help " + capitalizedTopic,
//                                              "Get help on plugin command '" + topic + "'",
//                                              HandleCommanderHelp);

                ICommander commander = null;

                Scene s = SceneManager.CurrentOrFirstScene;

                if (s != null && s.GetCommanders() != null)
                {
                    if (s.GetCommanders().ContainsKey(topic))
                        commander = s.GetCommanders()[topic];
                }

                if (commander == null)
                    continue;

                foreach (string command in commander.Commands.Keys)
                {
                    console.Commands.AddCommand(capitalizedTopic, false,
                                                  topic + " " + command,
                                                  topic + " " + commander.Commands[command].ShortHelp(),
                                                  String.Empty, HandleCommanderCommand);
                }
            }
        }

        private void HandleCommanderCommand(string module, string[] cmd)
        {
            SceneManager.SendCommandToPluginModules(cmd);
        }

        private void HandleCommanderHelp(string module, string[] cmd)
        {
            // Only safe for the interactive console, since it won't
            // let us come here unless both scene and commander exist
            //
            ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1].ToLower());
            if (moduleCommander != null)
                m_console.Output(moduleCommander.Help);
        }

        protected override void Initialize()
        {
            // Called from base.StartUp()

            m_httpServerPort = m_networkServersInfo.HttpListenerPort;
            SceneManager.OnRestartSim += HandleRestartRegion;

            // Only enable the watchdogs when all regions are ready.  Otherwise we get false positives when cpu is
            // heavily used during initial startup.
            //
            // FIXME: It's also possible that region ready status should be flipped during an OAR load since this
            // also makes heavy use of the CPU.
            SceneManager.OnRegionsReadyStatusChange
                += sm => { MemoryWatchdog.Enabled = sm.AllRegionsReady; Watchdog.Enabled = sm.AllRegionsReady; };
        }

        /// <summary>
        /// Execute the region creation process.  This includes setting up scene infrastructure.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="portadd_flag"></param>
        /// <returns></returns>
        public List<IClientNetworkServer> CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene)
        {
            return CreateRegion(regionInfo, portadd_flag, false, out scene);
        }

        /// <summary>
        /// Execute the region creation process.  This includes setting up scene infrastructure.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <returns></returns>
        public List<IClientNetworkServer> CreateRegion(RegionInfo regionInfo, out IScene scene)
        {
            return CreateRegion(regionInfo, false, true, out scene);
        }

        /// <summary>
        /// Execute the region creation process.  This includes setting up scene infrastructure.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="portadd_flag"></param>
        /// <param name="do_post_init"></param>
        /// <returns></returns>
        public List<IClientNetworkServer> CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene)
        {
            int port = regionInfo.InternalEndPoint.Port;

            // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims)
            // Commented this out because otherwise regions can't register with
            // the grid as there is already another region with the same UUID
            // at those coordinates. This is required for the load balancer to work.
            // --Mike, 2009.02.25
            //regionInfo.originRegionID = regionInfo.RegionID;

            // set initial ServerURI
            regionInfo.HttpPort = m_httpServerPort;
            regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort.ToString() + "/";
            
            regionInfo.osSecret = m_osSecret;
            
            if ((proxyUrl.Length > 0) && (portadd_flag))
            {
                // set proxy url to RegionInfo
                regionInfo.proxyUrl = proxyUrl;
                regionInfo.ProxyOffset = proxyOffset;
                Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName);
            }

            List<IClientNetworkServer> clientServers;
            Scene scene = SetupScene(regionInfo, proxyOffset, Config, out clientServers);

            m_log.Info("[MODULES]: Loading Region's modules (old style)");

            // Use this in the future, the line above will be deprecated soon
            m_log.Info("[REGIONMODULES]: Loading Region's modules (new style)");
            IRegionModulesController controller;
            if (ApplicationRegistry.TryGet(out controller))
            {
                controller.AddRegionToModules(scene);
            }
            else m_log.Error("[REGIONMODULES]: The new RegionModulesController is missing...");

            // XPTO: Fix this
//            if (m_securePermissionsLoading)
//            {
//                foreach (string s in m_permsModules)
//                {
//                    if (!scene.RegionModules.ContainsKey(s))
//                    {
//                        bool found = false;
//                        foreach (IRegionModule m in modules)
//                        {
//                            if (m.Name == s)
//                            {
//                                found = true;
//                            }
//                        }
//                        if (!found)
//                        {
//                            m_log.Fatal("[MODULES]: Required module " + s + " not found.");
//                            Environment.Exit(0);
//                        }
//                    }
//                }
//            }

            scene.SetModuleInterfaces();
// First Step of bootreport sequence
            if (scene.SnmpService != null)
            {
                scene.SnmpService.ColdStart(1,scene);
                scene.SnmpService.LinkDown(scene);
            }

            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("Loading prins", scene);
            }

            while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
                SetUpEstateOwner(scene);

            // Prims have to be loaded after module configuration since some modules may be invoked during the load
            scene.LoadPrimsFromStorage(regionInfo.originRegionID);
            
            // TODO : Try setting resource for region xstats here on scene
            MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo));
            
            scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
            scene.EventManager.TriggerParcelPrimCountUpdate();

            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("Grid Registration in progress", scene);
            } 

            try
            {
                scene.RegisterRegionWithGrid();
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[STARTUP]: Registration of region with grid failed, aborting startup due to {0} {1}", 
                    e.Message, e.StackTrace);

                if (scene.SnmpService != null)
                {
                    scene.SnmpService.Critical("Grid registration failed. Startup aborted.", scene);
                }
                // Carrying on now causes a lot of confusion down the
                // line - we need to get the user's attention
                Environment.Exit(1);
            }

            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("Grid Registration done", scene);
            }

            // We need to do this after we've initialized the
            // scripting engines.
            scene.CreateScriptInstances();

            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("ScriptEngine started", scene);
            }

            SceneManager.Add(scene);

            if (m_autoCreateClientStack)
            {
                foreach (IClientNetworkServer clientserver in clientServers)
                {
                    m_clientServers.Add(clientserver);
                    clientserver.Start();
                }
            }

            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("Initializing region modules", scene);
            }
            scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); };

            mscene = scene;

            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("The region is operational", scene);
                scene.SnmpService.LinkUp(scene);
            }

            return clientServers;
        }

        /// <summary>
        /// Try to set up the estate owner for the given scene.
        /// </summary>
        /// <remarks>
        /// The involves asking the user for information about the user on the console.  If the user does not already
        /// exist then it is created.
        /// </remarks>
        /// <param name="scene"></param>
        private void SetUpEstateOwner(Scene scene)
        {
            RegionInfo regionInfo = scene.RegionInfo;

            string estateOwnerFirstName = null;
            string estateOwnerLastName = null;
            string estateOwnerEMail = null;
            string estateOwnerPassword = null;
            string rawEstateOwnerUuid = null;

            if (Config.Configs[ESTATE_SECTION_NAME] != null)
            {
                string defaultEstateOwnerName
                    = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerName", "").Trim();
                string[] ownerNames = defaultEstateOwnerName.Split(' ');

                if (ownerNames.Length >= 2)
                {
                    estateOwnerFirstName = ownerNames[0];
                    estateOwnerLastName = ownerNames[1];
                }

                // Info to be used only on Standalone Mode
                rawEstateOwnerUuid = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerUUID", null);
                estateOwnerEMail = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerEMail", null);
                estateOwnerPassword = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateOwnerPassword", null);
            }

            MainConsole.Instance.OutputFormat("Estate {0} has no owner set.", regionInfo.EstateSettings.EstateName);
            List<char> excluded = new List<char>(new char[1]{' '});


            if (estateOwnerFirstName == null || estateOwnerLastName == null)
            {
                estateOwnerFirstName = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test", excluded);
                estateOwnerLastName = MainConsole.Instance.CmdPrompt("Estate owner last name", "User", excluded);
            }

            UserAccount account
                = scene.UserAccountService.GetUserAccount(regionInfo.ScopeID, estateOwnerFirstName, estateOwnerLastName);

            if (account == null)
            {

                // XXX: The LocalUserAccountServicesConnector is currently registering its inner service rather than
                // itself!
//                    if (scene.UserAccountService is LocalUserAccountServicesConnector)
//                    {
//                        IUserAccountService innerUas
//                            = ((LocalUserAccountServicesConnector)scene.UserAccountService).UserAccountService;
//
//                        m_log.DebugFormat("B {0}", innerUas.GetType());
//
//                        if (innerUas is UserAccountService)
//                        {

                if (scene.UserAccountService is UserAccountService)
                {
                    if (estateOwnerPassword == null)
                        estateOwnerPassword = MainConsole.Instance.PasswdPrompt("Password");

                    if (estateOwnerEMail == null)
                        estateOwnerEMail = MainConsole.Instance.CmdPrompt("Email");

                    if (rawEstateOwnerUuid == null)
                        rawEstateOwnerUuid = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString());
        
                    UUID estateOwnerUuid = UUID.Zero;
                    if (!UUID.TryParse(rawEstateOwnerUuid, out estateOwnerUuid))
                    {
                        m_log.ErrorFormat("[OPENSIM]: ID {0} is not a valid UUID", rawEstateOwnerUuid);
                        return;
                    }

                    // If we've been given a zero uuid then this signals that we should use a random user id
                    if (estateOwnerUuid == UUID.Zero)
                        estateOwnerUuid = UUID.Random();

                    account
                        = ((UserAccountService)scene.UserAccountService).CreateUser(
                            regionInfo.ScopeID,
                            estateOwnerUuid,
                            estateOwnerFirstName,
                            estateOwnerLastName,
                            estateOwnerPassword,
                            estateOwnerEMail);
                }
            }

            if (account == null)
            {
                m_log.ErrorFormat(
                    "[OPENSIM]: Unable to store account. If this simulator is connected to a grid, you must create the estate owner account first at the grid level.");
            }
            else
            {
                regionInfo.EstateSettings.EstateOwner = account.PrincipalID;
                regionInfo.EstateSettings.Save();
            }
        }

        private void ShutdownRegion(Scene scene)
        {
            m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName);
            if (scene.SnmpService != null)
            {
                scene.SnmpService.BootInfo("The region is shutting down", scene);
                scene.SnmpService.LinkDown(scene);
            }
            IRegionModulesController controller;
            if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller))
            {
                controller.RemoveRegionFromModules(scene);
            }
        }

        public void RemoveRegion(Scene scene, bool cleanup)
        {
            // only need to check this if we are not at the
            // root level
            if ((SceneManager.CurrentScene != null) &&
                (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
            {
                SceneManager.TrySetCurrentScene("..");
            }

            scene.DeleteAllSceneObjects();
            SceneManager.CloseScene(scene);
            ShutdownClientServer(scene.RegionInfo);
            
            if (!cleanup)
                return;

            if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile))
            {
                if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml"))
                {
                    File.Delete(scene.RegionInfo.RegionFile);
                    m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile);
                }
                if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini"))
                {
                    try
                    {
                        IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile);
                        if (source.Configs[scene.RegionInfo.RegionName] != null)
                        {
                            source.Configs.Remove(scene.RegionInfo.RegionName);

                            if (source.Configs.Count == 0)
                            {
                                File.Delete(scene.RegionInfo.RegionFile);
                            }
                            else
                            {
                                source.Save(scene.RegionInfo.RegionFile);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }

        public void RemoveRegion(string name, bool cleanUp)
        {
            Scene target;
            if (SceneManager.TryGetScene(name, out target))
                RemoveRegion(target, cleanUp);
        }

        /// <summary>
        /// Remove a region from the simulator without deleting it permanently.
        /// </summary>
        /// <param name="scene"></param>
        /// <returns></returns>
        public void CloseRegion(Scene scene)
        {
            // only need to check this if we are not at the
            // root level
            if ((SceneManager.CurrentScene != null) &&
                (SceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
            {
                SceneManager.TrySetCurrentScene("..");
            }

            SceneManager.CloseScene(scene);
            ShutdownClientServer(scene.RegionInfo);
        }
        
        /// <summary>
        /// Remove a region from the simulator without deleting it permanently.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public void CloseRegion(string name)
        {
            Scene target;
            if (SceneManager.TryGetScene(name, out target))
                CloseRegion(target);
        }
        
        /// <summary>
        /// Create a scene and its initial base structures.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="clientServer"> </param>
        /// <returns></returns>
        protected Scene SetupScene(RegionInfo regionInfo, out List<IClientNetworkServer> clientServer)
        {
            return SetupScene(regionInfo, 0, null, out clientServer);
        }

        /// <summary>
        /// Create a scene and its initial base structures.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="proxyOffset"></param>
        /// <param name="configSource"></param>
        /// <param name="clientServer"> </param>
        /// <returns></returns>
        protected Scene SetupScene(
            RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out List<IClientNetworkServer> clientServer)
        {
            List<IClientNetworkServer> clientNetworkServers = null;

            AgentCircuitManager circuitManager = new AgentCircuitManager();
            IPAddress listenIP = regionInfo.InternalEndPoint.Address;
            //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP))
            //    listenIP = IPAddress.Parse("0.0.0.0");

            uint port = (uint) regionInfo.InternalEndPoint.Port;

            if (m_autoCreateClientStack)
            {
                clientNetworkServers = m_clientStackManager.CreateServers(
                        listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource,
                        circuitManager);
            }
            else
            {
                clientServer = null;
            }

            regionInfo.InternalEndPoint.Port = (int) port;

            Scene scene = CreateScene(regionInfo, m_simulationDataService, m_estateDataService, circuitManager);

            if (m_autoCreateClientStack)
            {
                foreach (IClientNetworkServer clientnetserver in clientNetworkServers)
                {
                    clientnetserver.AddScene(scene);
                }
            }
            clientServer = clientNetworkServers;
            scene.LoadWorldMap();

            scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName);
            scene.PhysicsScene.RequestAssetMethod = scene.PhysicsRequestAsset;
            scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised());
            scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight);

            return scene;
        }

        protected override ClientStackManager CreateClientStackManager()
        {
            return new ClientStackManager(m_configSettings.ClientstackDll);
        }

        protected override Scene CreateScene(RegionInfo regionInfo, ISimulationDataService simDataService,
            IEstateDataService estateDataService, AgentCircuitManager circuitManager)
        {
            SceneCommunicationService sceneGridService = new SceneCommunicationService();

            return new Scene(
                regionInfo, circuitManager, sceneGridService,
                simDataService, estateDataService,
                Config, m_version);
        }
        
        protected void ShutdownClientServer(RegionInfo whichRegion)
        {
            // Close and remove the clientserver for a region
            bool foundClientServer = false;
            int clientServerElement = 0;
            Location location = new Location(whichRegion.RegionHandle);

            for (int i = 0; i < m_clientServers.Count; i++)
            {
                if (m_clientServers[i].HandlesRegion(location))
                {
                    clientServerElement = i;
                    foundClientServer = true;
                    break;
                }
            }

            if (foundClientServer)
            {
                m_clientServers[clientServerElement].Stop();
                m_clientServers.RemoveAt(clientServerElement);
            }
        }
        
        protected virtual void HandleRestartRegion(RegionInfo whichRegion)
        {
            m_log.InfoFormat(
                "[OPENSIM]: Got restart signal from SceneManager for region {0} ({1},{2})", 
                whichRegion.RegionName, whichRegion.RegionLocX, whichRegion.RegionLocY);

            ShutdownClientServer(whichRegion);
            IScene scene;
            CreateRegion(whichRegion, true, out scene);
            scene.Start();
        }

        # region Setup methods

        protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier)
        {
            return GetPhysicsScene(
                m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, Config, osSceneIdentifier);
        }

        /// <summary>
        /// Handler to supply the current status of this sim
        /// </summary>
        /// Currently this is always OK if the simulator is still listening for connections on its HTTP service
        public class SimStatusHandler : IStreamedRequestHandler
        {
            public byte[] Handle(string path, Stream request,
                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
            {
                return Util.UTF8.GetBytes("OK");
            }

            public string Name { get { return "SimStatus"; } }
            public string Description { get { return "Simulator Status"; } }

            public string ContentType
            {
                get { return "text/plain"; }
            }

            public string HttpMethod
            {
                get { return "GET"; }
            }

            public string Path
            {
                get { return "/simstatus"; }
            }
        }

        /// <summary>
        /// Handler to supply the current extended status of this sim
        /// Sends the statistical data in a json serialization 
        /// </summary>
        public class XSimStatusHandler : IStreamedRequestHandler
        {
            OpenSimBase m_opensim;
            string osXStatsURI = String.Empty;

            public string Name { get { return "XSimStatus"; } }
            public string Description { get { return "Simulator XStatus"; } }
        
            public XSimStatusHandler(OpenSimBase sim)
            {
                m_opensim = sim;
                osXStatsURI = Util.SHA1Hash(sim.osSecret);
            }
            
            public byte[] Handle(string path, Stream request,
                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
            {
                return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
            }

            public string ContentType
            {
                get { return "text/plain"; }
            }

            public string HttpMethod
            {
                get { return "GET"; }
            }

            public string Path
            {
                // This is for the OpenSimulator instance and is the osSecret hashed
                get { return "/" + osXStatsURI; }
            }
        }

        /// <summary>
        /// Handler to supply the current extended status of this sim to a user configured URI
        /// Sends the statistical data in a json serialization 
        /// If the request contains a key, "callback" the response will be wrappend in the 
        /// associated value for jsonp used with ajax/javascript
        /// </summary>
        public class UXSimStatusHandler : IStreamedRequestHandler
        {
            OpenSimBase m_opensim;
            string osUXStatsURI = String.Empty;

            public string Name { get { return "UXSimStatus"; } }
            public string Description { get { return "Simulator UXStatus"; } }
        
            public UXSimStatusHandler(OpenSimBase sim)
            {
                m_opensim = sim;
                osUXStatsURI = sim.userStatsURI;
                
            }
            
            public byte[] Handle(string path, Stream request,
                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
            {
                return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
            }

            public string ContentType
            {
                get { return "text/plain"; }
            }

            public string HttpMethod
            {
                get { return "GET"; }
            }

            public string Path
            {
                // This is for the OpenSimulator instance and is the user provided URI 
                get { return "/" + osUXStatsURI; }
            }
        }

        #endregion

        /// <summary>
        /// Performs any last-minute sanity checking and shuts down the region server
        /// </summary>
        protected override void ShutdownSpecific()
        {
            if (proxyUrl.Length > 0)
            {
                Util.XmlRpcCommand(proxyUrl, "Stop");
            }

            m_log.Info("[SHUTDOWN]: Closing all threads");
            m_log.Info("[SHUTDOWN]: Killing listener thread");
            m_log.Info("[SHUTDOWN]: Killing clients");
            m_log.Info("[SHUTDOWN]: Closing console and terminating");

            try
            {
                SceneManager.Close();
            }
            catch (Exception e)
            {
                m_log.Error("[SHUTDOWN]: Ignoring failure during shutdown - ", e);
            }

            base.ShutdownSpecific();
        }

        /// <summary>
        /// Get the start time and up time of Region server
        /// </summary>
        /// <param name="starttime">The first out parameter describing when the Region server started</param>
        /// <param name="uptime">The second out parameter describing how long the Region server has run</param>
        public void GetRunTime(out string starttime, out string uptime)
        {
            starttime = m_startuptime.ToString();
            uptime = (DateTime.Now - m_startuptime).ToString();
        }

        /// <summary>
        /// Get the number of the avatars in the Region server
        /// </summary>
        /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param>
        public void GetAvatarNumber(out int usernum)
        {
            usernum = SceneManager.GetCurrentSceneAvatars().Count;
        }

        /// <summary>
        /// Get the number of regions
        /// </summary>
        /// <param name="regionnum">The first out parameter describing the number of regions</param>
        public void GetRegionNumber(out int regionnum)
        {
            regionnum = SceneManager.Scenes.Count;
        }
        
        /// <summary>
        /// Create an estate with an initial region.
        /// </summary>
        /// <remarks>
        /// This method doesn't allow an estate to be created with the same name as existing estates.
        /// </remarks>
        /// <param name="regInfo"></param>
        /// <param name="estatesByName">A list of estate names that already exist.</param>
        /// <param name="estateName">Estate name to create if already known</param>
        /// <returns>true if the estate was created, false otherwise</returns>
        public bool CreateEstate(RegionInfo regInfo, Dictionary<string, EstateSettings> estatesByName, string estateName)
        {
            // Create a new estate
            regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, true);

            string newName;
            if (estateName != null && estateName != "")
                newName = estateName;
            else
                newName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName);

            if (estatesByName.ContainsKey(newName))
            {
                MainConsole.Instance.OutputFormat("An estate named {0} already exists.  Please try again.", newName);
                return false;
            }
            
            regInfo.EstateSettings.EstateName = newName;
            
            // FIXME: Later on, the scene constructor will reload the estate settings no matter what.
            // Therefore, we need to do an initial save here otherwise the new estate name will be reset
            // back to the default.  The reloading of estate settings by scene could be eliminated if it
            // knows that the passed in settings in RegionInfo are already valid.  Also, it might be 
            // possible to eliminate some additional later saves made by callers of this method.
            regInfo.EstateSettings.Save();   
            
            return true;
        }
        
        /// <summary>
        /// Load the estate information for the provided RegionInfo object.
        /// </summary>
        /// <param name="regInfo"></param>
        public bool PopulateRegionEstateInfo(RegionInfo regInfo)
        {
            if (EstateDataService != null)
                regInfo.EstateSettings = EstateDataService.LoadEstateSettings(regInfo.RegionID, false);

            if (regInfo.EstateSettings.EstateID != 0)
                return false;	// estate info in the database did not change

            m_log.WarnFormat("[ESTATE] Region {0} is not part of an estate.", regInfo.RegionName);
            
            List<EstateSettings> estates = EstateDataService.LoadEstateSettingsAll();                
            Dictionary<string, EstateSettings> estatesByName = new Dictionary<string, EstateSettings>();

            foreach (EstateSettings estate in estates)
                estatesByName[estate.EstateName] = estate;

            string defaultEstateName = null;

            if (Config.Configs[ESTATE_SECTION_NAME] != null)
            {
                defaultEstateName = Config.Configs[ESTATE_SECTION_NAME].GetString("DefaultEstateName", null);

                if (defaultEstateName != null)
                {
                    EstateSettings defaultEstate;
                    bool defaultEstateJoined = false;

                    if (estatesByName.ContainsKey(defaultEstateName))
                    {
                        defaultEstate = estatesByName[defaultEstateName];

                        if (EstateDataService.LinkRegion(regInfo.RegionID, (int)defaultEstate.EstateID))
                            defaultEstateJoined = true;
                    }
                    else
                    {
                        if (CreateEstate(regInfo, estatesByName, defaultEstateName))
                            defaultEstateJoined = true;
                    }

                    if (defaultEstateJoined)
                        return true; // need to update the database
                    else
                        m_log.ErrorFormat(
                            "[OPENSIM BASE]: Joining default estate {0} failed", defaultEstateName);
                }
            }

            // If we have no default estate or creation of the default estate failed then ask the user.
            while (true)
            {
                if (estates.Count == 0)
                {
                    m_log.Info("[ESTATE]: No existing estates found.  You must create a new one.");

                    if (CreateEstate(regInfo, estatesByName, null))
                        break;
                    else
                        continue;
                }
                else
                {
                    string response
                        = MainConsole.Instance.CmdPrompt(
                            string.Format(
                                "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
                                "yes",
                                new List<string>() { "yes", "no" });

                    if (response == "no")
                    {
                        if (CreateEstate(regInfo, estatesByName, null))
                            break;
                        else
                            continue;
                    }
                    else
                    {
                        string[] estateNames = estatesByName.Keys.ToArray();
                        response
                            = MainConsole.Instance.CmdPrompt(
                                string.Format(
                                    "Name of estate to join.  Existing estate names are ({0})",
                                    string.Join(", ", estateNames)),
                                estateNames[0]);

                        List<int> estateIDs = EstateDataService.GetEstates(response);
                        if (estateIDs.Count < 1)
                        {
                            MainConsole.Instance.Output("The name you have entered matches no known estate.  Please try again.");
                            continue;
                        }

                        int estateID = estateIDs[0];

                        regInfo.EstateSettings = EstateDataService.LoadEstateSettings(estateID);

                        if (EstateDataService.LinkRegion(regInfo.RegionID, estateID))
                            break;

                        MainConsole.Instance.Output("Joining the estate failed. Please try again.");
                    }
                }
    	    }

    	    return true;	// need to update the database
    	}
    }
    
    public class OpenSimConfigSource
    {
        public IConfigSource Source;
    }
}