RemoteAdminPlugin.cs 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Xml;
  32. using System.Net;
  33. using System.Reflection;
  34. using System.Timers;
  35. using System.Threading;
  36. using log4net;
  37. using Nini.Config;
  38. using Nwc.XmlRpc;
  39. using OpenMetaverse;
  40. using OpenSim;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Communications;
  43. using OpenSim.Framework.Console;
  44. using OpenSim.Framework.Servers;
  45. using OpenSim.Framework.Servers.HttpServer;
  46. using OpenSim.Region.CoreModules.World.Terrain;
  47. using OpenSim.Region.Framework.Interfaces;
  48. using OpenSim.Region.Framework.Scenes;
  49. using OpenSim.Services.Interfaces;
  50. using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
  51. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  52. namespace OpenSim.ApplicationPlugins.RemoteController
  53. {
  54. public class RemoteAdminPlugin : IApplicationPlugin
  55. {
  56. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  57. private static bool m_defaultAvatarsLoaded = false;
  58. private static Object m_requestLock = new Object();
  59. private static Object m_saveOarLock = new Object();
  60. private OpenSimBase m_application;
  61. private IHttpServer m_httpServer;
  62. private IConfig m_config;
  63. private IConfigSource m_configSource;
  64. private string m_requiredPassword = String.Empty;
  65. private HashSet<string> m_accessIP;
  66. private string m_name = "RemoteAdminPlugin";
  67. private string m_version = "0.0";
  68. public string Version
  69. {
  70. get { return m_version; }
  71. }
  72. public string Name
  73. {
  74. get { return m_name; }
  75. }
  76. public void Initialise()
  77. {
  78. m_log.Error("[RADMIN]: " + Name + " cannot be default-initialized!");
  79. throw new PluginNotInitialisedException(Name);
  80. }
  81. public void Initialise(OpenSimBase openSim)
  82. {
  83. m_configSource = openSim.ConfigSource.Source;
  84. try
  85. {
  86. if (m_configSource.Configs["RemoteAdmin"] == null ||
  87. !m_configSource.Configs["RemoteAdmin"].GetBoolean("enabled", false))
  88. {
  89. // No config or disabled
  90. }
  91. else
  92. {
  93. m_config = m_configSource.Configs["RemoteAdmin"];
  94. m_log.Debug("[RADMIN]: Remote Admin Plugin Enabled");
  95. m_requiredPassword = m_config.GetString("access_password", String.Empty);
  96. int port = m_config.GetInt("port", 0);
  97. string accessIP = m_config.GetString("access_ip_addresses", String.Empty);
  98. m_accessIP = new HashSet<string>();
  99. if (accessIP != String.Empty)
  100. {
  101. string[] ips = accessIP.Split(new char[] { ',' });
  102. foreach (string ip in ips)
  103. {
  104. string current = ip.Trim();
  105. if (current != String.Empty)
  106. m_accessIP.Add(current);
  107. }
  108. }
  109. m_application = openSim;
  110. string bind_ip_address = m_config.GetString("bind_ip_address", "0.0.0.0");
  111. IPAddress ipaddr = IPAddress.Parse(bind_ip_address);
  112. m_httpServer = MainServer.GetHttpServer((uint)port,ipaddr);
  113. Dictionary<string, XmlRpcMethod> availableMethods = new Dictionary<string, XmlRpcMethod>();
  114. availableMethods["admin_create_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateRegionMethod);
  115. availableMethods["admin_delete_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcDeleteRegionMethod);
  116. availableMethods["admin_close_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCloseRegionMethod);
  117. availableMethods["admin_modify_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcModifyRegionMethod);
  118. availableMethods["admin_region_query"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRegionQueryMethod);
  119. availableMethods["admin_shutdown"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcShutdownMethod);
  120. availableMethods["admin_broadcast"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAlertMethod);
  121. availableMethods["admin_restart"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRestartMethod);
  122. availableMethods["admin_load_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadHeightmapMethod);
  123. availableMethods["admin_save_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveHeightmapMethod);
  124. // Agent management
  125. availableMethods["admin_get_agents"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcGetAgentsMethod);
  126. availableMethods["admin_teleport_agent"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcTeleportAgentMethod);
  127. // User management
  128. availableMethods["admin_create_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateUserMethod);
  129. availableMethods["admin_create_user_email"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateUserMethod);
  130. availableMethods["admin_exists_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcUserExistsMethod);
  131. availableMethods["admin_update_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcUpdateUserAccountMethod);
  132. // Region state management
  133. availableMethods["admin_load_xml"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadXMLMethod);
  134. availableMethods["admin_save_xml"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveXMLMethod);
  135. availableMethods["admin_load_oar"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadOARMethod);
  136. availableMethods["admin_save_oar"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveOARMethod);
  137. // Estate access list management
  138. availableMethods["admin_acl_clear"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListClear);
  139. availableMethods["admin_acl_add"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListAdd);
  140. availableMethods["admin_acl_remove"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListRemove);
  141. availableMethods["admin_acl_list"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListList);
  142. // Either enable full remote functionality or just selected features
  143. string enabledMethods = m_config.GetString("enabled_methods", "all");
  144. // To get this, you must explicitly specify "all" or
  145. // mention it in a whitelist. It won't be available
  146. // If you just leave the option out!
  147. //
  148. if (!String.IsNullOrEmpty(enabledMethods))
  149. availableMethods["admin_console_command"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcConsoleCommandMethod);
  150. // The assumption here is that simply enabling Remote Admin as before will produce the same
  151. // behavior - enable all methods unless the whitelist is in place for backward-compatibility.
  152. if (enabledMethods.ToLower() == "all" || String.IsNullOrEmpty(enabledMethods))
  153. {
  154. foreach (string method in availableMethods.Keys)
  155. {
  156. m_httpServer.AddXmlRPCHandler(method, availableMethods[method], false);
  157. }
  158. }
  159. else
  160. {
  161. foreach (string enabledMethod in enabledMethods.Split('|'))
  162. {
  163. m_httpServer.AddXmlRPCHandler(enabledMethod, availableMethods[enabledMethod], false);
  164. }
  165. }
  166. }
  167. }
  168. catch (NullReferenceException)
  169. {
  170. // Ignore.
  171. }
  172. }
  173. public void PostInitialise()
  174. {
  175. if (!CreateDefaultAvatars())
  176. {
  177. m_log.Info("[RADMIN]: Default avatars not loaded");
  178. }
  179. }
  180. /// <summary>
  181. /// Invoke an XmlRpc method with the standard actions (password check, etc.)
  182. /// </summary>
  183. /// <param name="method"></param>
  184. private XmlRpcResponse InvokeXmlRpcMethod(
  185. XmlRpcRequest request, IPEndPoint remoteClient, Action<XmlRpcRequest, XmlRpcResponse, IPEndPoint> method)
  186. {
  187. XmlRpcResponse response = new XmlRpcResponse();
  188. Hashtable responseData = new Hashtable();
  189. response.Value = responseData;
  190. try
  191. {
  192. Hashtable requestData = (Hashtable) request.Params[0];
  193. CheckStringParameters(requestData, responseData, new string[] {"password"});
  194. FailIfRemoteAdminNotAllowed((string)requestData["password"], responseData, remoteClient.Address.ToString());
  195. method(request, response, remoteClient);
  196. }
  197. catch (Exception e)
  198. {
  199. m_log.ErrorFormat(
  200. "[RADMIN]: Method {0} failed. Exception {1}{2}", request.MethodName, e.Message, e.StackTrace);
  201. responseData["success"] = false;
  202. responseData["error"] = e.Message;
  203. }
  204. return response;
  205. }
  206. private void FailIfRemoteAdminNotAllowed(string password, Hashtable responseData, string check_ip_address)
  207. {
  208. if (m_accessIP.Count > 0 && !m_accessIP.Contains(check_ip_address))
  209. {
  210. m_log.WarnFormat("[RADMIN]: Unauthorized access blocked from IP {0}", check_ip_address);
  211. responseData["accepted"] = false;
  212. throw new Exception("not authorized");
  213. }
  214. if (m_requiredPassword != String.Empty && password != m_requiredPassword)
  215. {
  216. m_log.WarnFormat("[RADMIN]: Wrong password, blocked access from IP {0}", check_ip_address);
  217. responseData["accepted"] = false;
  218. throw new Exception("wrong password");
  219. }
  220. }
  221. private void XmlRpcRestartMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  222. {
  223. Hashtable responseData = (Hashtable)response.Value;
  224. Hashtable requestData = (Hashtable)request.Params[0];
  225. try
  226. {
  227. m_log.Info("[RADMIN]: Request to restart Region.");
  228. CheckRegionParams(requestData, responseData);
  229. Scene rebootedScene = null;
  230. GetSceneFromRegionParams(requestData, responseData, out rebootedScene);
  231. responseData["success"] = false;
  232. responseData["accepted"] = true;
  233. responseData["rebooting"] = true;
  234. IRestartModule restartModule = rebootedScene.RequestModuleInterface<IRestartModule>();
  235. if (restartModule != null)
  236. {
  237. List<int> times = new List<int> { 30, 15 };
  238. restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), true);
  239. responseData["success"] = true;
  240. }
  241. }
  242. catch (Exception e)
  243. {
  244. // m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace);
  245. responseData["rebooting"] = false;
  246. throw e;
  247. }
  248. m_log.Info("[RADMIN]: Restart Region request complete");
  249. }
  250. private void XmlRpcAlertMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  251. {
  252. m_log.Info("[RADMIN]: Alert request started");
  253. Hashtable responseData = (Hashtable)response.Value;
  254. Hashtable requestData = (Hashtable)request.Params[0];
  255. string message = (string) requestData["message"];
  256. m_log.InfoFormat("[RADMIN]: Broadcasting: {0}", message);
  257. responseData["accepted"] = true;
  258. responseData["success"] = true;
  259. m_application.SceneManager.ForEachScene(
  260. delegate(Scene scene)
  261. {
  262. IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
  263. if (dialogModule != null)
  264. dialogModule.SendGeneralAlert(message);
  265. });
  266. m_log.Info("[RADMIN]: Alert request complete");
  267. }
  268. private void XmlRpcLoadHeightmapMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  269. {
  270. m_log.Info("[RADMIN]: Load height maps request started");
  271. Hashtable responseData = (Hashtable)response.Value;
  272. Hashtable requestData = (Hashtable)request.Params[0];
  273. // m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request);
  274. // foreach (string k in requestData.Keys)
  275. // {
  276. // m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}: >{1}< {2}",
  277. // k, (string)requestData[k], ((string)requestData[k]).Length);
  278. // }
  279. CheckStringParameters(requestData, responseData, new string[] {"filename", "regionid"});
  280. CheckRegionParams(requestData, responseData);
  281. Scene scene = null;
  282. GetSceneFromRegionParams(requestData, responseData, out scene);
  283. string file = (string)requestData["filename"];
  284. responseData["accepted"] = true;
  285. LoadHeightmap(file, scene.RegionInfo.RegionID);
  286. responseData["success"] = true;
  287. m_log.Info("[RADMIN]: Load height maps request complete");
  288. }
  289. private void XmlRpcSaveHeightmapMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  290. {
  291. m_log.Info("[RADMIN]: Save height maps request started");
  292. Hashtable responseData = (Hashtable)response.Value;
  293. Hashtable requestData = (Hashtable)request.Params[0];
  294. // m_log.DebugFormat("[RADMIN]: Save Terrain: XmlRpc {0}", request.ToString());
  295. CheckStringParameters(requestData, responseData, new string[] { "filename", "regionid" });
  296. CheckRegionParams(requestData, responseData);
  297. Scene region = null;
  298. GetSceneFromRegionParams(requestData, responseData, out region);
  299. string file = (string)requestData["filename"];
  300. m_log.InfoFormat("[RADMIN]: Terrain Saving: {0}", file);
  301. responseData["accepted"] = true;
  302. ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
  303. if (null == terrainModule) throw new Exception("terrain module not available");
  304. terrainModule.SaveToFile(file);
  305. responseData["success"] = true;
  306. m_log.Info("[RADMIN]: Save height maps request complete");
  307. }
  308. private void XmlRpcShutdownMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  309. {
  310. m_log.Info("[RADMIN]: Received Shutdown Administrator Request");
  311. Hashtable responseData = (Hashtable)response.Value;
  312. Hashtable requestData = (Hashtable)request.Params[0];
  313. responseData["accepted"] = true;
  314. response.Value = responseData;
  315. int timeout = 2000;
  316. string message;
  317. if (requestData.ContainsKey("shutdown")
  318. && ((string) requestData["shutdown"] == "delayed")
  319. && requestData.ContainsKey("milliseconds"))
  320. {
  321. timeout = Int32.Parse(requestData["milliseconds"].ToString());
  322. message
  323. = "Region is going down in " + ((int) (timeout/1000)).ToString()
  324. + " second(s). Please save what you are doing and log out.";
  325. }
  326. else
  327. {
  328. message = "Region is going down now.";
  329. }
  330. m_application.SceneManager.ForEachScene(
  331. delegate(Scene scene)
  332. {
  333. IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
  334. if (dialogModule != null)
  335. dialogModule.SendGeneralAlert(message);
  336. });
  337. // Perform shutdown
  338. System.Timers.Timer shutdownTimer = new System.Timers.Timer(timeout); // Wait before firing
  339. shutdownTimer.AutoReset = false;
  340. shutdownTimer.Elapsed += new ElapsedEventHandler(shutdownTimer_Elapsed);
  341. lock (shutdownTimer)
  342. {
  343. shutdownTimer.Start();
  344. }
  345. responseData["success"] = true;
  346. m_log.Info("[RADMIN]: Shutdown Administrator Request complete");
  347. }
  348. private void shutdownTimer_Elapsed(object sender, ElapsedEventArgs e)
  349. {
  350. m_application.Shutdown();
  351. }
  352. /// <summary>
  353. /// Create a new region.
  354. /// <summary>
  355. /// <param name="request">incoming XML RPC request</param>
  356. /// <remarks>
  357. /// XmlRpcCreateRegionMethod takes the following XMLRPC
  358. /// parameters
  359. /// <list type="table">
  360. /// <listheader><term>parameter name</term><description>description</description></listheader>
  361. /// <item><term>password</term>
  362. /// <description>admin password as set in OpenSim.ini</description></item>
  363. /// <item><term>region_name</term>
  364. /// <description>desired region name</description></item>
  365. /// <item><term>region_id</term>
  366. /// <description>(optional) desired region UUID</description></item>
  367. /// <item><term>region_x</term>
  368. /// <description>desired region X coordinate (integer)</description></item>
  369. /// <item><term>region_y</term>
  370. /// <description>desired region Y coordinate (integer)</description></item>
  371. /// <item><term>estate_owner_first</term>
  372. /// <description>firstname of estate owner (formerly region master)
  373. /// (required if new estate is being created, optional otherwise)</description></item>
  374. /// <item><term>estate_owner_last</term>
  375. /// <description>lastname of estate owner (formerly region master)
  376. /// (required if new estate is being created, optional otherwise)</description></item>
  377. /// <item><term>estate_owner_uuid</term>
  378. /// <description>explicit UUID to use for estate owner (optional)</description></item>
  379. /// <item><term>listen_ip</term>
  380. /// <description>internal IP address (dotted quad)</description></item>
  381. /// <item><term>listen_port</term>
  382. /// <description>internal port (integer)</description></item>
  383. /// <item><term>external_address</term>
  384. /// <description>external IP address</description></item>
  385. /// <item><term>persist</term>
  386. /// <description>if true, persist the region info
  387. /// ('true' or 'false')</description></item>
  388. /// <item><term>public</term>
  389. /// <description>if true, the region is public
  390. /// ('true' or 'false') (optional, default: true)</description></item>
  391. /// <item><term>enable_voice</term>
  392. /// <description>if true, enable voice on all parcels,
  393. /// ('true' or 'false') (optional, default: false)</description></item>
  394. /// <item><term>estate_name</term>
  395. /// <description>the name of the estate to join (or to create if it doesn't
  396. /// already exist)</description></item>
  397. /// <item><term>region_file</term>
  398. /// <description>The name of the file to persist the region specifications to.
  399. /// If omitted, the region_file_template setting from OpenSim.ini will be used. (optional)</description></item>
  400. /// </list>
  401. ///
  402. /// XmlRpcCreateRegionMethod returns
  403. /// <list type="table">
  404. /// <listheader><term>name</term><description>description</description></listheader>
  405. /// <item><term>success</term>
  406. /// <description>true or false</description></item>
  407. /// <item><term>error</term>
  408. /// <description>error message if success is false</description></item>
  409. /// <item><term>region_uuid</term>
  410. /// <description>UUID of the newly created region</description></item>
  411. /// <item><term>region_name</term>
  412. /// <description>name of the newly created region</description></item>
  413. /// </list>
  414. /// </remarks>
  415. private void XmlRpcCreateRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  416. {
  417. m_log.Info("[RADMIN]: CreateRegion: new request");
  418. Hashtable responseData = (Hashtable)response.Value;
  419. Hashtable requestData = (Hashtable)request.Params[0];
  420. lock (m_requestLock)
  421. {
  422. int m_regionLimit = m_config.GetInt("region_limit", 0);
  423. bool m_enableVoiceForNewRegions = m_config.GetBoolean("create_region_enable_voice", false);
  424. bool m_publicAccess = m_config.GetBoolean("create_region_public", true);
  425. CheckStringParameters(requestData, responseData, new string[]
  426. {
  427. "region_name",
  428. "listen_ip", "external_address",
  429. "estate_name"
  430. });
  431. CheckIntegerParams(requestData, responseData, new string[] {"region_x", "region_y", "listen_port"});
  432. // check whether we still have space left (iff we are using limits)
  433. if (m_regionLimit != 0 && m_application.SceneManager.Scenes.Count >= m_regionLimit)
  434. throw new Exception(String.Format("cannot instantiate new region, server capacity {0} already reached; delete regions first",
  435. m_regionLimit));
  436. // extract or generate region ID now
  437. Scene scene = null;
  438. UUID regionID = UUID.Zero;
  439. if (requestData.ContainsKey("region_id") &&
  440. !String.IsNullOrEmpty((string) requestData["region_id"]))
  441. {
  442. regionID = (UUID) (string) requestData["region_id"];
  443. if (m_application.SceneManager.TryGetScene(regionID, out scene))
  444. throw new Exception(
  445. String.Format("region UUID already in use by region {0}, UUID {1}, <{2},{3}>",
  446. scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
  447. scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
  448. }
  449. else
  450. {
  451. regionID = UUID.Random();
  452. m_log.DebugFormat("[RADMIN] CreateRegion: new region UUID {0}", regionID);
  453. }
  454. // create volatile or persistent region info
  455. RegionInfo region = new RegionInfo();
  456. region.RegionID = regionID;
  457. region.originRegionID = regionID;
  458. region.RegionName = (string) requestData["region_name"];
  459. region.RegionLocX = Convert.ToUInt32(requestData["region_x"]);
  460. region.RegionLocY = Convert.ToUInt32(requestData["region_y"]);
  461. // check for collisions: region name, region UUID,
  462. // region location
  463. if (m_application.SceneManager.TryGetScene(region.RegionName, out scene))
  464. throw new Exception(
  465. String.Format("region name already in use by region {0}, UUID {1}, <{2},{3}>",
  466. scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
  467. scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
  468. if (m_application.SceneManager.TryGetScene(region.RegionLocX, region.RegionLocY, out scene))
  469. throw new Exception(
  470. String.Format("region location <{0},{1}> already in use by region {2}, UUID {3}, <{4},{5}>",
  471. region.RegionLocX, region.RegionLocY,
  472. scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
  473. scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
  474. region.InternalEndPoint =
  475. new IPEndPoint(IPAddress.Parse((string) requestData["listen_ip"]), 0);
  476. region.InternalEndPoint.Port = Convert.ToInt32(requestData["listen_port"]);
  477. if (0 == region.InternalEndPoint.Port) throw new Exception("listen_port is 0");
  478. if (m_application.SceneManager.TryGetScene(region.InternalEndPoint, out scene))
  479. throw new Exception(
  480. String.Format(
  481. "region internal IP {0} and port {1} already in use by region {2}, UUID {3}, <{4},{5}>",
  482. region.InternalEndPoint.Address,
  483. region.InternalEndPoint.Port,
  484. scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
  485. scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
  486. region.ExternalHostName = (string) requestData["external_address"];
  487. bool persist = Convert.ToBoolean(requestData["persist"]);
  488. if (persist)
  489. {
  490. // default place for region configuration files is in the
  491. // Regions directory of the config dir (aka /bin)
  492. string regionConfigPath = Path.Combine(Util.configDir(), "Regions");
  493. try
  494. {
  495. // OpenSim.ini can specify a different regions dir
  496. IConfig startupConfig = (IConfig) m_configSource.Configs["Startup"];
  497. regionConfigPath = startupConfig.GetString("regionload_regionsdir", regionConfigPath).Trim();
  498. }
  499. catch (Exception)
  500. {
  501. // No INI setting recorded.
  502. }
  503. string regionIniPath;
  504. if (requestData.Contains("region_file"))
  505. {
  506. // Make sure that the file to be created is in a subdirectory of the region storage directory.
  507. string requestedFilePath = Path.Combine(regionConfigPath, (string) requestData["region_file"]);
  508. string requestedDirectory = Path.GetDirectoryName(Path.GetFullPath(requestedFilePath));
  509. if (requestedDirectory.StartsWith(Path.GetFullPath(regionConfigPath)))
  510. regionIniPath = requestedFilePath;
  511. else
  512. throw new Exception("Invalid location for region file.");
  513. }
  514. else
  515. {
  516. regionIniPath = Path.Combine(regionConfigPath,
  517. String.Format(
  518. m_config.GetString("region_file_template",
  519. "{0}x{1}-{2}.ini"),
  520. region.RegionLocX.ToString(),
  521. region.RegionLocY.ToString(),
  522. regionID.ToString(),
  523. region.InternalEndPoint.Port.ToString(),
  524. region.RegionName.Replace(" ", "_").Replace(":", "_").
  525. Replace("/", "_")));
  526. }
  527. m_log.DebugFormat("[RADMIN] CreateRegion: persisting region {0} to {1}",
  528. region.RegionID, regionIniPath);
  529. region.SaveRegionToFile("dynamic region", regionIniPath);
  530. }
  531. else
  532. {
  533. region.Persistent = false;
  534. }
  535. // Set the estate
  536. // Check for an existing estate
  537. List<int> estateIDs = m_application.EstateDataService.GetEstates((string) requestData["estate_name"]);
  538. if (estateIDs.Count < 1)
  539. {
  540. UUID userID = UUID.Zero;
  541. if (requestData.ContainsKey("estate_owner_uuid"))
  542. {
  543. // ok, client wants us to use an explicit UUID
  544. // regardless of what the avatar name provided
  545. userID = new UUID((string) requestData["estate_owner_uuid"]);
  546. // Check that the specified user exists
  547. Scene currentOrFirst = m_application.SceneManager.CurrentOrFirstScene;
  548. IUserAccountService accountService = currentOrFirst.UserAccountService;
  549. UserAccount user = accountService.GetUserAccount(currentOrFirst.RegionInfo.ScopeID, userID);
  550. if (user == null)
  551. throw new Exception("Specified user was not found.");
  552. }
  553. else if (requestData.ContainsKey("estate_owner_first") & requestData.ContainsKey("estate_owner_last"))
  554. {
  555. // We need to look up the UUID for the avatar with the provided name.
  556. string ownerFirst = (string) requestData["estate_owner_first"];
  557. string ownerLast = (string) requestData["estate_owner_last"];
  558. Scene currentOrFirst = m_application.SceneManager.CurrentOrFirstScene;
  559. IUserAccountService accountService = currentOrFirst.UserAccountService;
  560. UserAccount user = accountService.GetUserAccount(currentOrFirst.RegionInfo.ScopeID,
  561. ownerFirst, ownerLast);
  562. // Check that the specified user exists
  563. if (user == null)
  564. throw new Exception("Specified user was not found.");
  565. userID = user.PrincipalID;
  566. }
  567. else
  568. {
  569. throw new Exception("Estate owner details not provided.");
  570. }
  571. // Create a new estate with the name provided
  572. region.EstateSettings = m_application.EstateDataService.CreateNewEstate();
  573. region.EstateSettings.EstateName = (string) requestData["estate_name"];
  574. region.EstateSettings.EstateOwner = userID;
  575. // Persistence does not seem to effect the need to save a new estate
  576. region.EstateSettings.Save();
  577. if (!m_application.EstateDataService.LinkRegion(region.RegionID, (int) region.EstateSettings.EstateID))
  578. throw new Exception("Failed to join estate.");
  579. }
  580. else
  581. {
  582. int estateID = estateIDs[0];
  583. region.EstateSettings = m_application.EstateDataService.LoadEstateSettings(region.RegionID, false);
  584. if (region.EstateSettings.EstateID != estateID)
  585. {
  586. // The region is already part of an estate, but not the one we want.
  587. region.EstateSettings = m_application.EstateDataService.LoadEstateSettings(estateID);
  588. if (!m_application.EstateDataService.LinkRegion(region.RegionID, estateID))
  589. throw new Exception("Failed to join estate.");
  590. }
  591. }
  592. // Create the region and perform any initial initialization
  593. IScene newScene;
  594. m_application.CreateRegion(region, out newScene);
  595. // If an access specification was provided, use it.
  596. // Otherwise accept the default.
  597. newScene.RegionInfo.EstateSettings.PublicAccess = GetBoolean(requestData, "public", m_publicAccess);
  598. newScene.RegionInfo.EstateSettings.Save();
  599. // enable voice on newly created region if
  600. // requested by either the XmlRpc request or the
  601. // configuration
  602. if (GetBoolean(requestData, "enable_voice", m_enableVoiceForNewRegions))
  603. {
  604. List<ILandObject> parcels = ((Scene)newScene).LandChannel.AllParcels();
  605. foreach (ILandObject parcel in parcels)
  606. {
  607. parcel.LandData.Flags |= (uint) ParcelFlags.AllowVoiceChat;
  608. parcel.LandData.Flags |= (uint) ParcelFlags.UseEstateVoiceChan;
  609. ((Scene)newScene).LandChannel.UpdateLandObject(parcel.LandData.LocalID, parcel.LandData);
  610. }
  611. }
  612. //Load Heightmap if specified to new region
  613. if (requestData.Contains("heightmap_file"))
  614. {
  615. LoadHeightmap((string)requestData["heightmap_file"], region.RegionID);
  616. }
  617. responseData["success"] = true;
  618. responseData["region_name"] = region.RegionName;
  619. responseData["region_id"] = region.RegionID.ToString();
  620. responseData["region_uuid"] = region.RegionID.ToString(); //Deprecate July 2012
  621. m_log.Info("[RADMIN]: CreateRegion: request complete");
  622. }
  623. }
  624. /// <summary>
  625. /// Delete a new region.
  626. /// <summary>
  627. /// <param name="request">incoming XML RPC request</param>
  628. /// <remarks>
  629. /// XmlRpcDeleteRegionMethod takes the following XMLRPC
  630. /// parameters
  631. /// <list type="table">
  632. /// <listheader><term>parameter name</term><description>description</description></listheader>
  633. /// <item><term>password</term>
  634. /// <description>admin password as set in OpenSim.ini</description></item>
  635. /// <item><term>region_name</term>
  636. /// <description>desired region name</description></item>
  637. /// <item><term>region_id</term>
  638. /// <description>(optional) desired region UUID</description></item>
  639. /// </list>
  640. ///
  641. /// XmlRpcDeleteRegionMethod returns
  642. /// <list type="table">
  643. /// <listheader><term>name</term><description>description</description></listheader>
  644. /// <item><term>success</term>
  645. /// <description>true or false</description></item>
  646. /// <item><term>error</term>
  647. /// <description>error message if success is false</description></item>
  648. /// </list>
  649. /// </remarks>
  650. private void XmlRpcDeleteRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  651. {
  652. m_log.Info("[RADMIN]: DeleteRegion: new request");
  653. Hashtable responseData = (Hashtable)response.Value;
  654. Hashtable requestData = (Hashtable)request.Params[0];
  655. lock (m_requestLock)
  656. {
  657. CheckStringParameters(requestData, responseData, new string[] {"region_name"});
  658. CheckRegionParams(requestData, responseData);
  659. Scene scene = null;
  660. GetSceneFromRegionParams(requestData, responseData, out scene);
  661. m_application.RemoveRegion(scene, true);
  662. responseData["success"] = true;
  663. responseData["region_name"] = scene.RegionInfo.RegionName;
  664. responseData["region_id"] = scene.RegionInfo.RegionID;
  665. m_log.Info("[RADMIN]: DeleteRegion: request complete");
  666. }
  667. }
  668. /// <summary>
  669. /// Close a region.
  670. /// <summary>
  671. /// <param name="request">incoming XML RPC request</param>
  672. /// <remarks>
  673. /// XmlRpcCloseRegionMethod takes the following XMLRPC
  674. /// parameters
  675. /// <list type="table">
  676. /// <listheader><term>parameter name</term><description>description</description></listheader>
  677. /// <item><term>password</term>
  678. /// <description>admin password as set in OpenSim.ini</description></item>
  679. /// <item><term>region_name</term>
  680. /// <description>desired region name</description></item>
  681. /// <item><term>region_id</term>
  682. /// <description>(optional) desired region UUID</description></item>
  683. /// </list>
  684. ///
  685. /// XmlRpcShutdownRegionMethod returns
  686. /// <list type="table">
  687. /// <listheader><term>name</term><description>description</description></listheader>
  688. /// <item><term>success</term>
  689. /// <description>true or false</description></item>
  690. /// <item><term>region_name</term>
  691. /// <description>the region name if success is true</description></item>
  692. /// <item><term>error</term>
  693. /// <description>error message if success is false</description></item>
  694. /// </list>
  695. /// </remarks>
  696. private void XmlRpcCloseRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  697. {
  698. m_log.Info("[RADMIN]: CloseRegion: new request");
  699. Hashtable responseData = (Hashtable)response.Value;
  700. Hashtable requestData = (Hashtable)request.Params[0];
  701. lock (m_requestLock)
  702. {
  703. CheckRegionParams(requestData, responseData);
  704. Scene scene = null;
  705. GetSceneFromRegionParams(requestData, responseData, out scene);
  706. m_application.CloseRegion(scene);
  707. responseData["success"] = true;
  708. responseData["region_name"] = scene.RegionInfo.RegionName;
  709. responseData["region_id"] = scene.RegionInfo.RegionID;
  710. response.Value = responseData;
  711. m_log.Info("[RADMIN]: CloseRegion: request complete");
  712. }
  713. }
  714. /// <summary>
  715. /// Change characteristics of an existing region.
  716. /// <summary>
  717. /// <param name="request">incoming XML RPC request</param>
  718. /// <remarks>
  719. /// XmlRpcModifyRegionMethod takes the following XMLRPC
  720. /// parameters
  721. /// <list type="table">
  722. /// <listheader><term>parameter name</term><description>description</description></listheader>
  723. /// <item><term>password</term>
  724. /// <description>admin password as set in OpenSim.ini</description></item>
  725. /// <item><term>region_name</term>
  726. /// <description>desired region name</description></item>
  727. /// <item><term>region_id</term>
  728. /// <description>(optional) desired region UUID</description></item>
  729. /// <item><term>public</term>
  730. /// <description>if true, set the region to public
  731. /// ('true' or 'false'), else to private</description></item>
  732. /// <item><term>enable_voice</term>
  733. /// <description>if true, enable voice on all parcels of
  734. /// the region, else disable</description></item>
  735. /// </list>
  736. ///
  737. /// XmlRpcModifyRegionMethod returns
  738. /// <list type="table">
  739. /// <listheader><term>name</term><description>description</description></listheader>
  740. /// <item><term>success</term>
  741. /// <description>true or false</description></item>
  742. /// <item><term>error</term>
  743. /// <description>error message if success is false</description></item>
  744. /// </list>
  745. /// </remarks>
  746. private void XmlRpcModifyRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  747. {
  748. m_log.Info("[RADMIN]: ModifyRegion: new request");
  749. Hashtable responseData = (Hashtable)response.Value;
  750. Hashtable requestData = (Hashtable)request.Params[0];
  751. lock (m_requestLock)
  752. {
  753. CheckRegionParams(requestData, responseData);
  754. Scene scene = null;
  755. GetSceneFromRegionParams(requestData, responseData, out scene);
  756. // Modify access
  757. scene.RegionInfo.EstateSettings.PublicAccess =
  758. GetBoolean(requestData,"public", scene.RegionInfo.EstateSettings.PublicAccess);
  759. if (scene.RegionInfo.Persistent)
  760. scene.RegionInfo.EstateSettings.Save();
  761. if (requestData.ContainsKey("enable_voice"))
  762. {
  763. bool enableVoice = GetBoolean(requestData, "enable_voice", true);
  764. List<ILandObject> parcels = ((Scene)scene).LandChannel.AllParcels();
  765. foreach (ILandObject parcel in parcels)
  766. {
  767. if (enableVoice)
  768. {
  769. parcel.LandData.Flags |= (uint)ParcelFlags.AllowVoiceChat;
  770. parcel.LandData.Flags |= (uint)ParcelFlags.UseEstateVoiceChan;
  771. }
  772. else
  773. {
  774. parcel.LandData.Flags &= ~(uint)ParcelFlags.AllowVoiceChat;
  775. parcel.LandData.Flags &= ~(uint)ParcelFlags.UseEstateVoiceChan;
  776. }
  777. scene.LandChannel.UpdateLandObject(parcel.LandData.LocalID, parcel.LandData);
  778. }
  779. }
  780. responseData["success"] = true;
  781. responseData["region_name"] = scene.RegionInfo.RegionName;
  782. responseData["region_id"] = scene.RegionInfo.RegionID;
  783. m_log.Info("[RADMIN]: ModifyRegion: request complete");
  784. }
  785. }
  786. /// <summary>
  787. /// Create a new user account.
  788. /// <summary>
  789. /// <param name="request">incoming XML RPC request</param>
  790. /// <remarks>
  791. /// XmlRpcCreateUserMethod takes the following XMLRPC
  792. /// parameters
  793. /// <list type="table">
  794. /// <listheader><term>parameter name</term><description>description</description></listheader>
  795. /// <item><term>password</term>
  796. /// <description>admin password as set in OpenSim.ini</description></item>
  797. /// <item><term>user_firstname</term>
  798. /// <description>avatar's first name</description></item>
  799. /// <item><term>user_lastname</term>
  800. /// <description>avatar's last name</description></item>
  801. /// <item><term>user_password</term>
  802. /// <description>avatar's password</description></item>
  803. /// <item><term>user_email</term>
  804. /// <description>email of the avatar's owner (optional)</description></item>
  805. /// <item><term>start_region_x</term>
  806. /// <description>avatar's start region coordinates, X value</description></item>
  807. /// <item><term>start_region_y</term>
  808. /// <description>avatar's start region coordinates, Y value</description></item>
  809. /// </list>
  810. ///
  811. /// XmlRpcCreateUserMethod returns
  812. /// <list type="table">
  813. /// <listheader><term>name</term><description>description</description></listheader>
  814. /// <item><term>success</term>
  815. /// <description>true or false</description></item>
  816. /// <item><term>error</term>
  817. /// <description>error message if success is false</description></item>
  818. /// <item><term>avatar_uuid</term>
  819. /// <description>UUID of the newly created avatar
  820. /// account; UUID.Zero if failed.
  821. /// </description></item>
  822. /// </list>
  823. /// </remarks>
  824. private void XmlRpcCreateUserMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  825. {
  826. m_log.Info("[RADMIN]: CreateUser: new request");
  827. Hashtable responseData = (Hashtable)response.Value;
  828. Hashtable requestData = (Hashtable)request.Params[0];
  829. lock (m_requestLock)
  830. {
  831. try
  832. {
  833. // check completeness
  834. CheckStringParameters(requestData, responseData, new string[]
  835. {
  836. "user_firstname",
  837. "user_lastname", "user_password",
  838. });
  839. CheckIntegerParams(requestData, responseData, new string[] {"start_region_x", "start_region_y"});
  840. // do the job
  841. string firstName = (string) requestData["user_firstname"];
  842. string lastName = (string) requestData["user_lastname"];
  843. string password = (string) requestData["user_password"];
  844. uint regionXLocation = Convert.ToUInt32(requestData["start_region_x"]);
  845. uint regionYLocation = Convert.ToUInt32(requestData["start_region_y"]);
  846. string email = ""; // empty string for email
  847. if (requestData.Contains("user_email"))
  848. email = (string)requestData["user_email"];
  849. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  850. UUID scopeID = scene.RegionInfo.ScopeID;
  851. UserAccount account = CreateUser(scopeID, firstName, lastName, password, email);
  852. if (null == account)
  853. throw new Exception(String.Format("failed to create new user {0} {1}",
  854. firstName, lastName));
  855. // Set home position
  856. GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
  857. (int)(regionXLocation * Constants.RegionSize), (int)(regionYLocation * Constants.RegionSize));
  858. if (null == home)
  859. {
  860. m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", firstName, lastName);
  861. }
  862. else
  863. {
  864. scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  865. m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, firstName, lastName);
  866. }
  867. // Establish the avatar's initial appearance
  868. UpdateUserAppearance(responseData, requestData, account.PrincipalID);
  869. responseData["success"] = true;
  870. responseData["avatar_uuid"] = account.PrincipalID.ToString();
  871. m_log.InfoFormat("[RADMIN]: CreateUser: User {0} {1} created, UUID {2}", firstName, lastName, account.PrincipalID);
  872. }
  873. catch (Exception e)
  874. {
  875. responseData["avatar_uuid"] = UUID.Zero.ToString();
  876. throw e;
  877. }
  878. m_log.Info("[RADMIN]: CreateUser: request complete");
  879. }
  880. }
  881. /// <summary>
  882. /// Check whether a certain user account exists.
  883. /// <summary>
  884. /// <param name="request">incoming XML RPC request</param>
  885. /// <remarks>
  886. /// XmlRpcUserExistsMethod takes the following XMLRPC
  887. /// parameters
  888. /// <list type="table">
  889. /// <listheader><term>parameter name</term><description>description</description></listheader>
  890. /// <item><term>password</term>
  891. /// <description>admin password as set in OpenSim.ini</description></item>
  892. /// <item><term>user_firstname</term>
  893. /// <description>avatar's first name</description></item>
  894. /// <item><term>user_lastname</term>
  895. /// <description>avatar's last name</description></item>
  896. /// </list>
  897. ///
  898. /// XmlRpcCreateUserMethod returns
  899. /// <list type="table">
  900. /// <listheader><term>name</term><description>description</description></listheader>
  901. /// <item><term>user_firstname</term>
  902. /// <description>avatar's first name</description></item>
  903. /// <item><term>user_lastname</term>
  904. /// <description>avatar's last name</description></item>
  905. /// <item><term>user_lastlogin</term>
  906. /// <description>avatar's last login time (secs since UNIX epoch)</description></item>
  907. /// <item><term>success</term>
  908. /// <description>true or false</description></item>
  909. /// <item><term>error</term>
  910. /// <description>error message if success is false</description></item>
  911. /// </list>
  912. /// </remarks>
  913. private void XmlRpcUserExistsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  914. {
  915. m_log.Info("[RADMIN]: UserExists: new request");
  916. Hashtable responseData = (Hashtable)response.Value;
  917. Hashtable requestData = (Hashtable)request.Params[0];
  918. // check completeness
  919. CheckStringParameters(requestData, responseData, new string[] {"user_firstname", "user_lastname"});
  920. string firstName = (string) requestData["user_firstname"];
  921. string lastName = (string) requestData["user_lastname"];
  922. responseData["user_firstname"] = firstName;
  923. responseData["user_lastname"] = lastName;
  924. UUID scopeID = m_application.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
  925. UserAccount account = m_application.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);
  926. if (null == account)
  927. {
  928. responseData["success"] = false;
  929. responseData["lastlogin"] = 0;
  930. }
  931. else
  932. {
  933. GridUserInfo userInfo = m_application.SceneManager.CurrentOrFirstScene.GridUserService.GetGridUserInfo(account.PrincipalID.ToString());
  934. if (userInfo != null)
  935. responseData["lastlogin"] = userInfo.Login;
  936. else
  937. responseData["lastlogin"] = 0;
  938. responseData["success"] = true;
  939. }
  940. m_log.Info("[RADMIN]: UserExists: request complete");
  941. }
  942. /// <summary>
  943. /// Update a user account.
  944. /// <summary>
  945. /// <param name="request">incoming XML RPC request</param>
  946. /// <remarks>
  947. /// XmlRpcUpdateUserAccountMethod takes the following XMLRPC
  948. /// parameters (changeable ones are optional)
  949. /// <list type="table">
  950. /// <listheader><term>parameter name</term><description>description</description></listheader>
  951. /// <item><term>password</term>
  952. /// <description>admin password as set in OpenSim.ini</description></item>
  953. /// <item><term>user_firstname</term>
  954. /// <description>avatar's first name (cannot be changed)</description></item>
  955. /// <item><term>user_lastname</term>
  956. /// <description>avatar's last name (cannot be changed)</description></item>
  957. /// <item><term>user_password</term>
  958. /// <description>avatar's password (changeable)</description></item>
  959. /// <item><term>start_region_x</term>
  960. /// <description>avatar's start region coordinates, X
  961. /// value (changeable)</description></item>
  962. /// <item><term>start_region_y</term>
  963. /// <description>avatar's start region coordinates, Y
  964. /// value (changeable)</description></item>
  965. /// <item><term>about_real_world (not implemented yet)</term>
  966. /// <description>"about" text of avatar owner (changeable)</description></item>
  967. /// <item><term>about_virtual_world (not implemented yet)</term>
  968. /// <description>"about" text of avatar (changeable)</description></item>
  969. /// </list>
  970. ///
  971. /// XmlRpcCreateUserMethod returns
  972. /// <list type="table">
  973. /// <listheader><term>name</term><description>description</description></listheader>
  974. /// <item><term>success</term>
  975. /// <description>true or false</description></item>
  976. /// <item><term>error</term>
  977. /// <description>error message if success is false</description></item>
  978. /// <item><term>avatar_uuid</term>
  979. /// <description>UUID of the updated avatar
  980. /// account; UUID.Zero if failed.
  981. /// </description></item>
  982. /// </list>
  983. /// </remarks>
  984. private void XmlRpcUpdateUserAccountMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  985. {
  986. m_log.Info("[RADMIN]: UpdateUserAccount: new request");
  987. m_log.Warn("[RADMIN]: This method needs update for 0.7");
  988. Hashtable responseData = (Hashtable)response.Value;
  989. Hashtable requestData = (Hashtable)request.Params[0];
  990. lock (m_requestLock)
  991. {
  992. try
  993. {
  994. // check completeness
  995. CheckStringParameters(requestData, responseData, new string[] {
  996. "user_firstname",
  997. "user_lastname"});
  998. // do the job
  999. string firstName = (string) requestData["user_firstname"];
  1000. string lastName = (string) requestData["user_lastname"];
  1001. string password = String.Empty;
  1002. uint? regionXLocation = null;
  1003. uint? regionYLocation = null;
  1004. // uint? ulaX = null;
  1005. // uint? ulaY = null;
  1006. // uint? ulaZ = null;
  1007. // uint? usaX = null;
  1008. // uint? usaY = null;
  1009. // uint? usaZ = null;
  1010. // string aboutFirstLive = String.Empty;
  1011. // string aboutAvatar = String.Empty;
  1012. if (requestData.ContainsKey("user_password")) password = (string) requestData["user_password"];
  1013. if (requestData.ContainsKey("start_region_x"))
  1014. regionXLocation = Convert.ToUInt32(requestData["start_region_x"]);
  1015. if (requestData.ContainsKey("start_region_y"))
  1016. regionYLocation = Convert.ToUInt32(requestData["start_region_y"]);
  1017. // if (requestData.ContainsKey("start_lookat_x"))
  1018. // ulaX = Convert.ToUInt32((Int32) requestData["start_lookat_x"]);
  1019. // if (requestData.ContainsKey("start_lookat_y"))
  1020. // ulaY = Convert.ToUInt32((Int32) requestData["start_lookat_y"]);
  1021. // if (requestData.ContainsKey("start_lookat_z"))
  1022. // ulaZ = Convert.ToUInt32((Int32) requestData["start_lookat_z"]);
  1023. // if (requestData.ContainsKey("start_standat_x"))
  1024. // usaX = Convert.ToUInt32((Int32) requestData["start_standat_x"]);
  1025. // if (requestData.ContainsKey("start_standat_y"))
  1026. // usaY = Convert.ToUInt32((Int32) requestData["start_standat_y"]);
  1027. // if (requestData.ContainsKey("start_standat_z"))
  1028. // usaZ = Convert.ToUInt32((Int32) requestData["start_standat_z"]);
  1029. // if (requestData.ContainsKey("about_real_world"))
  1030. // aboutFirstLive = (string)requestData["about_real_world"];
  1031. // if (requestData.ContainsKey("about_virtual_world"))
  1032. // aboutAvatar = (string)requestData["about_virtual_world"];
  1033. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1034. UUID scopeID = scene.RegionInfo.ScopeID;
  1035. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);
  1036. if (null == account)
  1037. throw new Exception(String.Format("avatar {0} {1} does not exist", firstName, lastName));
  1038. if (!String.IsNullOrEmpty(password))
  1039. {
  1040. m_log.DebugFormat("[RADMIN]: UpdateUserAccount: updating password for avatar {0} {1}", firstName, lastName);
  1041. ChangeUserPassword(firstName, lastName, password);
  1042. }
  1043. // if (null != usaX) userProfile.HomeLocationX = (uint) usaX;
  1044. // if (null != usaY) userProfile.HomeLocationY = (uint) usaY;
  1045. // if (null != usaZ) userProfile.HomeLocationZ = (uint) usaZ;
  1046. // if (null != ulaX) userProfile.HomeLookAtX = (uint) ulaX;
  1047. // if (null != ulaY) userProfile.HomeLookAtY = (uint) ulaY;
  1048. // if (null != ulaZ) userProfile.HomeLookAtZ = (uint) ulaZ;
  1049. // if (String.Empty != aboutFirstLive) userProfile.FirstLifeAboutText = aboutFirstLive;
  1050. // if (String.Empty != aboutAvatar) userProfile.AboutText = aboutAvatar;
  1051. // Set home position
  1052. if ((null != regionXLocation) && (null != regionYLocation))
  1053. {
  1054. GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
  1055. (int)(regionXLocation * Constants.RegionSize), (int)(regionYLocation * Constants.RegionSize));
  1056. if (null == home) {
  1057. m_log.WarnFormat("[RADMIN]: Unable to set home region for updated user account {0} {1}", firstName, lastName);
  1058. } else {
  1059. scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  1060. m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, firstName, lastName);
  1061. }
  1062. }
  1063. // User has been created. Now establish gender and appearance.
  1064. UpdateUserAppearance(responseData, requestData, account.PrincipalID);
  1065. responseData["success"] = true;
  1066. responseData["avatar_uuid"] = account.PrincipalID.ToString();
  1067. m_log.InfoFormat("[RADMIN]: UpdateUserAccount: account for user {0} {1} updated, UUID {2}",
  1068. firstName, lastName,
  1069. account.PrincipalID);
  1070. }
  1071. catch (Exception e)
  1072. {
  1073. responseData["avatar_uuid"] = UUID.Zero.ToString();
  1074. throw e;
  1075. }
  1076. m_log.Info("[RADMIN]: UpdateUserAccount: request complete");
  1077. }
  1078. }
  1079. /// <summary>
  1080. /// Load an OAR file into a region..
  1081. /// <summary>
  1082. /// <param name="request">incoming XML RPC request</param>
  1083. /// <remarks>
  1084. /// XmlRpcLoadOARMethod takes the following XMLRPC
  1085. /// parameters
  1086. /// <list type="table">
  1087. /// <listheader><term>parameter name</term><description>description</description></listheader>
  1088. /// <item><term>password</term>
  1089. /// <description>admin password as set in OpenSim.ini</description></item>
  1090. /// <item><term>filename</term>
  1091. /// <description>file name of the OAR file</description></item>
  1092. /// <item><term>region_uuid</term>
  1093. /// <description>UUID of the region</description></item>
  1094. /// <item><term>region_name</term>
  1095. /// <description>region name</description></item>
  1096. /// <item><term>merge</term>
  1097. /// <description>true if oar should be merged</description></item>
  1098. /// <item><term>skip-assets</term>
  1099. /// <description>true if assets should be skiped</description></item>
  1100. /// </list>
  1101. ///
  1102. /// <code>region_uuid</code> takes precedence over
  1103. /// <code>region_name</code> if both are present; one of both
  1104. /// must be present.
  1105. ///
  1106. /// XmlRpcLoadOARMethod returns
  1107. /// <list type="table">
  1108. /// <listheader><term>name</term><description>description</description></listheader>
  1109. /// <item><term>success</term>
  1110. /// <description>true or false</description></item>
  1111. /// <item><term>error</term>
  1112. /// <description>error message if success is false</description></item>
  1113. /// </list>
  1114. /// </remarks>
  1115. private void XmlRpcLoadOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1116. {
  1117. m_log.Info("[RADMIN]: Received Load OAR Administrator Request");
  1118. Hashtable responseData = (Hashtable)response.Value;
  1119. Hashtable requestData = (Hashtable)request.Params[0];
  1120. lock (m_requestLock)
  1121. {
  1122. try
  1123. {
  1124. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1125. CheckRegionParams(requestData, responseData);
  1126. Scene scene = null;
  1127. GetSceneFromRegionParams(requestData, responseData, out scene);
  1128. string filename = (string) requestData["filename"];
  1129. bool mergeOar = false;
  1130. bool skipAssets = false;
  1131. if ((string)requestData["merge"] == "true")
  1132. {
  1133. mergeOar = true;
  1134. }
  1135. if ((string)requestData["skip-assets"] == "true")
  1136. {
  1137. skipAssets = true;
  1138. }
  1139. IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
  1140. if (archiver != null)
  1141. archiver.DearchiveRegion(filename, mergeOar, skipAssets, Guid.Empty);
  1142. else
  1143. throw new Exception("Archiver module not present for scene");
  1144. responseData["loaded"] = true;
  1145. }
  1146. catch (Exception e)
  1147. {
  1148. responseData["loaded"] = false;
  1149. throw e;
  1150. }
  1151. m_log.Info("[RADMIN]: Load OAR Administrator Request complete");
  1152. }
  1153. }
  1154. /// <summary>
  1155. /// Save a region to an OAR file
  1156. /// <summary>
  1157. /// <param name="request">incoming XML RPC request</param>
  1158. /// <remarks>
  1159. /// XmlRpcSaveOARMethod takes the following XMLRPC
  1160. /// parameters
  1161. /// <list type="table">
  1162. /// <listheader><term>parameter name</term><description>description</description></listheader>
  1163. /// <item><term>password</term>
  1164. /// <description>admin password as set in OpenSim.ini</description></item>
  1165. /// <item><term>filename</term>
  1166. /// <description>file name for the OAR file</description></item>
  1167. /// <item><term>region_uuid</term>
  1168. /// <description>UUID of the region</description></item>
  1169. /// <item><term>region_name</term>
  1170. /// <description>region name</description></item>
  1171. /// <item><term>profile</term>
  1172. /// <description>profile url</description></item>
  1173. /// <item><term>noassets</term>
  1174. /// <description>true if no assets should be saved</description></item>
  1175. /// <item><term>perm</term>
  1176. /// <description>C and/or T</description></item>
  1177. /// </list>
  1178. ///
  1179. /// <code>region_uuid</code> takes precedence over
  1180. /// <code>region_name</code> if both are present; one of both
  1181. /// must be present.
  1182. ///
  1183. /// XmlRpcLoadOARMethod returns
  1184. /// <list type="table">
  1185. /// <listheader><term>name</term><description>description</description></listheader>
  1186. /// <item><term>success</term>
  1187. /// <description>true or false</description></item>
  1188. /// <item><term>error</term>
  1189. /// <description>error message if success is false</description></item>
  1190. /// </list>
  1191. /// </remarks>
  1192. private void XmlRpcSaveOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1193. {
  1194. m_log.Info("[RADMIN]: Received Save OAR Administrator Request");
  1195. Hashtable responseData = (Hashtable)response.Value;
  1196. Hashtable requestData = (Hashtable)request.Params[0];
  1197. try
  1198. {
  1199. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1200. CheckRegionParams(requestData, responseData);
  1201. Scene scene = null;
  1202. GetSceneFromRegionParams(requestData, responseData, out scene);
  1203. string filename = (string)requestData["filename"];
  1204. Dictionary<string, object> options = new Dictionary<string, object>();
  1205. //if (requestData.Contains("version"))
  1206. //{
  1207. // options["version"] = (string)requestData["version"];
  1208. //}
  1209. if (requestData.Contains("home"))
  1210. {
  1211. options["home"] = (string)requestData["home"];
  1212. }
  1213. if ((string)requestData["noassets"] == "true")
  1214. {
  1215. options["noassets"] = (string)requestData["noassets"] ;
  1216. }
  1217. if (requestData.Contains("perm"))
  1218. {
  1219. options["checkPermissions"] = (string)requestData["perm"];
  1220. }
  1221. IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
  1222. if (archiver != null)
  1223. {
  1224. scene.EventManager.OnOarFileSaved += RemoteAdminOarSaveCompleted;
  1225. archiver.ArchiveRegion(filename, options);
  1226. lock (m_saveOarLock)
  1227. Monitor.Wait(m_saveOarLock,5000);
  1228. scene.EventManager.OnOarFileSaved -= RemoteAdminOarSaveCompleted;
  1229. }
  1230. else
  1231. {
  1232. throw new Exception("Archiver module not present for scene");
  1233. }
  1234. responseData["saved"] = true;
  1235. }
  1236. catch (Exception e)
  1237. {
  1238. responseData["saved"] = false;
  1239. throw e;
  1240. }
  1241. m_log.Info("[RADMIN]: Save OAR Administrator Request complete");
  1242. }
  1243. private void RemoteAdminOarSaveCompleted(Guid uuid, string name)
  1244. {
  1245. m_log.DebugFormat("[RADMIN]: File processing complete for {0}", name);
  1246. lock (m_saveOarLock)
  1247. Monitor.Pulse(m_saveOarLock);
  1248. }
  1249. private void XmlRpcLoadXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1250. {
  1251. m_log.Info("[RADMIN]: Received Load XML Administrator Request");
  1252. Hashtable responseData = (Hashtable)response.Value;
  1253. Hashtable requestData = (Hashtable)request.Params[0];
  1254. lock (m_requestLock)
  1255. {
  1256. try
  1257. {
  1258. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1259. CheckRegionParams(requestData, responseData);
  1260. Scene scene = null;
  1261. GetSceneFromRegionParams(requestData, responseData, out scene);
  1262. string filename = (string) requestData["filename"];
  1263. responseData["switched"] = true;
  1264. string xml_version = "1";
  1265. if (requestData.Contains("xml_version"))
  1266. {
  1267. xml_version = (string) requestData["xml_version"];
  1268. }
  1269. switch (xml_version)
  1270. {
  1271. case "1":
  1272. m_application.SceneManager.LoadCurrentSceneFromXml(filename, true, new Vector3(0, 0, 0));
  1273. break;
  1274. case "2":
  1275. m_application.SceneManager.LoadCurrentSceneFromXml2(filename);
  1276. break;
  1277. default:
  1278. throw new Exception(String.Format("unknown Xml{0} format", xml_version));
  1279. }
  1280. responseData["loaded"] = true;
  1281. }
  1282. catch (Exception e)
  1283. {
  1284. responseData["loaded"] = false;
  1285. responseData["switched"] = false;
  1286. throw e;
  1287. }
  1288. m_log.Info("[RADMIN]: Load XML Administrator Request complete");
  1289. }
  1290. }
  1291. private void XmlRpcSaveXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1292. {
  1293. m_log.Info("[RADMIN]: Received Save XML Administrator Request");
  1294. Hashtable responseData = (Hashtable)response.Value;
  1295. Hashtable requestData = (Hashtable)request.Params[0];
  1296. try
  1297. {
  1298. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1299. CheckRegionParams(requestData, responseData);
  1300. Scene scene = null;
  1301. GetSceneFromRegionParams(requestData, responseData, out scene);
  1302. string filename = (string) requestData["filename"];
  1303. responseData["switched"] = true;
  1304. string xml_version = "1";
  1305. if (requestData.Contains("xml_version"))
  1306. {
  1307. xml_version = (string) requestData["xml_version"];
  1308. }
  1309. switch (xml_version)
  1310. {
  1311. case "1":
  1312. m_application.SceneManager.SaveCurrentSceneToXml(filename);
  1313. break;
  1314. case "2":
  1315. m_application.SceneManager.SaveCurrentSceneToXml2(filename);
  1316. break;
  1317. default:
  1318. throw new Exception(String.Format("unknown Xml{0} format", xml_version));
  1319. }
  1320. responseData["saved"] = true;
  1321. }
  1322. catch (Exception e)
  1323. {
  1324. responseData["saved"] = false;
  1325. responseData["switched"] = false;
  1326. throw e;
  1327. }
  1328. m_log.Info("[RADMIN]: Save XML Administrator Request complete");
  1329. }
  1330. private void XmlRpcRegionQueryMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1331. {
  1332. m_log.Info("[RADMIN]: Received Query XML Administrator Request");
  1333. Hashtable responseData = (Hashtable)response.Value;
  1334. Hashtable requestData = (Hashtable)request.Params[0];
  1335. CheckRegionParams(requestData, responseData);
  1336. Scene scene = null;
  1337. GetSceneFromRegionParams(requestData, responseData, out scene);
  1338. int health = scene.GetHealth();
  1339. responseData["health"] = health;
  1340. responseData["success"] = true;
  1341. m_log.Info("[RADMIN]: Query XML Administrator Request complete");
  1342. }
  1343. private void XmlRpcConsoleCommandMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1344. {
  1345. m_log.Info("[RADMIN]: Received Command XML Administrator Request");
  1346. Hashtable responseData = (Hashtable)response.Value;
  1347. Hashtable requestData = (Hashtable)request.Params[0];
  1348. CheckStringParameters(requestData, responseData, new string[] {"command"});
  1349. MainConsole.Instance.RunCommand(requestData["command"].ToString());
  1350. m_log.Info("[RADMIN]: Command XML Administrator Request complete");
  1351. }
  1352. private void XmlRpcAccessListClear(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1353. {
  1354. m_log.Info("[RADMIN]: Received Access List Clear Request");
  1355. Hashtable responseData = (Hashtable)response.Value;
  1356. Hashtable requestData = (Hashtable)request.Params[0];
  1357. responseData["success"] = true;
  1358. CheckRegionParams(requestData, responseData);
  1359. Scene scene = null;
  1360. GetSceneFromRegionParams(requestData, responseData, out scene);
  1361. scene.RegionInfo.EstateSettings.EstateAccess = new UUID[]{};
  1362. if (scene.RegionInfo.Persistent)
  1363. scene.RegionInfo.EstateSettings.Save();
  1364. m_log.Info("[RADMIN]: Access List Clear Request complete");
  1365. }
  1366. private void XmlRpcAccessListAdd(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1367. {
  1368. m_log.Info("[RADMIN]: Received Access List Add Request");
  1369. Hashtable responseData = (Hashtable)response.Value;
  1370. Hashtable requestData = (Hashtable)request.Params[0];
  1371. CheckRegionParams(requestData, responseData);
  1372. Scene scene = null;
  1373. GetSceneFromRegionParams(requestData, responseData, out scene);
  1374. int addedUsers = 0;
  1375. if (requestData.Contains("users"))
  1376. {
  1377. UUID scopeID = scene.RegionInfo.ScopeID;
  1378. IUserAccountService userService = scene.UserAccountService;
  1379. Hashtable users = (Hashtable) requestData["users"];
  1380. List<UUID> uuids = new List<UUID>();
  1381. foreach (string name in users.Values)
  1382. {
  1383. string[] parts = name.Split();
  1384. UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
  1385. if (account != null)
  1386. {
  1387. uuids.Add(account.PrincipalID);
  1388. m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
  1389. }
  1390. }
  1391. List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
  1392. foreach (UUID uuid in uuids)
  1393. {
  1394. if (!accessControlList.Contains(uuid))
  1395. {
  1396. accessControlList.Add(uuid);
  1397. addedUsers++;
  1398. }
  1399. }
  1400. scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
  1401. if (scene.RegionInfo.Persistent)
  1402. scene.RegionInfo.EstateSettings.Save();
  1403. }
  1404. responseData["added"] = addedUsers;
  1405. m_log.Info("[RADMIN]: Access List Add Request complete");
  1406. }
  1407. private void XmlRpcAccessListRemove(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1408. {
  1409. m_log.Info("[RADMIN]: Received Access List Remove Request");
  1410. Hashtable responseData = (Hashtable)response.Value;
  1411. Hashtable requestData = (Hashtable)request.Params[0];
  1412. CheckRegionParams(requestData, responseData);
  1413. Scene scene = null;
  1414. GetSceneFromRegionParams(requestData, responseData, out scene);
  1415. int removedUsers = 0;
  1416. if (requestData.Contains("users"))
  1417. {
  1418. UUID scopeID = scene.RegionInfo.ScopeID;
  1419. IUserAccountService userService = scene.UserAccountService;
  1420. //UserProfileCacheService ups = m_application.CommunicationsManager.UserProfileCacheService;
  1421. Hashtable users = (Hashtable) requestData["users"];
  1422. List<UUID> uuids = new List<UUID>();
  1423. foreach (string name in users.Values)
  1424. {
  1425. string[] parts = name.Split();
  1426. UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
  1427. if (account != null)
  1428. {
  1429. uuids.Add(account.PrincipalID);
  1430. }
  1431. }
  1432. List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
  1433. foreach (UUID uuid in uuids)
  1434. {
  1435. if (accessControlList.Contains(uuid))
  1436. {
  1437. accessControlList.Remove(uuid);
  1438. removedUsers++;
  1439. }
  1440. }
  1441. scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
  1442. if (scene.RegionInfo.Persistent)
  1443. scene.RegionInfo.EstateSettings.Save();
  1444. }
  1445. responseData["removed"] = removedUsers;
  1446. responseData["success"] = true;
  1447. m_log.Info("[RADMIN]: Access List Remove Request complete");
  1448. }
  1449. private void XmlRpcAccessListList(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1450. {
  1451. m_log.Info("[RADMIN]: Received Access List List Request");
  1452. Hashtable responseData = (Hashtable)response.Value;
  1453. Hashtable requestData = (Hashtable)request.Params[0];
  1454. CheckRegionParams(requestData, responseData);
  1455. Scene scene = null;
  1456. GetSceneFromRegionParams(requestData, responseData, out scene);
  1457. UUID[] accessControlList = scene.RegionInfo.EstateSettings.EstateAccess;
  1458. Hashtable users = new Hashtable();
  1459. foreach (UUID user in accessControlList)
  1460. {
  1461. UUID scopeID = scene.RegionInfo.ScopeID;
  1462. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, user);
  1463. if (account != null)
  1464. {
  1465. users[user.ToString()] = account.FirstName + " " + account.LastName;
  1466. }
  1467. }
  1468. responseData["users"] = users;
  1469. responseData["success"] = true;
  1470. m_log.Info("[RADMIN]: Access List List Request complete");
  1471. }
  1472. private void XmlRpcGetAgentsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1473. {
  1474. Hashtable responseData = (Hashtable)response.Value;
  1475. Hashtable requestData = (Hashtable)request.Params[0];
  1476. bool includeChildren = false;
  1477. if (requestData.Contains("include_children"))
  1478. bool.TryParse((string)requestData["include_children"], out includeChildren);
  1479. Scene scene;
  1480. GetSceneFromRegionParams(requestData, responseData, out scene);
  1481. ArrayList xmlRpcRegions = new ArrayList();
  1482. responseData["regions"] = xmlRpcRegions;
  1483. Hashtable xmlRpcRegion = new Hashtable();
  1484. xmlRpcRegions.Add(xmlRpcRegion);
  1485. xmlRpcRegion["name"] = scene.Name;
  1486. xmlRpcRegion["id"] = scene.RegionInfo.RegionID.ToString();
  1487. List<ScenePresence> agents = scene.GetScenePresences();
  1488. ArrayList xmlrpcAgents = new ArrayList();
  1489. foreach (ScenePresence agent in agents)
  1490. {
  1491. if (agent.IsChildAgent && !includeChildren)
  1492. continue;
  1493. Hashtable xmlRpcAgent = new Hashtable();
  1494. xmlRpcAgent.Add("name", agent.Name);
  1495. xmlRpcAgent.Add("id", agent.UUID.ToString());
  1496. xmlRpcAgent.Add("type", agent.PresenceType.ToString());
  1497. xmlRpcAgent.Add("current_parcel_id", agent.currentParcelUUID.ToString());
  1498. Vector3 pos = agent.AbsolutePosition;
  1499. xmlRpcAgent.Add("pos_x", pos.X.ToString());
  1500. xmlRpcAgent.Add("pos_y", pos.Y.ToString());
  1501. xmlRpcAgent.Add("pos_z", pos.Z.ToString());
  1502. Vector3 lookAt = agent.Lookat;
  1503. xmlRpcAgent.Add("lookat_x", lookAt.X.ToString());
  1504. xmlRpcAgent.Add("lookat_y", lookAt.Y.ToString());
  1505. xmlRpcAgent.Add("lookat_z", lookAt.Z.ToString());
  1506. Vector3 vel = agent.Velocity;
  1507. xmlRpcAgent.Add("vel_x", vel.X.ToString());
  1508. xmlRpcAgent.Add("vel_y", vel.Y.ToString());
  1509. xmlRpcAgent.Add("vel_z", vel.Z.ToString());
  1510. xmlRpcAgent.Add("is_flying", agent.Flying.ToString());
  1511. xmlRpcAgent.Add("is_sat_on_ground", agent.SitGround.ToString());
  1512. xmlRpcAgent.Add("is_sat_on_object", agent.IsSatOnObject.ToString());
  1513. xmlrpcAgents.Add(xmlRpcAgent);
  1514. }
  1515. m_log.DebugFormat(
  1516. "[REMOTE ADMIN]: XmlRpcGetAgents found {0} agents in {1}", xmlrpcAgents.Count, scene.Name);
  1517. xmlRpcRegion["agents"] = xmlrpcAgents;
  1518. responseData["success"] = true;
  1519. }
  1520. private void XmlRpcTeleportAgentMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1521. {
  1522. Hashtable responseData = (Hashtable)response.Value;
  1523. Hashtable requestData = (Hashtable)request.Params[0];
  1524. UUID agentId;
  1525. string regionName = null;
  1526. Vector3 pos, lookAt;
  1527. ScenePresence sp = null;
  1528. if (requestData.Contains("agent_first_name") && requestData.Contains("agent_last_name"))
  1529. {
  1530. string firstName = requestData["agent_first_name"].ToString();
  1531. string lastName = requestData["agent_last_name"].ToString();
  1532. m_application.SceneManager.TryGetRootScenePresenceByName(firstName, lastName, out sp);
  1533. if (sp == null)
  1534. throw new Exception(
  1535. string.Format(
  1536. "No agent found with agent_first_name {0} and agent_last_name {1}", firstName, lastName));
  1537. }
  1538. else if (requestData.Contains("agent_id"))
  1539. {
  1540. string rawAgentId = (string)requestData["agent_id"];
  1541. if (!UUID.TryParse(rawAgentId, out agentId))
  1542. throw new Exception(string.Format("agent_id {0} does not have the correct id format", rawAgentId));
  1543. m_application.SceneManager.TryGetRootScenePresence(agentId, out sp);
  1544. if (sp == null)
  1545. throw new Exception(string.Format("No agent with agent_id {0} found in this simulator", agentId));
  1546. }
  1547. else
  1548. {
  1549. throw new Exception("No agent_id or agent_first_name and agent_last_name parameters specified");
  1550. }
  1551. if (requestData.Contains("region_name"))
  1552. regionName = (string)requestData["region_name"];
  1553. pos.X = ParseFloat(requestData, "pos_x", sp.AbsolutePosition.X);
  1554. pos.Y = ParseFloat(requestData, "pos_y", sp.AbsolutePosition.Y);
  1555. pos.Z = ParseFloat(requestData, "pos_z", sp.AbsolutePosition.Z);
  1556. lookAt.X = ParseFloat(requestData, "lookat_x", sp.Lookat.X);
  1557. lookAt.Y = ParseFloat(requestData, "lookat_y", sp.Lookat.Y);
  1558. lookAt.Z = ParseFloat(requestData, "lookat_z", sp.Lookat.Z);
  1559. sp.Scene.RequestTeleportLocation(
  1560. sp.ControllingClient, regionName, pos, lookAt, (uint)Constants.TeleportFlags.ViaLocation);
  1561. // We have no way of telling the failure of the actual teleport
  1562. responseData["success"] = true;
  1563. }
  1564. /// <summary>
  1565. /// Parse a float with the given parameter name from a request data hash table.
  1566. /// </summary>
  1567. /// <remarks>
  1568. /// Will throw an exception if parameter is not a float.
  1569. /// Will not throw if parameter is not found, passes back default value instead.
  1570. /// </remarks>
  1571. /// <param name="requestData"></param>
  1572. /// <param name="paramName"></param>
  1573. /// <param name="defaultVal"></param>
  1574. /// <returns></returns>
  1575. private static float ParseFloat(Hashtable requestData, string paramName, float defaultVal)
  1576. {
  1577. if (requestData.Contains(paramName))
  1578. {
  1579. string rawVal = (string)requestData[paramName];
  1580. float val;
  1581. if (!float.TryParse(rawVal, out val))
  1582. throw new Exception(string.Format("{0} {1} is not a valid float", paramName, rawVal));
  1583. else
  1584. return val;
  1585. }
  1586. else
  1587. {
  1588. return defaultVal;
  1589. }
  1590. }
  1591. private static void CheckStringParameters(Hashtable requestData, Hashtable responseData, string[] param)
  1592. {
  1593. foreach (string parameter in param)
  1594. {
  1595. if (!requestData.Contains(parameter))
  1596. {
  1597. responseData["accepted"] = false;
  1598. throw new Exception(String.Format("missing string parameter {0}", parameter));
  1599. }
  1600. if (String.IsNullOrEmpty((string) requestData[parameter]))
  1601. {
  1602. responseData["accepted"] = false;
  1603. throw new Exception(String.Format("parameter {0} is empty", parameter));
  1604. }
  1605. }
  1606. }
  1607. private static void CheckIntegerParams(Hashtable requestData, Hashtable responseData, string[] param)
  1608. {
  1609. foreach (string parameter in param)
  1610. {
  1611. if (!requestData.Contains(parameter))
  1612. {
  1613. responseData["accepted"] = false;
  1614. throw new Exception(String.Format("missing integer parameter {0}", parameter));
  1615. }
  1616. }
  1617. }
  1618. private void CheckRegionParams(Hashtable requestData, Hashtable responseData)
  1619. {
  1620. //Checks if region parameters exist and gives exeption if no parameters are given
  1621. if ((requestData.ContainsKey("region_id") && !String.IsNullOrEmpty((string)requestData["region_id"])) ||
  1622. (requestData.ContainsKey("region_name") && !String.IsNullOrEmpty((string)requestData["region_name"])))
  1623. {
  1624. return;
  1625. }
  1626. #region Deprecate July 2012
  1627. //region_ID, regionid, region_uuid will be deprecated in July 2012!!!!!!
  1628. else if (requestData.ContainsKey("regionid") &&
  1629. !String.IsNullOrEmpty((string)requestData["regionid"]))
  1630. {
  1631. m_log.WarnFormat("[RADMIN]: Use of parameter regionid will be deprecated as of July 2012. Use region_id instead");
  1632. }
  1633. else if (requestData.ContainsKey("region_ID") &&
  1634. !String.IsNullOrEmpty((string)requestData["region_ID"]))
  1635. {
  1636. m_log.WarnFormat("[RADMIN]: Use of parameter region_ID will be deprecated as of July 2012. Use region_id instead");
  1637. }
  1638. else if (requestData.ContainsKey("regionID") &&
  1639. !String.IsNullOrEmpty((string)requestData["regionID"]))
  1640. {
  1641. m_log.WarnFormat("[RADMIN]: Use of parameter regionID will be deprecated as of July 2012. Use region_id instead");
  1642. }
  1643. else if (requestData.ContainsKey("region_uuid") &&
  1644. !String.IsNullOrEmpty((string)requestData["region_uuid"]))
  1645. {
  1646. m_log.WarnFormat("[RADMIN]: Use of parameter region_uuid will be deprecated as of July 2012. Use region_id instead");
  1647. }
  1648. #endregion
  1649. else
  1650. {
  1651. responseData["accepted"] = false;
  1652. throw new Exception("no region_name or region_id given");
  1653. }
  1654. }
  1655. private void GetSceneFromRegionParams(Hashtable requestData, Hashtable responseData, out Scene scene)
  1656. {
  1657. scene = null;
  1658. if (requestData.ContainsKey("region_id") &&
  1659. !String.IsNullOrEmpty((string)requestData["region_id"]))
  1660. {
  1661. UUID regionID = (UUID)(string)requestData["region_id"];
  1662. if (!m_application.SceneManager.TryGetScene(regionID, out scene))
  1663. {
  1664. responseData["error"] = String.Format("Region ID {0} not found", regionID);
  1665. throw new Exception(String.Format("Region ID {0} not found", regionID));
  1666. }
  1667. }
  1668. #region Deprecate July 2012
  1669. else if (requestData.ContainsKey("regionid") &&
  1670. !String.IsNullOrEmpty((string)requestData["regionid"]))
  1671. {
  1672. m_log.WarnFormat("[RADMIN]: Use of parameter regionid will be deprecated as of July 2012. Use region_id instead");
  1673. UUID regionID = (UUID)(string)requestData["regionid"];
  1674. if (!m_application.SceneManager.TryGetScene(regionID, out scene))
  1675. {
  1676. responseData["error"] = String.Format("Region ID {0} not found", regionID);
  1677. throw new Exception(String.Format("Region ID {0} not found", regionID));
  1678. }
  1679. }
  1680. else if (requestData.ContainsKey("region_ID") &&
  1681. !String.IsNullOrEmpty((string)requestData["region_ID"]))
  1682. {
  1683. m_log.WarnFormat("[RADMIN]: Use of parameter region_ID will be deprecated as of July 2012. Use region_id instead");
  1684. UUID regionID = (UUID)(string)requestData["region_ID"];
  1685. if (!m_application.SceneManager.TryGetScene(regionID, out scene))
  1686. {
  1687. responseData["error"] = String.Format("Region ID {0} not found", regionID);
  1688. throw new Exception(String.Format("Region ID {0} not found", regionID));
  1689. }
  1690. }
  1691. else if (requestData.ContainsKey("regionID") &&
  1692. !String.IsNullOrEmpty((string)requestData["regionID"]))
  1693. {
  1694. m_log.WarnFormat("[RADMIN]: Use of parameter regionID will be deprecated as of July 2012. Use region_id instead");
  1695. UUID regionID = (UUID)(string)requestData["regionID"];
  1696. if (!m_application.SceneManager.TryGetScene(regionID, out scene))
  1697. {
  1698. responseData["error"] = String.Format("Region ID {0} not found", regionID);
  1699. throw new Exception(String.Format("Region ID {0} not found", regionID));
  1700. }
  1701. }
  1702. else if (requestData.ContainsKey("region_uuid") &&
  1703. !String.IsNullOrEmpty((string)requestData["region_uuid"]))
  1704. {
  1705. m_log.WarnFormat("[RADMIN]: Use of parameter region_uuid will be deprecated as of July 2012. Use region_id instead");
  1706. UUID regionID = (UUID)(string)requestData["region_uuid"];
  1707. if (!m_application.SceneManager.TryGetScene(regionID, out scene))
  1708. {
  1709. responseData["error"] = String.Format("Region ID {0} not found", regionID);
  1710. throw new Exception(String.Format("Region ID {0} not found", regionID));
  1711. }
  1712. }
  1713. #endregion
  1714. else if (requestData.ContainsKey("region_name") &&
  1715. !String.IsNullOrEmpty((string)requestData["region_name"]))
  1716. {
  1717. string regionName = (string)requestData["region_name"];
  1718. if (!m_application.SceneManager.TryGetScene(regionName, out scene))
  1719. {
  1720. responseData["error"] = String.Format("Region {0} not found", regionName);
  1721. throw new Exception(String.Format("Region {0} not found", regionName));
  1722. }
  1723. }
  1724. else
  1725. {
  1726. responseData["error"] = "no region_name or region_id given";
  1727. throw new Exception("no region_name or region_id given");
  1728. }
  1729. return;
  1730. }
  1731. private bool GetBoolean(Hashtable requestData, string tag, bool defaultValue)
  1732. {
  1733. // If an access value has been provided, apply it.
  1734. if (requestData.Contains(tag))
  1735. {
  1736. switch (((string)requestData[tag]).ToLower())
  1737. {
  1738. case "true" :
  1739. case "t" :
  1740. case "1" :
  1741. return true;
  1742. case "false" :
  1743. case "f" :
  1744. case "0" :
  1745. return false;
  1746. default :
  1747. return defaultValue;
  1748. }
  1749. }
  1750. else
  1751. return defaultValue;
  1752. }
  1753. private int GetIntegerAttribute(XmlNode node, string attribute, int defaultValue)
  1754. {
  1755. try { return Convert.ToInt32(node.Attributes[attribute].Value); } catch{}
  1756. return defaultValue;
  1757. }
  1758. private uint GetUnsignedAttribute(XmlNode node, string attribute, uint defaultValue)
  1759. {
  1760. try { return Convert.ToUInt32(node.Attributes[attribute].Value); } catch{}
  1761. return defaultValue;
  1762. }
  1763. private string GetStringAttribute(XmlNode node, string attribute, string defaultValue)
  1764. {
  1765. try { return node.Attributes[attribute].Value; } catch{}
  1766. return defaultValue;
  1767. }
  1768. public void Dispose()
  1769. {
  1770. }
  1771. /// <summary>
  1772. /// Create a user
  1773. /// </summary>
  1774. /// <param name="scopeID"></param>
  1775. /// <param name="firstName"></param>
  1776. /// <param name="lastName"></param>
  1777. /// <param name="password"></param>
  1778. /// <param name="email"></param>
  1779. private UserAccount CreateUser(UUID scopeID, string firstName, string lastName, string password, string email)
  1780. {
  1781. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1782. IUserAccountService userAccountService = scene.UserAccountService;
  1783. IGridService gridService = scene.GridService;
  1784. IAuthenticationService authenticationService = scene.AuthenticationService;
  1785. IGridUserService gridUserService = scene.GridUserService;
  1786. IInventoryService inventoryService = scene.InventoryService;
  1787. UserAccount account = userAccountService.GetUserAccount(scopeID, firstName, lastName);
  1788. if (null == account)
  1789. {
  1790. account = new UserAccount(scopeID, UUID.Random(), firstName, lastName, email);
  1791. if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
  1792. {
  1793. account.ServiceURLs = new Dictionary<string, object>();
  1794. account.ServiceURLs["HomeURI"] = string.Empty;
  1795. account.ServiceURLs["GatekeeperURI"] = string.Empty;
  1796. account.ServiceURLs["InventoryServerURI"] = string.Empty;
  1797. account.ServiceURLs["AssetServerURI"] = string.Empty;
  1798. }
  1799. if (userAccountService.StoreUserAccount(account))
  1800. {
  1801. bool success;
  1802. if (authenticationService != null)
  1803. {
  1804. success = authenticationService.SetPassword(account.PrincipalID, password);
  1805. if (!success)
  1806. m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
  1807. firstName, lastName);
  1808. }
  1809. GridRegion home = null;
  1810. if (gridService != null)
  1811. {
  1812. List<GridRegion> defaultRegions = gridService.GetDefaultRegions(UUID.Zero);
  1813. if (defaultRegions != null && defaultRegions.Count >= 1)
  1814. home = defaultRegions[0];
  1815. if (gridUserService != null && home != null)
  1816. gridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  1817. else
  1818. m_log.WarnFormat("[RADMIN]: Unable to set home for account {0} {1}.",
  1819. firstName, lastName);
  1820. }
  1821. else
  1822. m_log.WarnFormat("[RADMIN]: Unable to retrieve home region for account {0} {1}.",
  1823. firstName, lastName);
  1824. if (inventoryService != null)
  1825. {
  1826. success = inventoryService.CreateUserInventory(account.PrincipalID);
  1827. if (!success)
  1828. m_log.WarnFormat("[RADMIN]: Unable to create inventory for account {0} {1}.",
  1829. firstName, lastName);
  1830. }
  1831. m_log.InfoFormat("[RADMIN]: Account {0} {1} created successfully", firstName, lastName);
  1832. return account;
  1833. } else {
  1834. m_log.ErrorFormat("[RADMIN]: Account creation failed for account {0} {1}", firstName, lastName);
  1835. }
  1836. }
  1837. else
  1838. {
  1839. m_log.ErrorFormat("[RADMIN]: A user with the name {0} {1} already exists!", firstName, lastName);
  1840. }
  1841. return null;
  1842. }
  1843. /// <summary>
  1844. /// Change password
  1845. /// </summary>
  1846. /// <param name="firstName"></param>
  1847. /// <param name="lastName"></param>
  1848. /// <param name="password"></param>
  1849. private bool ChangeUserPassword(string firstName, string lastName, string password)
  1850. {
  1851. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1852. IUserAccountService userAccountService = scene.UserAccountService;
  1853. IAuthenticationService authenticationService = scene.AuthenticationService;
  1854. UserAccount account = userAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
  1855. if (null != account)
  1856. {
  1857. bool success = false;
  1858. if (authenticationService != null)
  1859. success = authenticationService.SetPassword(account.PrincipalID, password);
  1860. if (!success)
  1861. {
  1862. m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
  1863. firstName, lastName);
  1864. return false;
  1865. }
  1866. return true;
  1867. }
  1868. else
  1869. {
  1870. m_log.ErrorFormat("[RADMIN]: No such user");
  1871. return false;
  1872. }
  1873. }
  1874. private bool LoadHeightmap(string file, UUID regionID)
  1875. {
  1876. m_log.InfoFormat("[RADMIN]: Terrain Loading: {0}", file);
  1877. Scene region = null;
  1878. if (!m_application.SceneManager.TryGetScene(regionID, out region))
  1879. {
  1880. m_log.InfoFormat("[RADMIN]: unable to get a scene with that name: {0}", regionID.ToString());
  1881. return false;
  1882. }
  1883. ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
  1884. if (null == terrainModule) throw new Exception("terrain module not available");
  1885. if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
  1886. {
  1887. m_log.Info("[RADMIN]: Terrain path is URL");
  1888. Uri result;
  1889. if (Uri.TryCreate(file, UriKind.RelativeOrAbsolute, out result))
  1890. {
  1891. // the url is valid
  1892. string fileType = file.Substring(file.LastIndexOf('/') + 1);
  1893. terrainModule.LoadFromStream(fileType, result);
  1894. }
  1895. }
  1896. else
  1897. {
  1898. terrainModule.LoadFromFile(file);
  1899. }
  1900. m_log.Info("[RADMIN]: Load height maps request complete");
  1901. return true;
  1902. }
  1903. /// <summary>
  1904. /// This method is called by the user-create and user-modify methods to establish
  1905. /// or change, the user's appearance. Default avatar names can be specified via
  1906. /// the config file, but must correspond to avatars in the default appearance
  1907. /// file, or pre-existing in the user database.
  1908. /// This should probably get moved into somewhere more core eventually.
  1909. /// </summary>
  1910. private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
  1911. {
  1912. m_log.DebugFormat("[RADMIN]: updateUserAppearance");
  1913. string defaultMale = m_config.GetString("default_male", "Default Male");
  1914. string defaultFemale = m_config.GetString("default_female", "Default Female");
  1915. string defaultNeutral = m_config.GetString("default_female", "Default Default");
  1916. string model = String.Empty;
  1917. // Has a gender preference been supplied?
  1918. if (requestData.Contains("gender"))
  1919. {
  1920. switch ((string)requestData["gender"])
  1921. {
  1922. case "m" :
  1923. case "male" :
  1924. model = defaultMale;
  1925. break;
  1926. case "f" :
  1927. case "female" :
  1928. model = defaultFemale;
  1929. break;
  1930. case "n" :
  1931. case "neutral" :
  1932. default :
  1933. model = defaultNeutral;
  1934. break;
  1935. }
  1936. }
  1937. // Has an explicit model been specified?
  1938. if (requestData.Contains("model") && (String.IsNullOrEmpty((string)requestData["gender"])))
  1939. {
  1940. model = (string)requestData["model"];
  1941. }
  1942. // No appearance attributes were set
  1943. if (String.IsNullOrEmpty(model))
  1944. {
  1945. m_log.DebugFormat("[RADMIN]: Appearance update not requested");
  1946. return;
  1947. }
  1948. m_log.DebugFormat("[RADMIN]: Setting appearance for avatar {0}, using model <{1}>", userid, model);
  1949. string[] modelSpecifiers = model.Split();
  1950. if (modelSpecifiers.Length != 2)
  1951. {
  1952. m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
  1953. // modelSpecifiers = dmodel.Split();
  1954. return;
  1955. }
  1956. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1957. UUID scopeID = scene.RegionInfo.ScopeID;
  1958. UserAccount modelProfile = scene.UserAccountService.GetUserAccount(scopeID, modelSpecifiers[0], modelSpecifiers[1]);
  1959. if (modelProfile == null)
  1960. {
  1961. m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model);
  1962. return;
  1963. }
  1964. // Set current user's appearance. This bit is easy. The appearance structure is populated with
  1965. // actual asset ids, however to complete the magic we need to populate the inventory with the
  1966. // assets in question.
  1967. EstablishAppearance(userid, modelProfile.PrincipalID);
  1968. m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}",
  1969. userid, model);
  1970. }
  1971. /// <summary>
  1972. /// This method is called by updateAvatarAppearance once any specified model has been
  1973. /// ratified, or an appropriate default value has been adopted. The intended prototype
  1974. /// is known to exist, as is the target avatar.
  1975. /// </summary>
  1976. private void EstablishAppearance(UUID destination, UUID source)
  1977. {
  1978. m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source);
  1979. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1980. // If the model has no associated appearance we're done.
  1981. AvatarAppearance avatarAppearance = scene.AvatarService.GetAppearance(source);
  1982. if (avatarAppearance == null)
  1983. return;
  1984. // Simple appearance copy or copy Clothing and Bodyparts folders?
  1985. bool copyFolders = m_config.GetBoolean("copy_folders", false);
  1986. if (!copyFolders)
  1987. {
  1988. // Simple copy of wearables and appearance update
  1989. try
  1990. {
  1991. CopyWearablesAndAttachments(destination, source, avatarAppearance);
  1992. scene.AvatarService.SetAppearance(destination, avatarAppearance);
  1993. }
  1994. catch (Exception e)
  1995. {
  1996. m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
  1997. destination, e.Message);
  1998. }
  1999. return;
  2000. }
  2001. // Copy Clothing and Bodypart folders and appearance update
  2002. try
  2003. {
  2004. Dictionary<UUID,UUID> inventoryMap = new Dictionary<UUID,UUID>();
  2005. CopyInventoryFolders(destination, source, AssetType.Clothing, inventoryMap, avatarAppearance);
  2006. CopyInventoryFolders(destination, source, AssetType.Bodypart, inventoryMap, avatarAppearance);
  2007. AvatarWearable[] wearables = avatarAppearance.Wearables;
  2008. for (int i=0; i<wearables.Length; i++)
  2009. {
  2010. if (inventoryMap.ContainsKey(wearables[i][0].ItemID))
  2011. {
  2012. AvatarWearable wearable = new AvatarWearable();
  2013. wearable.Wear(inventoryMap[wearables[i][0].ItemID],
  2014. wearables[i][0].AssetID);
  2015. avatarAppearance.SetWearable(i, wearable);
  2016. }
  2017. }
  2018. scene.AvatarService.SetAppearance(destination, avatarAppearance);
  2019. }
  2020. catch (Exception e)
  2021. {
  2022. m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
  2023. destination, e.Message);
  2024. }
  2025. return;
  2026. }
  2027. /// <summary>
  2028. /// This method is called by establishAppearance to do a copy all inventory items
  2029. /// worn or attached to the Clothing inventory folder of the receiving avatar.
  2030. /// In parallel the avatar wearables and attachments are updated.
  2031. /// </summary>
  2032. private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance)
  2033. {
  2034. IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
  2035. // Get Clothing folder of receiver
  2036. InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, AssetType.Clothing);
  2037. if (destinationFolder == null)
  2038. throw new Exception("Cannot locate folder(s)");
  2039. // Missing destination folder? This should *never* be the case
  2040. if (destinationFolder.Type != (short)AssetType.Clothing)
  2041. {
  2042. destinationFolder = new InventoryFolderBase();
  2043. destinationFolder.ID = UUID.Random();
  2044. destinationFolder.Name = "Clothing";
  2045. destinationFolder.Owner = destination;
  2046. destinationFolder.Type = (short)AssetType.Clothing;
  2047. destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
  2048. destinationFolder.Version = 1;
  2049. inventoryService.AddFolder(destinationFolder); // store base record
  2050. m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
  2051. }
  2052. // Wearables
  2053. AvatarWearable[] wearables = avatarAppearance.Wearables;
  2054. AvatarWearable wearable;
  2055. for (int i = 0; i<wearables.Length; i++)
  2056. {
  2057. wearable = wearables[i];
  2058. if (wearable[0].ItemID != UUID.Zero)
  2059. {
  2060. // Get inventory item and copy it
  2061. InventoryItemBase item = new InventoryItemBase(wearable[0].ItemID, source);
  2062. item = inventoryService.GetItem(item);
  2063. if (item != null)
  2064. {
  2065. InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
  2066. destinationItem.Name = item.Name;
  2067. destinationItem.Owner = destination;
  2068. destinationItem.Description = item.Description;
  2069. destinationItem.InvType = item.InvType;
  2070. destinationItem.CreatorId = item.CreatorId;
  2071. destinationItem.CreatorData = item.CreatorData;
  2072. destinationItem.NextPermissions = item.NextPermissions;
  2073. destinationItem.CurrentPermissions = item.CurrentPermissions;
  2074. destinationItem.BasePermissions = item.BasePermissions;
  2075. destinationItem.EveryOnePermissions = item.EveryOnePermissions;
  2076. destinationItem.GroupPermissions = item.GroupPermissions;
  2077. destinationItem.AssetType = item.AssetType;
  2078. destinationItem.AssetID = item.AssetID;
  2079. destinationItem.GroupID = item.GroupID;
  2080. destinationItem.GroupOwned = item.GroupOwned;
  2081. destinationItem.SalePrice = item.SalePrice;
  2082. destinationItem.SaleType = item.SaleType;
  2083. destinationItem.Flags = item.Flags;
  2084. destinationItem.CreationDate = item.CreationDate;
  2085. destinationItem.Folder = destinationFolder.ID;
  2086. ApplyNextOwnerPermissions(destinationItem);
  2087. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
  2088. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
  2089. // Wear item
  2090. AvatarWearable newWearable = new AvatarWearable();
  2091. newWearable.Wear(destinationItem.ID, wearable[0].AssetID);
  2092. avatarAppearance.SetWearable(i, newWearable);
  2093. }
  2094. else
  2095. {
  2096. m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", wearable[0].ItemID, destinationFolder.ID);
  2097. }
  2098. }
  2099. }
  2100. // Attachments
  2101. List<AvatarAttachment> attachments = avatarAppearance.GetAttachments();
  2102. foreach (AvatarAttachment attachment in attachments)
  2103. {
  2104. int attachpoint = attachment.AttachPoint;
  2105. UUID itemID = attachment.ItemID;
  2106. if (itemID != UUID.Zero)
  2107. {
  2108. // Get inventory item and copy it
  2109. InventoryItemBase item = new InventoryItemBase(itemID, source);
  2110. item = inventoryService.GetItem(item);
  2111. if (item != null)
  2112. {
  2113. InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
  2114. destinationItem.Name = item.Name;
  2115. destinationItem.Owner = destination;
  2116. destinationItem.Description = item.Description;
  2117. destinationItem.InvType = item.InvType;
  2118. destinationItem.CreatorId = item.CreatorId;
  2119. destinationItem.CreatorData = item.CreatorData;
  2120. destinationItem.NextPermissions = item.NextPermissions;
  2121. destinationItem.CurrentPermissions = item.CurrentPermissions;
  2122. destinationItem.BasePermissions = item.BasePermissions;
  2123. destinationItem.EveryOnePermissions = item.EveryOnePermissions;
  2124. destinationItem.GroupPermissions = item.GroupPermissions;
  2125. destinationItem.AssetType = item.AssetType;
  2126. destinationItem.AssetID = item.AssetID;
  2127. destinationItem.GroupID = item.GroupID;
  2128. destinationItem.GroupOwned = item.GroupOwned;
  2129. destinationItem.SalePrice = item.SalePrice;
  2130. destinationItem.SaleType = item.SaleType;
  2131. destinationItem.Flags = item.Flags;
  2132. destinationItem.CreationDate = item.CreationDate;
  2133. destinationItem.Folder = destinationFolder.ID;
  2134. ApplyNextOwnerPermissions(destinationItem);
  2135. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
  2136. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
  2137. // Attach item
  2138. avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
  2139. m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
  2140. }
  2141. else
  2142. {
  2143. m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", itemID, destinationFolder.ID);
  2144. }
  2145. }
  2146. }
  2147. }
  2148. /// <summary>
  2149. /// This method is called by establishAppearance to copy inventory folders to make
  2150. /// copies of Clothing and Bodyparts inventory folders and attaches worn attachments
  2151. /// </summary>
  2152. private void CopyInventoryFolders(UUID destination, UUID source, AssetType assetType, Dictionary<UUID,UUID> inventoryMap,
  2153. AvatarAppearance avatarAppearance)
  2154. {
  2155. IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
  2156. InventoryFolderBase sourceFolder = inventoryService.GetFolderForType(source, assetType);
  2157. InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, assetType);
  2158. if (sourceFolder == null || destinationFolder == null)
  2159. throw new Exception("Cannot locate folder(s)");
  2160. // Missing source folder? This should *never* be the case
  2161. if (sourceFolder.Type != (short)assetType)
  2162. {
  2163. sourceFolder = new InventoryFolderBase();
  2164. sourceFolder.ID = UUID.Random();
  2165. if (assetType == AssetType.Clothing) {
  2166. sourceFolder.Name = "Clothing";
  2167. } else {
  2168. sourceFolder.Name = "Body Parts";
  2169. }
  2170. sourceFolder.Owner = source;
  2171. sourceFolder.Type = (short)assetType;
  2172. sourceFolder.ParentID = inventoryService.GetRootFolder(source).ID;
  2173. sourceFolder.Version = 1;
  2174. inventoryService.AddFolder(sourceFolder); // store base record
  2175. m_log.ErrorFormat("[RADMIN] Created folder for source {0}", source);
  2176. }
  2177. // Missing destination folder? This should *never* be the case
  2178. if (destinationFolder.Type != (short)assetType)
  2179. {
  2180. destinationFolder = new InventoryFolderBase();
  2181. destinationFolder.ID = UUID.Random();
  2182. if (assetType == AssetType.Clothing)
  2183. {
  2184. destinationFolder.Name = "Clothing";
  2185. }
  2186. else
  2187. {
  2188. destinationFolder.Name = "Body Parts";
  2189. }
  2190. destinationFolder.Owner = destination;
  2191. destinationFolder.Type = (short)assetType;
  2192. destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
  2193. destinationFolder.Version = 1;
  2194. inventoryService.AddFolder(destinationFolder); // store base record
  2195. m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
  2196. }
  2197. InventoryFolderBase extraFolder;
  2198. List<InventoryFolderBase> folders = inventoryService.GetFolderContent(source, sourceFolder.ID).Folders;
  2199. foreach (InventoryFolderBase folder in folders)
  2200. {
  2201. extraFolder = new InventoryFolderBase();
  2202. extraFolder.ID = UUID.Random();
  2203. extraFolder.Name = folder.Name;
  2204. extraFolder.Owner = destination;
  2205. extraFolder.Type = folder.Type;
  2206. extraFolder.Version = folder.Version;
  2207. extraFolder.ParentID = destinationFolder.ID;
  2208. inventoryService.AddFolder(extraFolder);
  2209. m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);
  2210. List<InventoryItemBase> items = inventoryService.GetFolderContent(source, folder.ID).Items;
  2211. foreach (InventoryItemBase item in items)
  2212. {
  2213. InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
  2214. destinationItem.Name = item.Name;
  2215. destinationItem.Owner = destination;
  2216. destinationItem.Description = item.Description;
  2217. destinationItem.InvType = item.InvType;
  2218. destinationItem.CreatorId = item.CreatorId;
  2219. destinationItem.CreatorData = item.CreatorData;
  2220. destinationItem.NextPermissions = item.NextPermissions;
  2221. destinationItem.CurrentPermissions = item.CurrentPermissions;
  2222. destinationItem.BasePermissions = item.BasePermissions;
  2223. destinationItem.EveryOnePermissions = item.EveryOnePermissions;
  2224. destinationItem.GroupPermissions = item.GroupPermissions;
  2225. destinationItem.AssetType = item.AssetType;
  2226. destinationItem.AssetID = item.AssetID;
  2227. destinationItem.GroupID = item.GroupID;
  2228. destinationItem.GroupOwned = item.GroupOwned;
  2229. destinationItem.SalePrice = item.SalePrice;
  2230. destinationItem.SaleType = item.SaleType;
  2231. destinationItem.Flags = item.Flags;
  2232. destinationItem.CreationDate = item.CreationDate;
  2233. destinationItem.Folder = extraFolder.ID;
  2234. ApplyNextOwnerPermissions(destinationItem);
  2235. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
  2236. inventoryMap.Add(item.ID, destinationItem.ID);
  2237. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, extraFolder.ID);
  2238. // Attach item, if original is attached
  2239. int attachpoint = avatarAppearance.GetAttachpoint(item.ID);
  2240. if (attachpoint != 0)
  2241. {
  2242. avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
  2243. m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
  2244. }
  2245. }
  2246. }
  2247. }
  2248. /// <summary>
  2249. /// Apply next owner permissions.
  2250. /// </summary>
  2251. private void ApplyNextOwnerPermissions(InventoryItemBase item)
  2252. {
  2253. if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
  2254. {
  2255. if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
  2256. item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
  2257. if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
  2258. item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
  2259. if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
  2260. item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
  2261. }
  2262. item.CurrentPermissions &= item.NextPermissions;
  2263. item.BasePermissions &= item.NextPermissions;
  2264. item.EveryOnePermissions &= item.NextPermissions;
  2265. // item.OwnerChanged = true;
  2266. // item.PermsMask = 0;
  2267. // item.PermsGranter = UUID.Zero;
  2268. }
  2269. /// <summary>
  2270. /// This method is called if a given model avatar name can not be found. If the external
  2271. /// file has already been loaded once, then control returns immediately. If not, then it
  2272. /// looks for a default appearance file. This file contains XML definitions of zero or more named
  2273. /// avatars, each avatar can specify zero or more "outfits". Each outfit is a collection
  2274. /// of items that together, define a particular ensemble for the avatar. Each avatar should
  2275. /// indicate which outfit is the default, and this outfit will be automatically worn. The
  2276. /// other outfits are provided to allow "real" avatars a way to easily change their outfits.
  2277. /// </summary>
  2278. private bool CreateDefaultAvatars()
  2279. {
  2280. // Only load once
  2281. if (m_defaultAvatarsLoaded)
  2282. {
  2283. return false;
  2284. }
  2285. m_log.DebugFormat("[RADMIN]: Creating default avatar entries");
  2286. m_defaultAvatarsLoaded = true;
  2287. // Load processing starts here...
  2288. try
  2289. {
  2290. string defaultAppearanceFileName = null;
  2291. //m_config may be null if RemoteAdmin configuration secition is missing or disabled in OpenSim.ini
  2292. if (m_config != null)
  2293. {
  2294. defaultAppearanceFileName = m_config.GetString("default_appearance", "default_appearance.xml");
  2295. }
  2296. if (File.Exists(defaultAppearanceFileName))
  2297. {
  2298. XmlDocument doc = new XmlDocument();
  2299. string name = "*unknown*";
  2300. string email = "anon@anon";
  2301. uint regionXLocation = 1000;
  2302. uint regionYLocation = 1000;
  2303. string password = UUID.Random().ToString(); // No requirement to sign-in.
  2304. UUID ID = UUID.Zero;
  2305. AvatarAppearance avatarAppearance;
  2306. XmlNodeList avatars;
  2307. XmlNodeList assets;
  2308. XmlNode perms = null;
  2309. bool include = false;
  2310. bool select = false;
  2311. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  2312. IInventoryService inventoryService = scene.InventoryService;
  2313. IAssetService assetService = scene.AssetService;
  2314. doc.LoadXml(File.ReadAllText(defaultAppearanceFileName));
  2315. // Load up any included assets. Duplicates will be ignored
  2316. assets = doc.GetElementsByTagName("RequiredAsset");
  2317. foreach (XmlNode assetNode in assets)
  2318. {
  2319. AssetBase asset = new AssetBase(UUID.Random(), GetStringAttribute(assetNode, "name", ""), SByte.Parse(GetStringAttribute(assetNode, "type", "")), UUID.Zero.ToString());
  2320. asset.Description = GetStringAttribute(assetNode,"desc","");
  2321. asset.Local = Boolean.Parse(GetStringAttribute(assetNode,"local",""));
  2322. asset.Temporary = Boolean.Parse(GetStringAttribute(assetNode,"temporary",""));
  2323. asset.Data = Convert.FromBase64String(assetNode.InnerText);
  2324. assetService.Store(asset);
  2325. }
  2326. avatars = doc.GetElementsByTagName("Avatar");
  2327. // The document may contain multiple avatars
  2328. foreach (XmlElement avatar in avatars)
  2329. {
  2330. m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}",
  2331. GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?"));
  2332. // Create the user identified by the avatar entry
  2333. try
  2334. {
  2335. // Only the name value is mandatory
  2336. name = GetStringAttribute(avatar,"name",name);
  2337. email = GetStringAttribute(avatar,"email",email);
  2338. regionXLocation = GetUnsignedAttribute(avatar,"regx",regionXLocation);
  2339. regionYLocation = GetUnsignedAttribute(avatar,"regy",regionYLocation);
  2340. password = GetStringAttribute(avatar,"password",password);
  2341. string[] names = name.Split();
  2342. UUID scopeID = scene.RegionInfo.ScopeID;
  2343. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, names[0], names[1]);
  2344. if (null == account)
  2345. {
  2346. account = CreateUser(scopeID, names[0], names[1], password, email);
  2347. if (null == account)
  2348. {
  2349. m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]);
  2350. return false;
  2351. }
  2352. }
  2353. // Set home position
  2354. GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
  2355. (int)(regionXLocation * Constants.RegionSize), (int)(regionYLocation * Constants.RegionSize));
  2356. if (null == home) {
  2357. m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", names[0], names[1]);
  2358. } else {
  2359. scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  2360. m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, names[0], names[1]);
  2361. }
  2362. ID = account.PrincipalID;
  2363. m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID);
  2364. include = true;
  2365. }
  2366. catch (Exception e)
  2367. {
  2368. m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message);
  2369. include = false;
  2370. }
  2371. // OK, User has been created OK, now we can install the inventory.
  2372. // First retrieve the current inventory (the user may already exist)
  2373. // Note that althought he inventory is retrieved, the hierarchy has
  2374. // not been interpreted at all.
  2375. if (include)
  2376. {
  2377. // Setup for appearance processing
  2378. avatarAppearance = scene.AvatarService.GetAppearance(ID);
  2379. if (avatarAppearance == null)
  2380. avatarAppearance = new AvatarAppearance();
  2381. AvatarWearable[] wearables = avatarAppearance.Wearables;
  2382. for (int i=0; i<wearables.Length; i++)
  2383. {
  2384. wearables[i] = new AvatarWearable();
  2385. }
  2386. try
  2387. {
  2388. // m_log.DebugFormat("[RADMIN] {0} folders, {1} items in inventory",
  2389. // uic.folders.Count, uic.items.Count);
  2390. InventoryFolderBase clothingFolder = inventoryService.GetFolderForType(ID, AssetType.Clothing);
  2391. // This should *never* be the case
  2392. if (clothingFolder == null || clothingFolder.Type != (short)AssetType.Clothing)
  2393. {
  2394. clothingFolder = new InventoryFolderBase();
  2395. clothingFolder.ID = UUID.Random();
  2396. clothingFolder.Name = "Clothing";
  2397. clothingFolder.Owner = ID;
  2398. clothingFolder.Type = (short)AssetType.Clothing;
  2399. clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID;
  2400. clothingFolder.Version = 1;
  2401. inventoryService.AddFolder(clothingFolder); // store base record
  2402. m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID);
  2403. }
  2404. // OK, now we have an inventory for the user, read in the outfits from the
  2405. // default appearance XMl file.
  2406. XmlNodeList outfits = avatar.GetElementsByTagName("Ensemble");
  2407. InventoryFolderBase extraFolder;
  2408. string outfitName;
  2409. UUID assetid;
  2410. foreach (XmlElement outfit in outfits)
  2411. {
  2412. m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}",
  2413. GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?"));
  2414. outfitName = GetStringAttribute(outfit,"name","");
  2415. select = (GetStringAttribute(outfit,"default","no") == "yes");
  2416. // If the folder already exists, re-use it. The defaults may
  2417. // change over time. Augment only.
  2418. List<InventoryFolderBase> folders = inventoryService.GetFolderContent(ID, clothingFolder.ID).Folders;
  2419. extraFolder = null;
  2420. foreach (InventoryFolderBase folder in folders)
  2421. {
  2422. if (folder.Name == outfitName)
  2423. {
  2424. extraFolder = folder;
  2425. break;
  2426. }
  2427. }
  2428. // Otherwise, we must create the folder.
  2429. if (extraFolder == null)
  2430. {
  2431. m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name);
  2432. extraFolder = new InventoryFolderBase();
  2433. extraFolder.ID = UUID.Random();
  2434. extraFolder.Name = outfitName;
  2435. extraFolder.Owner = ID;
  2436. extraFolder.Type = (short)AssetType.Clothing;
  2437. extraFolder.Version = 1;
  2438. extraFolder.ParentID = clothingFolder.ID;
  2439. inventoryService.AddFolder(extraFolder);
  2440. m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
  2441. }
  2442. // Now get the pieces that make up the outfit
  2443. XmlNodeList items = outfit.GetElementsByTagName("Item");
  2444. foreach (XmlElement item in items)
  2445. {
  2446. assetid = UUID.Zero;
  2447. XmlNodeList children = item.ChildNodes;
  2448. foreach (XmlNode child in children)
  2449. {
  2450. switch (child.Name)
  2451. {
  2452. case "Permissions" :
  2453. m_log.DebugFormat("[RADMIN]: Permissions specified");
  2454. perms = child;
  2455. break;
  2456. case "Asset" :
  2457. assetid = new UUID(child.InnerText);
  2458. break;
  2459. }
  2460. }
  2461. InventoryItemBase inventoryItem = null;
  2462. // Check if asset is in inventory already
  2463. inventoryItem = null;
  2464. List<InventoryItemBase> inventoryItems = inventoryService.GetFolderContent(ID, extraFolder.ID).Items;
  2465. foreach (InventoryItemBase listItem in inventoryItems)
  2466. {
  2467. if (listItem.AssetID == assetid)
  2468. {
  2469. inventoryItem = listItem;
  2470. break;
  2471. }
  2472. }
  2473. // Create inventory item
  2474. if (inventoryItem == null)
  2475. {
  2476. inventoryItem = new InventoryItemBase(UUID.Random(), ID);
  2477. inventoryItem.Name = GetStringAttribute(item,"name","");
  2478. inventoryItem.Description = GetStringAttribute(item,"desc","");
  2479. inventoryItem.InvType = GetIntegerAttribute(item,"invtype",-1);
  2480. inventoryItem.CreatorId = GetStringAttribute(item,"creatorid","");
  2481. inventoryItem.CreatorData = GetStringAttribute(item, "creatordata", "");
  2482. inventoryItem.NextPermissions = GetUnsignedAttribute(perms, "next", 0x7fffffff);
  2483. inventoryItem.CurrentPermissions = GetUnsignedAttribute(perms,"current",0x7fffffff);
  2484. inventoryItem.BasePermissions = GetUnsignedAttribute(perms,"base",0x7fffffff);
  2485. inventoryItem.EveryOnePermissions = GetUnsignedAttribute(perms,"everyone",0x7fffffff);
  2486. inventoryItem.GroupPermissions = GetUnsignedAttribute(perms,"group",0x7fffffff);
  2487. inventoryItem.AssetType = GetIntegerAttribute(item,"assettype",-1);
  2488. inventoryItem.AssetID = assetid; // associated asset
  2489. inventoryItem.GroupID = (UUID)GetStringAttribute(item,"groupid","");
  2490. inventoryItem.GroupOwned = (GetStringAttribute(item,"groupowned","false") == "true");
  2491. inventoryItem.SalePrice = GetIntegerAttribute(item,"saleprice",0);
  2492. inventoryItem.SaleType = (byte)GetIntegerAttribute(item,"saletype",0);
  2493. inventoryItem.Flags = GetUnsignedAttribute(item,"flags",0);
  2494. inventoryItem.CreationDate = GetIntegerAttribute(item,"creationdate",Util.UnixTimeSinceEpoch());
  2495. inventoryItem.Folder = extraFolder.ID; // Parent folder
  2496. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem);
  2497. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
  2498. }
  2499. // Attach item, if attachpoint is specified
  2500. int attachpoint = GetIntegerAttribute(item,"attachpoint",0);
  2501. if (attachpoint != 0)
  2502. {
  2503. avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID);
  2504. m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID);
  2505. }
  2506. // Record whether or not the item is to be initially worn
  2507. try
  2508. {
  2509. if (select && (GetStringAttribute(item, "wear", "false") == "true"))
  2510. {
  2511. avatarAppearance.Wearables[inventoryItem.Flags].Wear(inventoryItem.ID, inventoryItem.AssetID);
  2512. }
  2513. }
  2514. catch (Exception e)
  2515. {
  2516. m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
  2517. }
  2518. } // foreach item in outfit
  2519. m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName);
  2520. } // foreach outfit
  2521. m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name);
  2522. scene.AvatarService.SetAppearance(ID, avatarAppearance);
  2523. }
  2524. catch (Exception e)
  2525. {
  2526. m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}",
  2527. name, e.Message);
  2528. }
  2529. } // End of include
  2530. }
  2531. m_log.DebugFormat("[RADMIN]: Default avatar loading complete");
  2532. }
  2533. else
  2534. {
  2535. m_log.DebugFormat("[RADMIN]: No default avatar information available");
  2536. return false;
  2537. }
  2538. }
  2539. catch (Exception e)
  2540. {
  2541. m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message);
  2542. return false;
  2543. }
  2544. return true;
  2545. }
  2546. }
  2547. }