RemoteAdminPlugin.cs 148 KB

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