RemoteAdminPlugin.cs 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  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)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
  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)Util.RegionToWorldLoc((uint)regionXLocation), (int)Util.RegionToWorldLoc((uint)regionYLocation));
  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. Dictionary<string, object> archiveOptions = new Dictionary<string,object>();
  1276. if (mergeOar) archiveOptions.Add("merge", null);
  1277. if (skipAssets) archiveOptions.Add("skipAssets", null);
  1278. if (archiver != null)
  1279. archiver.DearchiveRegion(filename, Guid.Empty, archiveOptions);
  1280. else
  1281. throw new Exception("Archiver module not present for scene");
  1282. responseData["loaded"] = true;
  1283. }
  1284. catch (Exception e)
  1285. {
  1286. responseData["loaded"] = false;
  1287. throw e;
  1288. }
  1289. m_log.Info("[RADMIN]: Load OAR Administrator Request complete");
  1290. }
  1291. }
  1292. /// <summary>
  1293. /// Save a region to an OAR file
  1294. /// <summary>
  1295. /// <param name="request">incoming XML RPC request</param>
  1296. /// <remarks>
  1297. /// XmlRpcSaveOARMethod takes the following XMLRPC
  1298. /// parameters
  1299. /// <list type="table">
  1300. /// <listheader><term>parameter name</term><description>description</description></listheader>
  1301. /// <item><term>password</term>
  1302. /// <description>admin password as set in OpenSim.ini</description></item>
  1303. /// <item><term>filename</term>
  1304. /// <description>file name for the OAR file</description></item>
  1305. /// <item><term>region_uuid</term>
  1306. /// <description>UUID of the region</description></item>
  1307. /// <item><term>region_name</term>
  1308. /// <description>region name</description></item>
  1309. /// <item><term>profile</term>
  1310. /// <description>profile url</description></item>
  1311. /// <item><term>noassets</term>
  1312. /// <description>true if no assets should be saved</description></item>
  1313. /// <item><term>all</term>
  1314. /// <description>true to save all the regions in the simulator</description></item>
  1315. /// <item><term>perm</term>
  1316. /// <description>C and/or T</description></item>
  1317. /// </list>
  1318. ///
  1319. /// <code>region_uuid</code> takes precedence over
  1320. /// <code>region_name</code> if both are present; one of both
  1321. /// must be present.
  1322. ///
  1323. /// XmlRpcLoadOARMethod returns
  1324. /// <list type="table">
  1325. /// <listheader><term>name</term><description>description</description></listheader>
  1326. /// <item><term>success</term>
  1327. /// <description>true or false</description></item>
  1328. /// <item><term>error</term>
  1329. /// <description>error message if success is false</description></item>
  1330. /// </list>
  1331. /// </remarks>
  1332. private void XmlRpcSaveOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1333. {
  1334. m_log.Info("[RADMIN]: Received Save OAR Request");
  1335. Hashtable responseData = (Hashtable)response.Value;
  1336. Hashtable requestData = (Hashtable)request.Params[0];
  1337. try
  1338. {
  1339. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1340. CheckRegionParams(requestData, responseData);
  1341. Scene scene = null;
  1342. GetSceneFromRegionParams(requestData, responseData, out scene);
  1343. string filename = (string)requestData["filename"];
  1344. Dictionary<string, object> options = new Dictionary<string, object>();
  1345. //if (requestData.Contains("version"))
  1346. //{
  1347. // options["version"] = (string)requestData["version"];
  1348. //}
  1349. if (requestData.Contains("home"))
  1350. {
  1351. options["home"] = (string)requestData["home"];
  1352. }
  1353. if ((string)requestData["noassets"] == "true")
  1354. {
  1355. options["noassets"] = (string)requestData["noassets"] ;
  1356. }
  1357. if (requestData.Contains("perm"))
  1358. {
  1359. options["checkPermissions"] = (string)requestData["perm"];
  1360. }
  1361. if ((string)requestData["all"] == "true")
  1362. {
  1363. options["all"] = (string)requestData["all"];
  1364. }
  1365. IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
  1366. if (archiver != null)
  1367. {
  1368. Guid requestId = Guid.NewGuid();
  1369. scene.EventManager.OnOarFileSaved += RemoteAdminOarSaveCompleted;
  1370. m_log.InfoFormat(
  1371. "[RADMIN]: Submitting save OAR request for {0} to file {1}, request ID {2}",
  1372. scene.Name, filename, requestId);
  1373. archiver.ArchiveRegion(filename, requestId, options);
  1374. lock (m_saveOarLock)
  1375. Monitor.Wait(m_saveOarLock,5000);
  1376. scene.EventManager.OnOarFileSaved -= RemoteAdminOarSaveCompleted;
  1377. }
  1378. else
  1379. {
  1380. throw new Exception("Archiver module not present for scene");
  1381. }
  1382. responseData["saved"] = true;
  1383. }
  1384. catch (Exception e)
  1385. {
  1386. responseData["saved"] = false;
  1387. throw e;
  1388. }
  1389. m_log.Info("[RADMIN]: Save OAR Request complete");
  1390. }
  1391. private void RemoteAdminOarSaveCompleted(Guid uuid, string name)
  1392. {
  1393. if (name != "")
  1394. m_log.ErrorFormat("[RADMIN]: Saving of OAR file with request ID {0} failed with message {1}", uuid, name);
  1395. else
  1396. m_log.DebugFormat("[RADMIN]: Saved OAR file for request {0}", uuid);
  1397. lock (m_saveOarLock)
  1398. Monitor.Pulse(m_saveOarLock);
  1399. }
  1400. private void XmlRpcLoadXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1401. {
  1402. m_log.Info("[RADMIN]: Received Load XML Administrator Request");
  1403. Hashtable responseData = (Hashtable)response.Value;
  1404. Hashtable requestData = (Hashtable)request.Params[0];
  1405. lock (m_requestLock)
  1406. {
  1407. try
  1408. {
  1409. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1410. CheckRegionParams(requestData, responseData);
  1411. Scene scene = null;
  1412. GetSceneFromRegionParams(requestData, responseData, out scene);
  1413. string filename = (string) requestData["filename"];
  1414. responseData["switched"] = true;
  1415. string xml_version = "1";
  1416. if (requestData.Contains("xml_version"))
  1417. {
  1418. xml_version = (string) requestData["xml_version"];
  1419. }
  1420. switch (xml_version)
  1421. {
  1422. case "1":
  1423. m_application.SceneManager.LoadCurrentSceneFromXml(filename, true, new Vector3(0, 0, 0));
  1424. break;
  1425. case "2":
  1426. m_application.SceneManager.LoadCurrentSceneFromXml2(filename);
  1427. break;
  1428. default:
  1429. throw new Exception(String.Format("unknown Xml{0} format", xml_version));
  1430. }
  1431. responseData["loaded"] = true;
  1432. }
  1433. catch (Exception e)
  1434. {
  1435. responseData["loaded"] = false;
  1436. responseData["switched"] = false;
  1437. throw e;
  1438. }
  1439. m_log.Info("[RADMIN]: Load XML Administrator Request complete");
  1440. }
  1441. }
  1442. private void XmlRpcSaveXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1443. {
  1444. m_log.Info("[RADMIN]: Received Save XML Administrator Request");
  1445. Hashtable responseData = (Hashtable)response.Value;
  1446. Hashtable requestData = (Hashtable)request.Params[0];
  1447. try
  1448. {
  1449. CheckStringParameters(requestData, responseData, new string[] {"filename"});
  1450. CheckRegionParams(requestData, responseData);
  1451. Scene scene = null;
  1452. GetSceneFromRegionParams(requestData, responseData, out scene);
  1453. string filename = (string) requestData["filename"];
  1454. responseData["switched"] = true;
  1455. string xml_version = "1";
  1456. if (requestData.Contains("xml_version"))
  1457. {
  1458. xml_version = (string) requestData["xml_version"];
  1459. }
  1460. switch (xml_version)
  1461. {
  1462. case "1":
  1463. m_application.SceneManager.SaveCurrentSceneToXml(filename);
  1464. break;
  1465. case "2":
  1466. m_application.SceneManager.SaveCurrentSceneToXml2(filename);
  1467. break;
  1468. default:
  1469. throw new Exception(String.Format("unknown Xml{0} format", xml_version));
  1470. }
  1471. responseData["saved"] = true;
  1472. }
  1473. catch (Exception e)
  1474. {
  1475. responseData["saved"] = false;
  1476. responseData["switched"] = false;
  1477. throw e;
  1478. }
  1479. m_log.Info("[RADMIN]: Save XML Administrator Request complete");
  1480. }
  1481. private void XmlRpcRegionQueryMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1482. {
  1483. m_log.Info("[RADMIN]: Received Query XML Administrator Request");
  1484. Hashtable responseData = (Hashtable)response.Value;
  1485. Hashtable requestData = (Hashtable)request.Params[0];
  1486. CheckRegionParams(requestData, responseData);
  1487. Scene scene = null;
  1488. GetSceneFromRegionParams(requestData, responseData, out scene);
  1489. int health = scene.GetHealth();
  1490. responseData["health"] = health;
  1491. responseData["success"] = true;
  1492. m_log.Info("[RADMIN]: Query XML Administrator Request complete");
  1493. }
  1494. private void XmlRpcConsoleCommandMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1495. {
  1496. m_log.Info("[RADMIN]: Received Command XML Administrator Request");
  1497. Hashtable responseData = (Hashtable)response.Value;
  1498. Hashtable requestData = (Hashtable)request.Params[0];
  1499. CheckStringParameters(requestData, responseData, new string[] {"command"});
  1500. MainConsole.Instance.RunCommand(requestData["command"].ToString());
  1501. m_log.Info("[RADMIN]: Command XML Administrator Request complete");
  1502. }
  1503. private void XmlRpcAccessListClear(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1504. {
  1505. m_log.Info("[RADMIN]: Received Access List Clear Request");
  1506. Hashtable responseData = (Hashtable)response.Value;
  1507. Hashtable requestData = (Hashtable)request.Params[0];
  1508. responseData["success"] = true;
  1509. CheckRegionParams(requestData, responseData);
  1510. Scene scene = null;
  1511. GetSceneFromRegionParams(requestData, responseData, out scene);
  1512. scene.RegionInfo.EstateSettings.EstateAccess = new UUID[]{};
  1513. if (scene.RegionInfo.Persistent)
  1514. scene.RegionInfo.EstateSettings.Save();
  1515. m_log.Info("[RADMIN]: Access List Clear Request complete");
  1516. }
  1517. private void XmlRpcAccessListAdd(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1518. {
  1519. m_log.Info("[RADMIN]: Received Access List Add Request");
  1520. Hashtable responseData = (Hashtable)response.Value;
  1521. Hashtable requestData = (Hashtable)request.Params[0];
  1522. CheckRegionParams(requestData, responseData);
  1523. Scene scene = null;
  1524. GetSceneFromRegionParams(requestData, responseData, out scene);
  1525. int addedUsers = 0;
  1526. if (requestData.Contains("users"))
  1527. {
  1528. UUID scopeID = scene.RegionInfo.ScopeID;
  1529. IUserAccountService userService = scene.UserAccountService;
  1530. Hashtable users = (Hashtable) requestData["users"];
  1531. List<UUID> uuids = new List<UUID>();
  1532. foreach (string name in users.Values)
  1533. {
  1534. string[] parts = name.Split();
  1535. UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
  1536. if (account != null)
  1537. {
  1538. uuids.Add(account.PrincipalID);
  1539. m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
  1540. }
  1541. }
  1542. List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
  1543. foreach (UUID uuid in uuids)
  1544. {
  1545. if (!accessControlList.Contains(uuid))
  1546. {
  1547. accessControlList.Add(uuid);
  1548. addedUsers++;
  1549. }
  1550. }
  1551. scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
  1552. if (scene.RegionInfo.Persistent)
  1553. scene.RegionInfo.EstateSettings.Save();
  1554. }
  1555. responseData["added"] = addedUsers;
  1556. m_log.Info("[RADMIN]: Access List Add Request complete");
  1557. }
  1558. private void XmlRpcAccessListRemove(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1559. {
  1560. m_log.Info("[RADMIN]: Received Access List Remove Request");
  1561. Hashtable responseData = (Hashtable)response.Value;
  1562. Hashtable requestData = (Hashtable)request.Params[0];
  1563. CheckRegionParams(requestData, responseData);
  1564. Scene scene = null;
  1565. GetSceneFromRegionParams(requestData, responseData, out scene);
  1566. int removedUsers = 0;
  1567. if (requestData.Contains("users"))
  1568. {
  1569. UUID scopeID = scene.RegionInfo.ScopeID;
  1570. IUserAccountService userService = scene.UserAccountService;
  1571. //UserProfileCacheService ups = m_application.CommunicationsManager.UserProfileCacheService;
  1572. Hashtable users = (Hashtable) requestData["users"];
  1573. List<UUID> uuids = new List<UUID>();
  1574. foreach (string name in users.Values)
  1575. {
  1576. string[] parts = name.Split();
  1577. UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
  1578. if (account != null)
  1579. {
  1580. uuids.Add(account.PrincipalID);
  1581. }
  1582. }
  1583. List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
  1584. foreach (UUID uuid in uuids)
  1585. {
  1586. if (accessControlList.Contains(uuid))
  1587. {
  1588. accessControlList.Remove(uuid);
  1589. removedUsers++;
  1590. }
  1591. }
  1592. scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
  1593. if (scene.RegionInfo.Persistent)
  1594. scene.RegionInfo.EstateSettings.Save();
  1595. }
  1596. responseData["removed"] = removedUsers;
  1597. responseData["success"] = true;
  1598. m_log.Info("[RADMIN]: Access List Remove Request complete");
  1599. }
  1600. private void XmlRpcAccessListList(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1601. {
  1602. m_log.Info("[RADMIN]: Received Access List List Request");
  1603. Hashtable responseData = (Hashtable)response.Value;
  1604. Hashtable requestData = (Hashtable)request.Params[0];
  1605. CheckRegionParams(requestData, responseData);
  1606. Scene scene = null;
  1607. GetSceneFromRegionParams(requestData, responseData, out scene);
  1608. UUID[] accessControlList = scene.RegionInfo.EstateSettings.EstateAccess;
  1609. Hashtable users = new Hashtable();
  1610. foreach (UUID user in accessControlList)
  1611. {
  1612. UUID scopeID = scene.RegionInfo.ScopeID;
  1613. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, user);
  1614. if (account != null)
  1615. {
  1616. users[user.ToString()] = account.FirstName + " " + account.LastName;
  1617. }
  1618. }
  1619. responseData["users"] = users;
  1620. responseData["success"] = true;
  1621. m_log.Info("[RADMIN]: Access List List Request complete");
  1622. }
  1623. private void XmlRpcEstateReload(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1624. {
  1625. m_log.Info("[RADMIN]: Received Estate Reload Request");
  1626. Hashtable responseData = (Hashtable)response.Value;
  1627. // Hashtable requestData = (Hashtable)request.Params[0];
  1628. m_application.SceneManager.ForEachScene(s =>
  1629. s.RegionInfo.EstateSettings = m_application.EstateDataService.LoadEstateSettings(s.RegionInfo.RegionID, false)
  1630. );
  1631. responseData["success"] = true;
  1632. m_log.Info("[RADMIN]: Estate Reload Request complete");
  1633. }
  1634. private void XmlRpcGetAgentsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1635. {
  1636. Hashtable responseData = (Hashtable)response.Value;
  1637. Hashtable requestData = (Hashtable)request.Params[0];
  1638. bool includeChildren = false;
  1639. if (requestData.Contains("include_children"))
  1640. bool.TryParse((string)requestData["include_children"], out includeChildren);
  1641. Scene scene;
  1642. GetSceneFromRegionParams(requestData, responseData, out scene);
  1643. ArrayList xmlRpcRegions = new ArrayList();
  1644. responseData["regions"] = xmlRpcRegions;
  1645. Hashtable xmlRpcRegion = new Hashtable();
  1646. xmlRpcRegions.Add(xmlRpcRegion);
  1647. xmlRpcRegion["name"] = scene.Name;
  1648. xmlRpcRegion["id"] = scene.RegionInfo.RegionID.ToString();
  1649. List<ScenePresence> agents = scene.GetScenePresences();
  1650. ArrayList xmlrpcAgents = new ArrayList();
  1651. foreach (ScenePresence agent in agents)
  1652. {
  1653. if (agent.IsChildAgent && !includeChildren)
  1654. continue;
  1655. Hashtable xmlRpcAgent = new Hashtable();
  1656. xmlRpcAgent.Add("name", agent.Name);
  1657. xmlRpcAgent.Add("id", agent.UUID.ToString());
  1658. xmlRpcAgent.Add("type", agent.PresenceType.ToString());
  1659. xmlRpcAgent.Add("current_parcel_id", agent.currentParcelUUID.ToString());
  1660. Vector3 pos = agent.AbsolutePosition;
  1661. xmlRpcAgent.Add("pos_x", pos.X.ToString());
  1662. xmlRpcAgent.Add("pos_y", pos.Y.ToString());
  1663. xmlRpcAgent.Add("pos_z", pos.Z.ToString());
  1664. Vector3 lookAt = agent.Lookat;
  1665. xmlRpcAgent.Add("lookat_x", lookAt.X.ToString());
  1666. xmlRpcAgent.Add("lookat_y", lookAt.Y.ToString());
  1667. xmlRpcAgent.Add("lookat_z", lookAt.Z.ToString());
  1668. Vector3 vel = agent.Velocity;
  1669. xmlRpcAgent.Add("vel_x", vel.X.ToString());
  1670. xmlRpcAgent.Add("vel_y", vel.Y.ToString());
  1671. xmlRpcAgent.Add("vel_z", vel.Z.ToString());
  1672. xmlRpcAgent.Add("is_flying", agent.Flying.ToString());
  1673. xmlRpcAgent.Add("is_sat_on_ground", agent.SitGround.ToString());
  1674. xmlRpcAgent.Add("is_sat_on_object", agent.IsSatOnObject.ToString());
  1675. xmlrpcAgents.Add(xmlRpcAgent);
  1676. }
  1677. m_log.DebugFormat(
  1678. "[REMOTE ADMIN]: XmlRpcGetAgents found {0} agents in {1}", xmlrpcAgents.Count, scene.Name);
  1679. xmlRpcRegion["agents"] = xmlrpcAgents;
  1680. responseData["success"] = true;
  1681. }
  1682. private void XmlRpcTeleportAgentMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
  1683. {
  1684. Hashtable responseData = (Hashtable)response.Value;
  1685. Hashtable requestData = (Hashtable)request.Params[0];
  1686. UUID agentId;
  1687. string regionName = null;
  1688. Vector3 pos, lookAt;
  1689. ScenePresence sp = null;
  1690. if (requestData.Contains("agent_first_name") && requestData.Contains("agent_last_name"))
  1691. {
  1692. string firstName = requestData["agent_first_name"].ToString();
  1693. string lastName = requestData["agent_last_name"].ToString();
  1694. m_application.SceneManager.TryGetRootScenePresenceByName(firstName, lastName, out sp);
  1695. if (sp == null)
  1696. throw new Exception(
  1697. string.Format(
  1698. "No agent found with agent_first_name {0} and agent_last_name {1}", firstName, lastName));
  1699. }
  1700. else if (requestData.Contains("agent_id"))
  1701. {
  1702. string rawAgentId = (string)requestData["agent_id"];
  1703. if (!UUID.TryParse(rawAgentId, out agentId))
  1704. throw new Exception(string.Format("agent_id {0} does not have the correct id format", rawAgentId));
  1705. m_application.SceneManager.TryGetRootScenePresence(agentId, out sp);
  1706. if (sp == null)
  1707. throw new Exception(string.Format("No agent with agent_id {0} found in this simulator", agentId));
  1708. }
  1709. else
  1710. {
  1711. throw new Exception("No agent_id or agent_first_name and agent_last_name parameters specified");
  1712. }
  1713. if (requestData.Contains("region_name"))
  1714. regionName = (string)requestData["region_name"];
  1715. pos.X = ParseFloat(requestData, "pos_x", sp.AbsolutePosition.X);
  1716. pos.Y = ParseFloat(requestData, "pos_y", sp.AbsolutePosition.Y);
  1717. pos.Z = ParseFloat(requestData, "pos_z", sp.AbsolutePosition.Z);
  1718. lookAt.X = ParseFloat(requestData, "lookat_x", sp.Lookat.X);
  1719. lookAt.Y = ParseFloat(requestData, "lookat_y", sp.Lookat.Y);
  1720. lookAt.Z = ParseFloat(requestData, "lookat_z", sp.Lookat.Z);
  1721. sp.Scene.RequestTeleportLocation(
  1722. sp.ControllingClient, regionName, pos, lookAt, (uint)Constants.TeleportFlags.ViaLocation);
  1723. // We have no way of telling the failure of the actual teleport
  1724. responseData["success"] = true;
  1725. }
  1726. /// <summary>
  1727. /// Parse a float with the given parameter name from a request data hash table.
  1728. /// </summary>
  1729. /// <remarks>
  1730. /// Will throw an exception if parameter is not a float.
  1731. /// Will not throw if parameter is not found, passes back default value instead.
  1732. /// </remarks>
  1733. /// <param name="requestData"></param>
  1734. /// <param name="paramName"></param>
  1735. /// <param name="defaultVal"></param>
  1736. /// <returns></returns>
  1737. private static float ParseFloat(Hashtable requestData, string paramName, float defaultVal)
  1738. {
  1739. if (requestData.Contains(paramName))
  1740. {
  1741. string rawVal = (string)requestData[paramName];
  1742. float val;
  1743. if (!float.TryParse(rawVal, out val))
  1744. throw new Exception(string.Format("{0} {1} is not a valid float", paramName, rawVal));
  1745. else
  1746. return val;
  1747. }
  1748. else
  1749. {
  1750. return defaultVal;
  1751. }
  1752. }
  1753. private static void CheckStringParameters(Hashtable requestData, Hashtable responseData, string[] param)
  1754. {
  1755. foreach (string parameter in param)
  1756. {
  1757. if (!requestData.Contains(parameter))
  1758. {
  1759. responseData["accepted"] = false;
  1760. throw new Exception(String.Format("missing string parameter {0}", parameter));
  1761. }
  1762. if (String.IsNullOrEmpty((string) requestData[parameter]))
  1763. {
  1764. responseData["accepted"] = false;
  1765. throw new Exception(String.Format("parameter {0} is empty", parameter));
  1766. }
  1767. }
  1768. }
  1769. private static void CheckIntegerParams(Hashtable requestData, Hashtable responseData, string[] param)
  1770. {
  1771. foreach (string parameter in param)
  1772. {
  1773. if (!requestData.Contains(parameter))
  1774. {
  1775. responseData["accepted"] = false;
  1776. throw new Exception(String.Format("missing integer parameter {0}", parameter));
  1777. }
  1778. }
  1779. }
  1780. private void CheckRegionParams(Hashtable requestData, Hashtable responseData)
  1781. {
  1782. //Checks if region parameters exist and gives exeption if no parameters are given
  1783. if ((requestData.ContainsKey("region_id") && !String.IsNullOrEmpty((string)requestData["region_id"])) ||
  1784. (requestData.ContainsKey("region_name") && !String.IsNullOrEmpty((string)requestData["region_name"])))
  1785. {
  1786. return;
  1787. }
  1788. else
  1789. {
  1790. responseData["accepted"] = false;
  1791. throw new Exception("no region_name or region_id given");
  1792. }
  1793. }
  1794. private void GetSceneFromRegionParams(Hashtable requestData, Hashtable responseData, out Scene scene)
  1795. {
  1796. scene = null;
  1797. if (requestData.ContainsKey("region_id") &&
  1798. !String.IsNullOrEmpty((string)requestData["region_id"]))
  1799. {
  1800. UUID regionID = (UUID)(string)requestData["region_id"];
  1801. if (!m_application.SceneManager.TryGetScene(regionID, out scene))
  1802. {
  1803. responseData["error"] = String.Format("Region ID {0} not found", regionID);
  1804. throw new Exception(String.Format("Region ID {0} not found", regionID));
  1805. }
  1806. }
  1807. else if (requestData.ContainsKey("region_name") &&
  1808. !String.IsNullOrEmpty((string)requestData["region_name"]))
  1809. {
  1810. string regionName = (string)requestData["region_name"];
  1811. if (!m_application.SceneManager.TryGetScene(regionName, out scene))
  1812. {
  1813. responseData["error"] = String.Format("Region {0} not found", regionName);
  1814. throw new Exception(String.Format("Region {0} not found", regionName));
  1815. }
  1816. }
  1817. else
  1818. {
  1819. responseData["error"] = "no region_name or region_id given";
  1820. throw new Exception("no region_name or region_id given");
  1821. }
  1822. return;
  1823. }
  1824. private bool GetBoolean(Hashtable requestData, string tag, bool defaultValue)
  1825. {
  1826. // If an access value has been provided, apply it.
  1827. if (requestData.Contains(tag))
  1828. {
  1829. switch (((string)requestData[tag]).ToLower())
  1830. {
  1831. case "true" :
  1832. case "t" :
  1833. case "1" :
  1834. return true;
  1835. case "false" :
  1836. case "f" :
  1837. case "0" :
  1838. return false;
  1839. default :
  1840. return defaultValue;
  1841. }
  1842. }
  1843. else
  1844. return defaultValue;
  1845. }
  1846. private int GetIntegerAttribute(XmlNode node, string attribute, int defaultValue)
  1847. {
  1848. try { return Convert.ToInt32(node.Attributes[attribute].Value); } catch{}
  1849. return defaultValue;
  1850. }
  1851. private uint GetUnsignedAttribute(XmlNode node, string attribute, uint defaultValue)
  1852. {
  1853. try { return Convert.ToUInt32(node.Attributes[attribute].Value); } catch{}
  1854. return defaultValue;
  1855. }
  1856. private string GetStringAttribute(XmlNode node, string attribute, string defaultValue)
  1857. {
  1858. try { return node.Attributes[attribute].Value; } catch{}
  1859. return defaultValue;
  1860. }
  1861. public void Dispose()
  1862. {
  1863. }
  1864. /// <summary>
  1865. /// Create a user
  1866. /// </summary>
  1867. /// <param name="scopeID"></param>
  1868. /// <param name="firstName"></param>
  1869. /// <param name="lastName"></param>
  1870. /// <param name="password"></param>
  1871. /// <param name="email"></param>
  1872. private UserAccount CreateUser(UUID scopeID, string firstName, string lastName, string password, string email)
  1873. {
  1874. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1875. IUserAccountService userAccountService = scene.UserAccountService;
  1876. IGridService gridService = scene.GridService;
  1877. IAuthenticationService authenticationService = scene.AuthenticationService;
  1878. IGridUserService gridUserService = scene.GridUserService;
  1879. IInventoryService inventoryService = scene.InventoryService;
  1880. UserAccount account = userAccountService.GetUserAccount(scopeID, firstName, lastName);
  1881. if (null == account)
  1882. {
  1883. account = new UserAccount(scopeID, UUID.Random(), firstName, lastName, email);
  1884. if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
  1885. {
  1886. account.ServiceURLs = new Dictionary<string, object>();
  1887. account.ServiceURLs["HomeURI"] = string.Empty;
  1888. account.ServiceURLs["GatekeeperURI"] = string.Empty;
  1889. account.ServiceURLs["InventoryServerURI"] = string.Empty;
  1890. account.ServiceURLs["AssetServerURI"] = string.Empty;
  1891. }
  1892. if (userAccountService.StoreUserAccount(account))
  1893. {
  1894. bool success;
  1895. if (authenticationService != null)
  1896. {
  1897. success = authenticationService.SetPassword(account.PrincipalID, password);
  1898. if (!success)
  1899. m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
  1900. firstName, lastName);
  1901. }
  1902. GridRegion home = null;
  1903. if (gridService != null)
  1904. {
  1905. List<GridRegion> defaultRegions = gridService.GetDefaultRegions(UUID.Zero);
  1906. if (defaultRegions != null && defaultRegions.Count >= 1)
  1907. home = defaultRegions[0];
  1908. if (gridUserService != null && home != null)
  1909. gridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  1910. else
  1911. m_log.WarnFormat("[RADMIN]: Unable to set home for account {0} {1}.",
  1912. firstName, lastName);
  1913. }
  1914. else
  1915. m_log.WarnFormat("[RADMIN]: Unable to retrieve home region for account {0} {1}.",
  1916. firstName, lastName);
  1917. if (inventoryService != null)
  1918. {
  1919. success = inventoryService.CreateUserInventory(account.PrincipalID);
  1920. if (!success)
  1921. m_log.WarnFormat("[RADMIN]: Unable to create inventory for account {0} {1}.",
  1922. firstName, lastName);
  1923. }
  1924. m_log.InfoFormat("[RADMIN]: Account {0} {1} created successfully", firstName, lastName);
  1925. return account;
  1926. } else {
  1927. m_log.ErrorFormat("[RADMIN]: Account creation failed for account {0} {1}", firstName, lastName);
  1928. }
  1929. }
  1930. else
  1931. {
  1932. m_log.ErrorFormat("[RADMIN]: A user with the name {0} {1} already exists!", firstName, lastName);
  1933. }
  1934. return null;
  1935. }
  1936. /// <summary>
  1937. /// Change password
  1938. /// </summary>
  1939. /// <param name="firstName"></param>
  1940. /// <param name="lastName"></param>
  1941. /// <param name="password"></param>
  1942. private bool ChangeUserPassword(string firstName, string lastName, string password)
  1943. {
  1944. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  1945. IUserAccountService userAccountService = scene.UserAccountService;
  1946. IAuthenticationService authenticationService = scene.AuthenticationService;
  1947. UserAccount account = userAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
  1948. if (null != account)
  1949. {
  1950. bool success = false;
  1951. if (authenticationService != null)
  1952. success = authenticationService.SetPassword(account.PrincipalID, password);
  1953. if (!success)
  1954. {
  1955. m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
  1956. firstName, lastName);
  1957. return false;
  1958. }
  1959. return true;
  1960. }
  1961. else
  1962. {
  1963. m_log.ErrorFormat("[RADMIN]: No such user");
  1964. return false;
  1965. }
  1966. }
  1967. private bool LoadHeightmap(string file, UUID regionID)
  1968. {
  1969. m_log.InfoFormat("[RADMIN]: Terrain Loading: {0}", file);
  1970. Scene region = null;
  1971. if (!m_application.SceneManager.TryGetScene(regionID, out region))
  1972. {
  1973. m_log.InfoFormat("[RADMIN]: unable to get a scene with that name: {0}", regionID.ToString());
  1974. return false;
  1975. }
  1976. ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
  1977. if (null == terrainModule) throw new Exception("terrain module not available");
  1978. if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
  1979. {
  1980. m_log.Info("[RADMIN]: Terrain path is URL");
  1981. Uri result;
  1982. if (Uri.TryCreate(file, UriKind.RelativeOrAbsolute, out result))
  1983. {
  1984. // the url is valid
  1985. string fileType = file.Substring(file.LastIndexOf('/') + 1);
  1986. terrainModule.LoadFromStream(fileType, result);
  1987. }
  1988. }
  1989. else
  1990. {
  1991. terrainModule.LoadFromFile(file);
  1992. }
  1993. m_log.Info("[RADMIN]: Load height maps request complete");
  1994. return true;
  1995. }
  1996. /// <summary>
  1997. /// This method is called by the user-create and user-modify methods to establish
  1998. /// or change, the user's appearance. Default avatar names can be specified via
  1999. /// the config file, but must correspond to avatars in the default appearance
  2000. /// file, or pre-existing in the user database.
  2001. /// This should probably get moved into somewhere more core eventually.
  2002. /// </summary>
  2003. private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
  2004. {
  2005. m_log.DebugFormat("[RADMIN]: updateUserAppearance");
  2006. string defaultMale = m_config.GetString("default_male", "Default Male");
  2007. string defaultFemale = m_config.GetString("default_female", "Default Female");
  2008. string defaultNeutral = m_config.GetString("default_female", "Default Default");
  2009. string model = String.Empty;
  2010. // Has a gender preference been supplied?
  2011. if (requestData.Contains("gender"))
  2012. {
  2013. switch ((string)requestData["gender"])
  2014. {
  2015. case "m" :
  2016. case "male" :
  2017. model = defaultMale;
  2018. break;
  2019. case "f" :
  2020. case "female" :
  2021. model = defaultFemale;
  2022. break;
  2023. case "n" :
  2024. case "neutral" :
  2025. default :
  2026. model = defaultNeutral;
  2027. break;
  2028. }
  2029. }
  2030. // Has an explicit model been specified?
  2031. if (requestData.Contains("model") && (String.IsNullOrEmpty((string)requestData["gender"])))
  2032. {
  2033. model = (string)requestData["model"];
  2034. }
  2035. // No appearance attributes were set
  2036. if (String.IsNullOrEmpty(model))
  2037. {
  2038. m_log.DebugFormat("[RADMIN]: Appearance update not requested");
  2039. return;
  2040. }
  2041. m_log.DebugFormat("[RADMIN]: Setting appearance for avatar {0}, using model <{1}>", userid, model);
  2042. string[] modelSpecifiers = model.Split();
  2043. if (modelSpecifiers.Length != 2)
  2044. {
  2045. m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
  2046. // modelSpecifiers = dmodel.Split();
  2047. return;
  2048. }
  2049. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  2050. UUID scopeID = scene.RegionInfo.ScopeID;
  2051. UserAccount modelProfile = scene.UserAccountService.GetUserAccount(scopeID, modelSpecifiers[0], modelSpecifiers[1]);
  2052. if (modelProfile == null)
  2053. {
  2054. m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model);
  2055. return;
  2056. }
  2057. // Set current user's appearance. This bit is easy. The appearance structure is populated with
  2058. // actual asset ids, however to complete the magic we need to populate the inventory with the
  2059. // assets in question.
  2060. EstablishAppearance(userid, modelProfile.PrincipalID);
  2061. m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}",
  2062. userid, model);
  2063. }
  2064. /// <summary>
  2065. /// This method is called by updateAvatarAppearance once any specified model has been
  2066. /// ratified, or an appropriate default value has been adopted. The intended prototype
  2067. /// is known to exist, as is the target avatar.
  2068. /// </summary>
  2069. private void EstablishAppearance(UUID destination, UUID source)
  2070. {
  2071. m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source);
  2072. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  2073. // If the model has no associated appearance we're done.
  2074. AvatarAppearance avatarAppearance = scene.AvatarService.GetAppearance(source);
  2075. if (avatarAppearance == null)
  2076. return;
  2077. // Simple appearance copy or copy Clothing and Bodyparts folders?
  2078. bool copyFolders = m_config.GetBoolean("copy_folders", false);
  2079. if (!copyFolders)
  2080. {
  2081. // Simple copy of wearables and appearance update
  2082. try
  2083. {
  2084. CopyWearablesAndAttachments(destination, source, avatarAppearance);
  2085. scene.AvatarService.SetAppearance(destination, avatarAppearance);
  2086. }
  2087. catch (Exception e)
  2088. {
  2089. m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
  2090. destination, e.Message);
  2091. }
  2092. return;
  2093. }
  2094. // Copy Clothing and Bodypart folders and appearance update
  2095. try
  2096. {
  2097. Dictionary<UUID,UUID> inventoryMap = new Dictionary<UUID,UUID>();
  2098. CopyInventoryFolders(destination, source, AssetType.Clothing, inventoryMap, avatarAppearance);
  2099. CopyInventoryFolders(destination, source, AssetType.Bodypart, inventoryMap, avatarAppearance);
  2100. AvatarWearable[] wearables = avatarAppearance.Wearables;
  2101. for (int i=0; i<wearables.Length; i++)
  2102. {
  2103. if (inventoryMap.ContainsKey(wearables[i][0].ItemID))
  2104. {
  2105. AvatarWearable wearable = new AvatarWearable();
  2106. wearable.Wear(inventoryMap[wearables[i][0].ItemID],
  2107. wearables[i][0].AssetID);
  2108. avatarAppearance.SetWearable(i, wearable);
  2109. }
  2110. }
  2111. scene.AvatarService.SetAppearance(destination, avatarAppearance);
  2112. }
  2113. catch (Exception e)
  2114. {
  2115. m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
  2116. destination, e.Message);
  2117. }
  2118. return;
  2119. }
  2120. /// <summary>
  2121. /// This method is called by establishAppearance to do a copy all inventory items
  2122. /// worn or attached to the Clothing inventory folder of the receiving avatar.
  2123. /// In parallel the avatar wearables and attachments are updated.
  2124. /// </summary>
  2125. private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance)
  2126. {
  2127. IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
  2128. // Get Clothing folder of receiver
  2129. InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, AssetType.Clothing);
  2130. if (destinationFolder == null)
  2131. throw new Exception("Cannot locate folder(s)");
  2132. // Missing destination folder? This should *never* be the case
  2133. if (destinationFolder.Type != (short)AssetType.Clothing)
  2134. {
  2135. destinationFolder = new InventoryFolderBase();
  2136. destinationFolder.ID = UUID.Random();
  2137. destinationFolder.Name = "Clothing";
  2138. destinationFolder.Owner = destination;
  2139. destinationFolder.Type = (short)AssetType.Clothing;
  2140. destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
  2141. destinationFolder.Version = 1;
  2142. inventoryService.AddFolder(destinationFolder); // store base record
  2143. m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
  2144. }
  2145. // Wearables
  2146. AvatarWearable[] wearables = avatarAppearance.Wearables;
  2147. AvatarWearable wearable;
  2148. for (int i = 0; i<wearables.Length; i++)
  2149. {
  2150. wearable = wearables[i];
  2151. if (wearable[0].ItemID != UUID.Zero)
  2152. {
  2153. // Get inventory item and copy it
  2154. InventoryItemBase item = new InventoryItemBase(wearable[0].ItemID, source);
  2155. item = inventoryService.GetItem(item);
  2156. if (item != null)
  2157. {
  2158. InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
  2159. destinationItem.Name = item.Name;
  2160. destinationItem.Owner = destination;
  2161. destinationItem.Description = item.Description;
  2162. destinationItem.InvType = item.InvType;
  2163. destinationItem.CreatorId = item.CreatorId;
  2164. destinationItem.CreatorData = item.CreatorData;
  2165. destinationItem.NextPermissions = item.NextPermissions;
  2166. destinationItem.CurrentPermissions = item.CurrentPermissions;
  2167. destinationItem.BasePermissions = item.BasePermissions;
  2168. destinationItem.EveryOnePermissions = item.EveryOnePermissions;
  2169. destinationItem.GroupPermissions = item.GroupPermissions;
  2170. destinationItem.AssetType = item.AssetType;
  2171. destinationItem.AssetID = item.AssetID;
  2172. destinationItem.GroupID = item.GroupID;
  2173. destinationItem.GroupOwned = item.GroupOwned;
  2174. destinationItem.SalePrice = item.SalePrice;
  2175. destinationItem.SaleType = item.SaleType;
  2176. destinationItem.Flags = item.Flags;
  2177. destinationItem.CreationDate = item.CreationDate;
  2178. destinationItem.Folder = destinationFolder.ID;
  2179. ApplyNextOwnerPermissions(destinationItem);
  2180. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
  2181. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
  2182. // Wear item
  2183. AvatarWearable newWearable = new AvatarWearable();
  2184. newWearable.Wear(destinationItem.ID, wearable[0].AssetID);
  2185. avatarAppearance.SetWearable(i, newWearable);
  2186. }
  2187. else
  2188. {
  2189. m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", wearable[0].ItemID, destinationFolder.ID);
  2190. }
  2191. }
  2192. }
  2193. // Attachments
  2194. List<AvatarAttachment> attachments = avatarAppearance.GetAttachments();
  2195. foreach (AvatarAttachment attachment in attachments)
  2196. {
  2197. int attachpoint = attachment.AttachPoint;
  2198. UUID itemID = attachment.ItemID;
  2199. if (itemID != UUID.Zero)
  2200. {
  2201. // Get inventory item and copy it
  2202. InventoryItemBase item = new InventoryItemBase(itemID, source);
  2203. item = inventoryService.GetItem(item);
  2204. if (item != null)
  2205. {
  2206. InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
  2207. destinationItem.Name = item.Name;
  2208. destinationItem.Owner = destination;
  2209. destinationItem.Description = item.Description;
  2210. destinationItem.InvType = item.InvType;
  2211. destinationItem.CreatorId = item.CreatorId;
  2212. destinationItem.CreatorData = item.CreatorData;
  2213. destinationItem.NextPermissions = item.NextPermissions;
  2214. destinationItem.CurrentPermissions = item.CurrentPermissions;
  2215. destinationItem.BasePermissions = item.BasePermissions;
  2216. destinationItem.EveryOnePermissions = item.EveryOnePermissions;
  2217. destinationItem.GroupPermissions = item.GroupPermissions;
  2218. destinationItem.AssetType = item.AssetType;
  2219. destinationItem.AssetID = item.AssetID;
  2220. destinationItem.GroupID = item.GroupID;
  2221. destinationItem.GroupOwned = item.GroupOwned;
  2222. destinationItem.SalePrice = item.SalePrice;
  2223. destinationItem.SaleType = item.SaleType;
  2224. destinationItem.Flags = item.Flags;
  2225. destinationItem.CreationDate = item.CreationDate;
  2226. destinationItem.Folder = destinationFolder.ID;
  2227. ApplyNextOwnerPermissions(destinationItem);
  2228. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
  2229. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
  2230. // Attach item
  2231. avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
  2232. m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
  2233. }
  2234. else
  2235. {
  2236. m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", itemID, destinationFolder.ID);
  2237. }
  2238. }
  2239. }
  2240. }
  2241. /// <summary>
  2242. /// This method is called by establishAppearance to copy inventory folders to make
  2243. /// copies of Clothing and Bodyparts inventory folders and attaches worn attachments
  2244. /// </summary>
  2245. private void CopyInventoryFolders(UUID destination, UUID source, AssetType assetType, Dictionary<UUID,UUID> inventoryMap,
  2246. AvatarAppearance avatarAppearance)
  2247. {
  2248. IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;
  2249. InventoryFolderBase sourceFolder = inventoryService.GetFolderForType(source, assetType);
  2250. InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, assetType);
  2251. if (sourceFolder == null || destinationFolder == null)
  2252. throw new Exception("Cannot locate folder(s)");
  2253. // Missing source folder? This should *never* be the case
  2254. if (sourceFolder.Type != (short)assetType)
  2255. {
  2256. sourceFolder = new InventoryFolderBase();
  2257. sourceFolder.ID = UUID.Random();
  2258. if (assetType == AssetType.Clothing) {
  2259. sourceFolder.Name = "Clothing";
  2260. } else {
  2261. sourceFolder.Name = "Body Parts";
  2262. }
  2263. sourceFolder.Owner = source;
  2264. sourceFolder.Type = (short)assetType;
  2265. sourceFolder.ParentID = inventoryService.GetRootFolder(source).ID;
  2266. sourceFolder.Version = 1;
  2267. inventoryService.AddFolder(sourceFolder); // store base record
  2268. m_log.ErrorFormat("[RADMIN] Created folder for source {0}", source);
  2269. }
  2270. // Missing destination folder? This should *never* be the case
  2271. if (destinationFolder.Type != (short)assetType)
  2272. {
  2273. destinationFolder = new InventoryFolderBase();
  2274. destinationFolder.ID = UUID.Random();
  2275. if (assetType == AssetType.Clothing)
  2276. {
  2277. destinationFolder.Name = "Clothing";
  2278. }
  2279. else
  2280. {
  2281. destinationFolder.Name = "Body Parts";
  2282. }
  2283. destinationFolder.Owner = destination;
  2284. destinationFolder.Type = (short)assetType;
  2285. destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
  2286. destinationFolder.Version = 1;
  2287. inventoryService.AddFolder(destinationFolder); // store base record
  2288. m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
  2289. }
  2290. InventoryFolderBase extraFolder;
  2291. List<InventoryFolderBase> folders = inventoryService.GetFolderContent(source, sourceFolder.ID).Folders;
  2292. foreach (InventoryFolderBase folder in folders)
  2293. {
  2294. extraFolder = new InventoryFolderBase();
  2295. extraFolder.ID = UUID.Random();
  2296. extraFolder.Name = folder.Name;
  2297. extraFolder.Owner = destination;
  2298. extraFolder.Type = folder.Type;
  2299. extraFolder.Version = folder.Version;
  2300. extraFolder.ParentID = destinationFolder.ID;
  2301. inventoryService.AddFolder(extraFolder);
  2302. m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);
  2303. List<InventoryItemBase> items = inventoryService.GetFolderContent(source, folder.ID).Items;
  2304. foreach (InventoryItemBase item in items)
  2305. {
  2306. InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
  2307. destinationItem.Name = item.Name;
  2308. destinationItem.Owner = destination;
  2309. destinationItem.Description = item.Description;
  2310. destinationItem.InvType = item.InvType;
  2311. destinationItem.CreatorId = item.CreatorId;
  2312. destinationItem.CreatorData = item.CreatorData;
  2313. destinationItem.NextPermissions = item.NextPermissions;
  2314. destinationItem.CurrentPermissions = item.CurrentPermissions;
  2315. destinationItem.BasePermissions = item.BasePermissions;
  2316. destinationItem.EveryOnePermissions = item.EveryOnePermissions;
  2317. destinationItem.GroupPermissions = item.GroupPermissions;
  2318. destinationItem.AssetType = item.AssetType;
  2319. destinationItem.AssetID = item.AssetID;
  2320. destinationItem.GroupID = item.GroupID;
  2321. destinationItem.GroupOwned = item.GroupOwned;
  2322. destinationItem.SalePrice = item.SalePrice;
  2323. destinationItem.SaleType = item.SaleType;
  2324. destinationItem.Flags = item.Flags;
  2325. destinationItem.CreationDate = item.CreationDate;
  2326. destinationItem.Folder = extraFolder.ID;
  2327. ApplyNextOwnerPermissions(destinationItem);
  2328. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
  2329. inventoryMap.Add(item.ID, destinationItem.ID);
  2330. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, extraFolder.ID);
  2331. // Attach item, if original is attached
  2332. int attachpoint = avatarAppearance.GetAttachpoint(item.ID);
  2333. if (attachpoint != 0)
  2334. {
  2335. avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
  2336. m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
  2337. }
  2338. }
  2339. }
  2340. }
  2341. /// <summary>
  2342. /// Apply next owner permissions.
  2343. /// </summary>
  2344. private void ApplyNextOwnerPermissions(InventoryItemBase item)
  2345. {
  2346. if (item.InvType == (int)InventoryType.Object)
  2347. {
  2348. uint perms = item.CurrentPermissions;
  2349. PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref perms);
  2350. item.CurrentPermissions = perms;
  2351. }
  2352. item.CurrentPermissions &= item.NextPermissions;
  2353. item.BasePermissions &= item.NextPermissions;
  2354. item.EveryOnePermissions &= item.NextPermissions;
  2355. // item.OwnerChanged = true;
  2356. // item.PermsMask = 0;
  2357. // item.PermsGranter = UUID.Zero;
  2358. }
  2359. /// <summary>
  2360. /// This method is called if a given model avatar name can not be found. If the external
  2361. /// file has already been loaded once, then control returns immediately. If not, then it
  2362. /// looks for a default appearance file. This file contains XML definitions of zero or more named
  2363. /// avatars, each avatar can specify zero or more "outfits". Each outfit is a collection
  2364. /// of items that together, define a particular ensemble for the avatar. Each avatar should
  2365. /// indicate which outfit is the default, and this outfit will be automatically worn. The
  2366. /// other outfits are provided to allow "real" avatars a way to easily change their outfits.
  2367. /// </summary>
  2368. private bool CreateDefaultAvatars()
  2369. {
  2370. // Only load once
  2371. if (m_defaultAvatarsLoaded)
  2372. {
  2373. return false;
  2374. }
  2375. m_log.DebugFormat("[RADMIN]: Creating default avatar entries");
  2376. m_defaultAvatarsLoaded = true;
  2377. // Load processing starts here...
  2378. try
  2379. {
  2380. string defaultAppearanceFileName = null;
  2381. //m_config may be null if RemoteAdmin configuration secition is missing or disabled in OpenSim.ini
  2382. if (m_config != null)
  2383. {
  2384. defaultAppearanceFileName = m_config.GetString("default_appearance", "default_appearance.xml");
  2385. }
  2386. if (File.Exists(defaultAppearanceFileName))
  2387. {
  2388. XmlDocument doc = new XmlDocument();
  2389. string name = "*unknown*";
  2390. string email = "anon@anon";
  2391. uint regionXLocation = 1000;
  2392. uint regionYLocation = 1000;
  2393. string password = UUID.Random().ToString(); // No requirement to sign-in.
  2394. UUID ID = UUID.Zero;
  2395. AvatarAppearance avatarAppearance;
  2396. XmlNodeList avatars;
  2397. XmlNodeList assets;
  2398. XmlNode perms = null;
  2399. bool include = false;
  2400. bool select = false;
  2401. Scene scene = m_application.SceneManager.CurrentOrFirstScene;
  2402. IInventoryService inventoryService = scene.InventoryService;
  2403. IAssetService assetService = scene.AssetService;
  2404. doc.LoadXml(File.ReadAllText(defaultAppearanceFileName));
  2405. // Load up any included assets. Duplicates will be ignored
  2406. assets = doc.GetElementsByTagName("RequiredAsset");
  2407. foreach (XmlNode assetNode in assets)
  2408. {
  2409. AssetBase asset = new AssetBase(UUID.Random(), GetStringAttribute(assetNode, "name", ""), SByte.Parse(GetStringAttribute(assetNode, "type", "")), UUID.Zero.ToString());
  2410. asset.Description = GetStringAttribute(assetNode,"desc","");
  2411. asset.Local = Boolean.Parse(GetStringAttribute(assetNode,"local",""));
  2412. asset.Temporary = Boolean.Parse(GetStringAttribute(assetNode,"temporary",""));
  2413. asset.Data = Convert.FromBase64String(assetNode.InnerText);
  2414. assetService.Store(asset);
  2415. }
  2416. avatars = doc.GetElementsByTagName("Avatar");
  2417. // The document may contain multiple avatars
  2418. foreach (XmlElement avatar in avatars)
  2419. {
  2420. m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}",
  2421. GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?"));
  2422. // Create the user identified by the avatar entry
  2423. try
  2424. {
  2425. // Only the name value is mandatory
  2426. name = GetStringAttribute(avatar,"name",name);
  2427. email = GetStringAttribute(avatar,"email",email);
  2428. regionXLocation = GetUnsignedAttribute(avatar,"regx",regionXLocation);
  2429. regionYLocation = GetUnsignedAttribute(avatar,"regy",regionYLocation);
  2430. password = GetStringAttribute(avatar,"password",password);
  2431. string[] names = name.Split();
  2432. UUID scopeID = scene.RegionInfo.ScopeID;
  2433. UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, names[0], names[1]);
  2434. if (null == account)
  2435. {
  2436. account = CreateUser(scopeID, names[0], names[1], password, email);
  2437. if (null == account)
  2438. {
  2439. m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]);
  2440. return false;
  2441. }
  2442. }
  2443. // Set home position
  2444. GridRegion home = scene.GridService.GetRegionByPosition(scopeID,
  2445. (int)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
  2446. if (null == home) {
  2447. m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", names[0], names[1]);
  2448. } else {
  2449. scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  2450. m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, names[0], names[1]);
  2451. }
  2452. ID = account.PrincipalID;
  2453. m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID);
  2454. include = true;
  2455. }
  2456. catch (Exception e)
  2457. {
  2458. m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message);
  2459. include = false;
  2460. }
  2461. // OK, User has been created OK, now we can install the inventory.
  2462. // First retrieve the current inventory (the user may already exist)
  2463. // Note that althought he inventory is retrieved, the hierarchy has
  2464. // not been interpreted at all.
  2465. if (include)
  2466. {
  2467. // Setup for appearance processing
  2468. avatarAppearance = scene.AvatarService.GetAppearance(ID);
  2469. if (avatarAppearance == null)
  2470. avatarAppearance = new AvatarAppearance();
  2471. AvatarWearable[] wearables = avatarAppearance.Wearables;
  2472. for (int i=0; i<wearables.Length; i++)
  2473. {
  2474. wearables[i] = new AvatarWearable();
  2475. }
  2476. try
  2477. {
  2478. // m_log.DebugFormat("[RADMIN] {0} folders, {1} items in inventory",
  2479. // uic.folders.Count, uic.items.Count);
  2480. InventoryFolderBase clothingFolder = inventoryService.GetFolderForType(ID, AssetType.Clothing);
  2481. // This should *never* be the case
  2482. if (clothingFolder == null || clothingFolder.Type != (short)AssetType.Clothing)
  2483. {
  2484. clothingFolder = new InventoryFolderBase();
  2485. clothingFolder.ID = UUID.Random();
  2486. clothingFolder.Name = "Clothing";
  2487. clothingFolder.Owner = ID;
  2488. clothingFolder.Type = (short)AssetType.Clothing;
  2489. clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID;
  2490. clothingFolder.Version = 1;
  2491. inventoryService.AddFolder(clothingFolder); // store base record
  2492. m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID);
  2493. }
  2494. // OK, now we have an inventory for the user, read in the outfits from the
  2495. // default appearance XMl file.
  2496. XmlNodeList outfits = avatar.GetElementsByTagName("Ensemble");
  2497. InventoryFolderBase extraFolder;
  2498. string outfitName;
  2499. UUID assetid;
  2500. foreach (XmlElement outfit in outfits)
  2501. {
  2502. m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}",
  2503. GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?"));
  2504. outfitName = GetStringAttribute(outfit,"name","");
  2505. select = (GetStringAttribute(outfit,"default","no") == "yes");
  2506. // If the folder already exists, re-use it. The defaults may
  2507. // change over time. Augment only.
  2508. List<InventoryFolderBase> folders = inventoryService.GetFolderContent(ID, clothingFolder.ID).Folders;
  2509. extraFolder = null;
  2510. foreach (InventoryFolderBase folder in folders)
  2511. {
  2512. if (folder.Name == outfitName)
  2513. {
  2514. extraFolder = folder;
  2515. break;
  2516. }
  2517. }
  2518. // Otherwise, we must create the folder.
  2519. if (extraFolder == null)
  2520. {
  2521. m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name);
  2522. extraFolder = new InventoryFolderBase();
  2523. extraFolder.ID = UUID.Random();
  2524. extraFolder.Name = outfitName;
  2525. extraFolder.Owner = ID;
  2526. extraFolder.Type = (short)AssetType.Clothing;
  2527. extraFolder.Version = 1;
  2528. extraFolder.ParentID = clothingFolder.ID;
  2529. inventoryService.AddFolder(extraFolder);
  2530. m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
  2531. }
  2532. // Now get the pieces that make up the outfit
  2533. XmlNodeList items = outfit.GetElementsByTagName("Item");
  2534. foreach (XmlElement item in items)
  2535. {
  2536. assetid = UUID.Zero;
  2537. XmlNodeList children = item.ChildNodes;
  2538. foreach (XmlNode child in children)
  2539. {
  2540. switch (child.Name)
  2541. {
  2542. case "Permissions" :
  2543. m_log.DebugFormat("[RADMIN]: Permissions specified");
  2544. perms = child;
  2545. break;
  2546. case "Asset" :
  2547. assetid = new UUID(child.InnerText);
  2548. break;
  2549. }
  2550. }
  2551. InventoryItemBase inventoryItem = null;
  2552. // Check if asset is in inventory already
  2553. inventoryItem = null;
  2554. List<InventoryItemBase> inventoryItems = inventoryService.GetFolderContent(ID, extraFolder.ID).Items;
  2555. foreach (InventoryItemBase listItem in inventoryItems)
  2556. {
  2557. if (listItem.AssetID == assetid)
  2558. {
  2559. inventoryItem = listItem;
  2560. break;
  2561. }
  2562. }
  2563. // Create inventory item
  2564. if (inventoryItem == null)
  2565. {
  2566. inventoryItem = new InventoryItemBase(UUID.Random(), ID);
  2567. inventoryItem.Name = GetStringAttribute(item,"name","");
  2568. inventoryItem.Description = GetStringAttribute(item,"desc","");
  2569. inventoryItem.InvType = GetIntegerAttribute(item,"invtype",-1);
  2570. inventoryItem.CreatorId = GetStringAttribute(item,"creatorid","");
  2571. inventoryItem.CreatorData = GetStringAttribute(item, "creatordata", "");
  2572. inventoryItem.NextPermissions = GetUnsignedAttribute(perms, "next", 0x7fffffff);
  2573. inventoryItem.CurrentPermissions = GetUnsignedAttribute(perms,"current",0x7fffffff);
  2574. inventoryItem.BasePermissions = GetUnsignedAttribute(perms,"base",0x7fffffff);
  2575. inventoryItem.EveryOnePermissions = GetUnsignedAttribute(perms,"everyone",0x7fffffff);
  2576. inventoryItem.GroupPermissions = GetUnsignedAttribute(perms,"group",0x7fffffff);
  2577. inventoryItem.AssetType = GetIntegerAttribute(item,"assettype",-1);
  2578. inventoryItem.AssetID = assetid; // associated asset
  2579. inventoryItem.GroupID = (UUID)GetStringAttribute(item,"groupid","");
  2580. inventoryItem.GroupOwned = (GetStringAttribute(item,"groupowned","false") == "true");
  2581. inventoryItem.SalePrice = GetIntegerAttribute(item,"saleprice",0);
  2582. inventoryItem.SaleType = (byte)GetIntegerAttribute(item,"saletype",0);
  2583. inventoryItem.Flags = GetUnsignedAttribute(item,"flags",0);
  2584. inventoryItem.CreationDate = GetIntegerAttribute(item,"creationdate",Util.UnixTimeSinceEpoch());
  2585. inventoryItem.Folder = extraFolder.ID; // Parent folder
  2586. m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem);
  2587. m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
  2588. }
  2589. // Attach item, if attachpoint is specified
  2590. int attachpoint = GetIntegerAttribute(item,"attachpoint",0);
  2591. if (attachpoint != 0)
  2592. {
  2593. avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID);
  2594. m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID);
  2595. }
  2596. // Record whether or not the item is to be initially worn
  2597. try
  2598. {
  2599. if (select && (GetStringAttribute(item, "wear", "false") == "true"))
  2600. {
  2601. avatarAppearance.Wearables[inventoryItem.Flags].Wear(inventoryItem.ID, inventoryItem.AssetID);
  2602. }
  2603. }
  2604. catch (Exception e)
  2605. {
  2606. m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
  2607. }
  2608. } // foreach item in outfit
  2609. m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName);
  2610. } // foreach outfit
  2611. m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name);
  2612. scene.AvatarService.SetAppearance(ID, avatarAppearance);
  2613. }
  2614. catch (Exception e)
  2615. {
  2616. m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}",
  2617. name, e.Message);
  2618. }
  2619. } // End of include
  2620. }
  2621. m_log.DebugFormat("[RADMIN]: Default avatar loading complete");
  2622. }
  2623. else
  2624. {
  2625. m_log.DebugFormat("[RADMIN]: No default avatar information available");
  2626. return false;
  2627. }
  2628. }
  2629. catch (Exception e)
  2630. {
  2631. m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message);
  2632. return false;
  2633. }
  2634. return true;
  2635. }
  2636. }
  2637. }