RemoteAdminPlugin.cs 145 KB

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