Util.cs 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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.Data;
  31. using System.Diagnostics;
  32. using System.Globalization;
  33. using System.IO;
  34. using System.IO.Compression;
  35. using System.Net;
  36. using System.Net.Sockets;
  37. using System.Reflection;
  38. using System.Runtime.InteropServices;
  39. using System.Runtime.Serialization;
  40. using System.Runtime.Serialization.Formatters.Binary;
  41. using System.Security.Cryptography;
  42. using System.Text;
  43. using System.Text.RegularExpressions;
  44. using System.Xml;
  45. using System.Threading;
  46. using log4net;
  47. using Nini.Config;
  48. using Nwc.XmlRpc;
  49. using OpenMetaverse;
  50. using OpenMetaverse.StructuredData;
  51. using Amib.Threading;
  52. namespace OpenSim.Framework
  53. {
  54. /// <summary>
  55. /// The method used by Util.FireAndForget for asynchronously firing events
  56. /// </summary>
  57. /// <remarks>
  58. /// None is used to execute the method in the same thread that made the call. It should only be used by regression
  59. /// test code that relies on predictable event ordering.
  60. /// RegressionTest is used by regression tests. It fires the call synchronously and does not catch any exceptions.
  61. /// </remarks>
  62. public enum FireAndForgetMethod
  63. {
  64. None,
  65. RegressionTest,
  66. UnsafeQueueUserWorkItem,
  67. QueueUserWorkItem,
  68. BeginInvoke,
  69. SmartThreadPool,
  70. Thread,
  71. }
  72. /// <summary>
  73. /// Miscellaneous utility functions
  74. /// </summary>
  75. public class Util
  76. {
  77. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  78. private static uint nextXferID = 5000;
  79. private static Random randomClass = new Random();
  80. // Get a list of invalid file characters (OS dependent)
  81. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  82. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  83. private static object XferLock = new object();
  84. /// <summary>
  85. /// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
  86. /// </summary>
  87. private static SmartThreadPool m_ThreadPool;
  88. // Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC.
  89. private static readonly DateTime unixEpoch =
  90. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  91. private static readonly string rawUUIDPattern
  92. = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
  93. public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
  94. public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
  95. public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  96. public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
  97. /// <summary>
  98. /// Gets the name of the directory where the current running executable
  99. /// is located
  100. /// </summary>
  101. /// <returns>Filesystem path to the directory containing the current
  102. /// executable</returns>
  103. public static string ExecutingDirectory()
  104. {
  105. return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  106. }
  107. /// <summary>
  108. /// Linear interpolates B<->C using percent A
  109. /// </summary>
  110. /// <param name="a"></param>
  111. /// <param name="b"></param>
  112. /// <param name="c"></param>
  113. /// <returns></returns>
  114. public static double lerp(double a, double b, double c)
  115. {
  116. return (b*a) + (c*(1 - a));
  117. }
  118. /// <summary>
  119. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  120. /// Layout:
  121. /// A B
  122. /// C D
  123. /// A<->C = Y
  124. /// C<->D = X
  125. /// </summary>
  126. /// <param name="x"></param>
  127. /// <param name="y"></param>
  128. /// <param name="a"></param>
  129. /// <param name="b"></param>
  130. /// <param name="c"></param>
  131. /// <param name="d"></param>
  132. /// <returns></returns>
  133. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  134. {
  135. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  136. }
  137. public static Encoding UTF8 = Encoding.UTF8;
  138. public static Encoding UTF8NoBomEncoding = new UTF8Encoding(false);
  139. /// <value>
  140. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  141. /// </value>
  142. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  143. #region Vector Equations
  144. /// <summary>
  145. /// Get the distance between two 3d vectors
  146. /// </summary>
  147. /// <param name="a">A 3d vector</param>
  148. /// <param name="b">A 3d vector</param>
  149. /// <returns>The distance between the two vectors</returns>
  150. public static double GetDistanceTo(Vector3 a, Vector3 b)
  151. {
  152. float dx = a.X - b.X;
  153. float dy = a.Y - b.Y;
  154. float dz = a.Z - b.Z;
  155. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  156. }
  157. /// <summary>
  158. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  159. /// </summary>
  160. /// <param name="a"></param>
  161. /// <param name="b"></param>
  162. /// <param name="amount"></param>
  163. /// <returns></returns>
  164. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  165. {
  166. float dx = a.X - b.X;
  167. float dy = a.Y - b.Y;
  168. float dz = a.Z - b.Z;
  169. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  170. }
  171. /// <summary>
  172. /// Get the magnitude of a 3d vector
  173. /// </summary>
  174. /// <param name="a">A 3d vector</param>
  175. /// <returns>The magnitude of the vector</returns>
  176. public static double GetMagnitude(Vector3 a)
  177. {
  178. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  179. }
  180. /// <summary>
  181. /// Get a normalized form of a 3d vector
  182. /// </summary>
  183. /// <param name="a">A 3d vector</param>
  184. /// <returns>A new vector which is normalized form of the vector</returns>
  185. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  186. public static Vector3 GetNormalizedVector(Vector3 a)
  187. {
  188. if (IsZeroVector(a))
  189. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  190. float Mag = (float) GetMagnitude(a);
  191. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  192. }
  193. /// <summary>
  194. /// Returns if a vector is a zero vector (has all zero components)
  195. /// </summary>
  196. /// <returns></returns>
  197. public static bool IsZeroVector(Vector3 v)
  198. {
  199. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  200. {
  201. return true;
  202. }
  203. return false;
  204. }
  205. # endregion
  206. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  207. {
  208. float s;
  209. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  210. if (tr >= 1.0)
  211. {
  212. s = (float) (0.5 / Math.Sqrt(tr));
  213. return new Quaternion(
  214. (left.Z - up.Y) * s,
  215. (up.X - fwd.Z) * s,
  216. (fwd.Y - left.X) * s,
  217. (float) 0.25 / s);
  218. }
  219. else
  220. {
  221. float max = (left.Y > up.Z) ? left.Y : up.Z;
  222. if (max < fwd.X)
  223. {
  224. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  225. float x = (float) (s * 0.5);
  226. s = (float) (0.5 / s);
  227. return new Quaternion(
  228. x,
  229. (fwd.Y + left.X) * s,
  230. (up.X + fwd.Z) * s,
  231. (left.Z - up.Y) * s);
  232. }
  233. else if (max == left.Y)
  234. {
  235. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  236. float y = (float) (s * 0.5);
  237. s = (float) (0.5 / s);
  238. return new Quaternion(
  239. (fwd.Y + left.X) * s,
  240. y,
  241. (left.Z + up.Y) * s,
  242. (up.X - fwd.Z) * s);
  243. }
  244. else
  245. {
  246. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  247. float z = (float) (s * 0.5);
  248. s = (float) (0.5 / s);
  249. return new Quaternion(
  250. (up.X + fwd.Z) * s,
  251. (left.Z + up.Y) * s,
  252. z,
  253. (fwd.Y - left.X) * s);
  254. }
  255. }
  256. }
  257. public static Random RandomClass
  258. {
  259. get { return randomClass; }
  260. }
  261. public static ulong UIntsToLong(uint X, uint Y)
  262. {
  263. return Utils.UIntsToLong(X, Y);
  264. }
  265. public static T Clamp<T>(T x, T min, T max)
  266. where T : IComparable<T>
  267. {
  268. return x.CompareTo(max) > 0 ? max :
  269. x.CompareTo(min) < 0 ? min :
  270. x;
  271. }
  272. public static uint GetNextXferID()
  273. {
  274. uint id = 0;
  275. lock (XferLock)
  276. {
  277. id = nextXferID;
  278. nextXferID++;
  279. }
  280. return id;
  281. }
  282. public static string GetFileName(string file)
  283. {
  284. // Return just the filename on UNIX platforms
  285. // TODO: this should be customisable with a prefix, but that's something to do later.
  286. if (Environment.OSVersion.Platform == PlatformID.Unix)
  287. {
  288. return file;
  289. }
  290. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  291. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  292. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  293. {
  294. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  295. {
  296. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  297. }
  298. return "%APPDATA%\\OpenSim\\" + file;
  299. }
  300. // Catch all - covers older windows versions
  301. // (but those probably wont work anyway)
  302. return file;
  303. }
  304. /// <summary>
  305. /// Debug utility function to convert OSD into formatted XML for debugging purposes.
  306. /// </summary>
  307. /// <param name="osd">
  308. /// A <see cref="OSD"/>
  309. /// </param>
  310. /// <returns>
  311. /// A <see cref="System.String"/>
  312. /// </returns>
  313. public static string GetFormattedXml(OSD osd)
  314. {
  315. return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
  316. }
  317. /// <summary>
  318. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  319. /// </summary>
  320. /// <remarks>
  321. /// Please don't delete me even if I appear currently unused!
  322. /// </remarks>
  323. /// <param name="rawXml"></param>
  324. /// <returns></returns>
  325. public static string GetFormattedXml(string rawXml)
  326. {
  327. XmlDocument xd = new XmlDocument();
  328. xd.LoadXml(rawXml);
  329. StringBuilder sb = new StringBuilder();
  330. StringWriter sw = new StringWriter(sb);
  331. XmlTextWriter xtw = new XmlTextWriter(sw);
  332. xtw.Formatting = Formatting.Indented;
  333. try
  334. {
  335. xd.WriteTo(xtw);
  336. }
  337. finally
  338. {
  339. xtw.Close();
  340. }
  341. return sb.ToString();
  342. }
  343. /// <summary>
  344. /// Is the platform Windows?
  345. /// </summary>
  346. /// <returns>true if so, false otherwise</returns>
  347. public static bool IsWindows()
  348. {
  349. PlatformID platformId = Environment.OSVersion.Platform;
  350. return (platformId == PlatformID.Win32NT
  351. || platformId == PlatformID.Win32S
  352. || platformId == PlatformID.Win32Windows
  353. || platformId == PlatformID.WinCE);
  354. }
  355. public static bool LoadArchSpecificWindowsDll(string libraryName)
  356. {
  357. // We do this so that OpenSimulator on Windows loads the correct native library depending on whether
  358. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  359. // will find it already loaded later on.
  360. //
  361. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  362. // controlled in config files.
  363. string nativeLibraryPath;
  364. if (Util.Is64BitProcess())
  365. nativeLibraryPath = "lib64/" + libraryName;
  366. else
  367. nativeLibraryPath = "lib32/" + libraryName;
  368. m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
  369. if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
  370. {
  371. m_log.ErrorFormat(
  372. "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
  373. return false;
  374. }
  375. else
  376. {
  377. return true;
  378. }
  379. }
  380. public static bool IsEnvironmentSupported(ref string reason)
  381. {
  382. // Must have .NET 2.0 (Generics / libsl)
  383. if (Environment.Version.Major < 2)
  384. {
  385. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  386. return false;
  387. }
  388. // Windows 95/98/ME are unsupported
  389. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  390. Environment.OSVersion.Platform != PlatformID.Win32NT)
  391. {
  392. reason = "Windows 95/98/ME will not run OpenSim";
  393. return false;
  394. }
  395. // Windows 2000 / Pre-SP2 XP
  396. if (Environment.OSVersion.Version.Major == 5 &&
  397. Environment.OSVersion.Version.Minor == 0)
  398. {
  399. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  400. return false;
  401. }
  402. return true;
  403. }
  404. public static int UnixTimeSinceEpoch()
  405. {
  406. return ToUnixTime(DateTime.UtcNow);
  407. }
  408. public static int ToUnixTime(DateTime stamp)
  409. {
  410. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  411. return (int) t.TotalSeconds;
  412. }
  413. public static DateTime ToDateTime(ulong seconds)
  414. {
  415. DateTime epoch = unixEpoch;
  416. return epoch.AddSeconds(seconds);
  417. }
  418. public static DateTime ToDateTime(int seconds)
  419. {
  420. DateTime epoch = unixEpoch;
  421. return epoch.AddSeconds(seconds);
  422. }
  423. /// <summary>
  424. /// Return an md5 hash of the given string
  425. /// </summary>
  426. /// <param name="data"></param>
  427. /// <returns></returns>
  428. public static string Md5Hash(string data)
  429. {
  430. byte[] dataMd5 = ComputeMD5Hash(data);
  431. StringBuilder sb = new StringBuilder();
  432. for (int i = 0; i < dataMd5.Length; i++)
  433. sb.AppendFormat("{0:x2}", dataMd5[i]);
  434. return sb.ToString();
  435. }
  436. private static byte[] ComputeMD5Hash(string data)
  437. {
  438. MD5 md5 = MD5.Create();
  439. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  440. }
  441. /// <summary>
  442. /// Return an SHA1 hash
  443. /// </summary>
  444. /// <param name="data"></param>
  445. /// <returns></returns>
  446. public static string SHA1Hash(string data)
  447. {
  448. return SHA1Hash(Encoding.Default.GetBytes(data));
  449. }
  450. /// <summary>
  451. /// Return an SHA1 hash
  452. /// </summary>
  453. /// <param name="data"></param>
  454. /// <returns></returns>
  455. public static string SHA1Hash(byte[] data)
  456. {
  457. byte[] hash = ComputeSHA1Hash(data);
  458. return BitConverter.ToString(hash).Replace("-", String.Empty);
  459. }
  460. private static byte[] ComputeSHA1Hash(byte[] src)
  461. {
  462. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  463. return SHA1.ComputeHash(src);
  464. }
  465. public static int fast_distance2d(int x, int y)
  466. {
  467. x = Math.Abs(x);
  468. y = Math.Abs(y);
  469. int min = Math.Min(x, y);
  470. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  471. }
  472. /// <summary>
  473. /// Determines whether a point is inside a bounding box.
  474. /// </summary>
  475. /// <param name='v'></param>
  476. /// <param name='min'></param>
  477. /// <param name='max'></param>
  478. /// <returns></returns>
  479. public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
  480. {
  481. return v.X >= min.X & v.Y >= min.Y && v.Z >= min.Z
  482. && v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
  483. }
  484. /// <summary>
  485. /// Are the co-ordinates of the new region visible from the old region?
  486. /// </summary>
  487. /// <param name="oldx">Old region x-coord</param>
  488. /// <param name="newx">New region x-coord</param>
  489. /// <param name="oldy">Old region y-coord</param>
  490. /// <param name="newy">New region y-coord</param>
  491. /// <returns></returns>
  492. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy)
  493. {
  494. int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize);
  495. int startX = (int)oldx - dd;
  496. int startY = (int)oldy - dd;
  497. int endX = (int)oldx + dd;
  498. int endY = (int)oldy + dd;
  499. return (newx < startX || endX < newx || newy < startY || endY < newy);
  500. }
  501. public static string FieldToString(byte[] bytes)
  502. {
  503. return FieldToString(bytes, String.Empty);
  504. }
  505. /// <summary>
  506. /// Convert a variable length field (byte array) to a string, with a
  507. /// field name prepended to each line of the output
  508. /// </summary>
  509. /// <remarks>If the byte array has unprintable characters in it, a
  510. /// hex dump will be put in the string instead</remarks>
  511. /// <param name="bytes">The byte array to convert to a string</param>
  512. /// <param name="fieldName">A field name to prepend to each line of output</param>
  513. /// <returns>An ASCII string or a string containing a hex dump, minus
  514. /// the null terminator</returns>
  515. public static string FieldToString(byte[] bytes, string fieldName)
  516. {
  517. // Check for a common case
  518. if (bytes.Length == 0) return String.Empty;
  519. StringBuilder output = new StringBuilder();
  520. bool printable = true;
  521. for (int i = 0; i < bytes.Length; ++i)
  522. {
  523. // Check if there are any unprintable characters in the array
  524. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  525. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  526. {
  527. printable = false;
  528. break;
  529. }
  530. }
  531. if (printable)
  532. {
  533. if (fieldName.Length > 0)
  534. {
  535. output.Append(fieldName);
  536. output.Append(": ");
  537. }
  538. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  539. }
  540. else
  541. {
  542. for (int i = 0; i < bytes.Length; i += 16)
  543. {
  544. if (i != 0)
  545. output.Append(Environment.NewLine);
  546. if (fieldName.Length > 0)
  547. {
  548. output.Append(fieldName);
  549. output.Append(": ");
  550. }
  551. for (int j = 0; j < 16; j++)
  552. {
  553. if ((i + j) < bytes.Length)
  554. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  555. else
  556. output.Append(" ");
  557. }
  558. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  559. {
  560. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  561. output.Append((char) bytes[i + j]);
  562. else
  563. output.Append(".");
  564. }
  565. }
  566. }
  567. return output.ToString();
  568. }
  569. /// <summary>
  570. /// Converts a URL to a IPAddress
  571. /// </summary>
  572. /// <param name="url">URL Standard Format</param>
  573. /// <returns>A resolved IP Address</returns>
  574. public static IPAddress GetHostFromURL(string url)
  575. {
  576. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  577. }
  578. /// <summary>
  579. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  580. /// </summary>
  581. /// <param name="dnsAddress">DNS Hostname</param>
  582. /// <returns>An IP address, or null</returns>
  583. public static IPAddress GetHostFromDNS(string dnsAddress)
  584. {
  585. // Is it already a valid IP? No need to look it up.
  586. IPAddress ipa;
  587. if (IPAddress.TryParse(dnsAddress, out ipa))
  588. return ipa;
  589. IPAddress[] hosts = null;
  590. // Not an IP, lookup required
  591. try
  592. {
  593. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  594. }
  595. catch (Exception e)
  596. {
  597. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  598. // Still going to throw the exception on for now, since this was what was happening in the first place
  599. throw e;
  600. }
  601. foreach (IPAddress host in hosts)
  602. {
  603. if (host.AddressFamily == AddressFamily.InterNetwork)
  604. {
  605. return host;
  606. }
  607. }
  608. if (hosts.Length > 0)
  609. return hosts[0];
  610. return null;
  611. }
  612. public static Uri GetURI(string protocol, string hostname, int port, string path)
  613. {
  614. return new UriBuilder(protocol, hostname, port, path).Uri;
  615. }
  616. /// <summary>
  617. /// Gets a list of all local system IP addresses
  618. /// </summary>
  619. /// <returns></returns>
  620. public static IPAddress[] GetLocalHosts()
  621. {
  622. return Dns.GetHostAddresses(Dns.GetHostName());
  623. }
  624. public static IPAddress GetLocalHost()
  625. {
  626. IPAddress[] iplist = GetLocalHosts();
  627. if (iplist.Length == 0) // No accessible external interfaces
  628. {
  629. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  630. IPAddress localhost = loopback[0];
  631. return localhost;
  632. }
  633. foreach (IPAddress host in iplist)
  634. {
  635. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  636. {
  637. return host;
  638. }
  639. }
  640. if (iplist.Length > 0)
  641. {
  642. foreach (IPAddress host in iplist)
  643. {
  644. if (host.AddressFamily == AddressFamily.InterNetwork)
  645. return host;
  646. }
  647. // Well all else failed...
  648. return iplist[0];
  649. }
  650. return null;
  651. }
  652. /// <summary>
  653. /// Removes all invalid path chars (OS dependent)
  654. /// </summary>
  655. /// <param name="path">path</param>
  656. /// <returns>safe path</returns>
  657. public static string safePath(string path)
  658. {
  659. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  660. }
  661. /// <summary>
  662. /// Removes all invalid filename chars (OS dependent)
  663. /// </summary>
  664. /// <param name="path">filename</param>
  665. /// <returns>safe filename</returns>
  666. public static string safeFileName(string filename)
  667. {
  668. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  669. ;
  670. }
  671. //
  672. // directory locations
  673. //
  674. public static string homeDir()
  675. {
  676. string temp;
  677. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  678. // temp = Path.Combine(personal,".OpenSim");
  679. temp = ".";
  680. return temp;
  681. }
  682. public static string assetsDir()
  683. {
  684. return Path.Combine(configDir(), "assets");
  685. }
  686. public static string inventoryDir()
  687. {
  688. return Path.Combine(configDir(), "inventory");
  689. }
  690. public static string configDir()
  691. {
  692. return ".";
  693. }
  694. public static string dataDir()
  695. {
  696. return ".";
  697. }
  698. public static string logDir()
  699. {
  700. return ".";
  701. }
  702. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  703. public static string GetUniqueFilename(string FileName)
  704. {
  705. int count = 0;
  706. string Name;
  707. if (File.Exists(FileName))
  708. {
  709. FileInfo f = new FileInfo(FileName);
  710. if (!String.IsNullOrEmpty(f.Extension))
  711. {
  712. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  713. }
  714. else
  715. {
  716. Name = f.FullName;
  717. }
  718. while (File.Exists(FileName))
  719. {
  720. count++;
  721. FileName = Name + count + f.Extension;
  722. }
  723. }
  724. return FileName;
  725. }
  726. // Nini (config) related Methods
  727. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  728. {
  729. if (!File.Exists(fileName))
  730. {
  731. //create new file
  732. }
  733. XmlConfigSource config = new XmlConfigSource(fileName);
  734. AddDataRowToConfig(config, row);
  735. config.Save();
  736. return config;
  737. }
  738. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  739. {
  740. config.Configs.Add((string) row[0]);
  741. for (int i = 0; i < row.Table.Columns.Count; i++)
  742. {
  743. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  744. }
  745. }
  746. public static float Clip(float x, float min, float max)
  747. {
  748. return Math.Min(Math.Max(x, min), max);
  749. }
  750. public static int Clip(int x, int min, int max)
  751. {
  752. return Math.Min(Math.Max(x, min), max);
  753. }
  754. public static Vector3 Clip(Vector3 vec, float min, float max)
  755. {
  756. return new Vector3(Clip(vec.X, min, max), Clip(vec.Y, min, max),
  757. Clip(vec.Z, min, max));
  758. }
  759. /// <summary>
  760. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  761. /// </summary>
  762. /// <param name="UUID"></param>
  763. /// <returns></returns>
  764. public static String ToRawUuidString(UUID UUID)
  765. {
  766. return UUID.Guid.ToString("n");
  767. }
  768. public static string CleanString(string input)
  769. {
  770. if (input.Length == 0)
  771. return input;
  772. int clip = input.Length;
  773. // Test for ++ string terminator
  774. int pos = input.IndexOf("\0");
  775. if (pos != -1 && pos < clip)
  776. clip = pos;
  777. // Test for CR
  778. pos = input.IndexOf("\r");
  779. if (pos != -1 && pos < clip)
  780. clip = pos;
  781. // Test for LF
  782. pos = input.IndexOf("\n");
  783. if (pos != -1 && pos < clip)
  784. clip = pos;
  785. // Truncate string before first end-of-line character found
  786. return input.Substring(0, clip);
  787. }
  788. /// <summary>
  789. /// returns the contents of /etc/issue on Unix Systems
  790. /// Use this for where it's absolutely necessary to implement platform specific stuff
  791. /// </summary>
  792. /// <returns></returns>
  793. public static string ReadEtcIssue()
  794. {
  795. try
  796. {
  797. StreamReader sr = new StreamReader("/etc/issue.net");
  798. string issue = sr.ReadToEnd();
  799. sr.Close();
  800. return issue;
  801. }
  802. catch (Exception)
  803. {
  804. return "";
  805. }
  806. }
  807. public static void SerializeToFile(string filename, Object obj)
  808. {
  809. IFormatter formatter = new BinaryFormatter();
  810. Stream stream = null;
  811. try
  812. {
  813. stream = new FileStream(
  814. filename, FileMode.Create,
  815. FileAccess.Write, FileShare.None);
  816. formatter.Serialize(stream, obj);
  817. }
  818. catch (Exception e)
  819. {
  820. m_log.Error(e.ToString());
  821. }
  822. finally
  823. {
  824. if (stream != null)
  825. {
  826. stream.Close();
  827. }
  828. }
  829. }
  830. public static Object DeserializeFromFile(string filename)
  831. {
  832. IFormatter formatter = new BinaryFormatter();
  833. Stream stream = null;
  834. Object ret = null;
  835. try
  836. {
  837. stream = new FileStream(
  838. filename, FileMode.Open,
  839. FileAccess.Read, FileShare.None);
  840. ret = formatter.Deserialize(stream);
  841. }
  842. catch (Exception e)
  843. {
  844. m_log.Error(e.ToString());
  845. }
  846. finally
  847. {
  848. if (stream != null)
  849. {
  850. stream.Close();
  851. }
  852. }
  853. return ret;
  854. }
  855. public static string Compress(string text)
  856. {
  857. byte[] buffer = Util.UTF8.GetBytes(text);
  858. MemoryStream memory = new MemoryStream();
  859. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  860. {
  861. compressor.Write(buffer, 0, buffer.Length);
  862. }
  863. memory.Position = 0;
  864. byte[] compressed = new byte[memory.Length];
  865. memory.Read(compressed, 0, compressed.Length);
  866. byte[] compressedBuffer = new byte[compressed.Length + 4];
  867. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  868. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  869. return Convert.ToBase64String(compressedBuffer);
  870. }
  871. public static string Decompress(string compressedText)
  872. {
  873. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  874. using (MemoryStream memory = new MemoryStream())
  875. {
  876. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  877. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  878. byte[] buffer = new byte[msgLength];
  879. memory.Position = 0;
  880. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  881. {
  882. decompressor.Read(buffer, 0, buffer.Length);
  883. }
  884. return Util.UTF8.GetString(buffer);
  885. }
  886. }
  887. /// <summary>
  888. /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
  889. /// </summary>
  890. /// <param name='inputStream'>
  891. /// Input stream. Must be seekable.
  892. /// </param>
  893. /// <exception cref='ArgumentException'>
  894. /// Thrown if the input stream is not seekable.
  895. /// </exception>
  896. public static Stream Copy(Stream inputStream)
  897. {
  898. if (!inputStream.CanSeek)
  899. throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
  900. const int readSize = 256;
  901. byte[] buffer = new byte[readSize];
  902. MemoryStream ms = new MemoryStream();
  903. int count = inputStream.Read(buffer, 0, readSize);
  904. while (count > 0)
  905. {
  906. ms.Write(buffer, 0, count);
  907. count = inputStream.Read(buffer, 0, readSize);
  908. }
  909. ms.Position = 0;
  910. inputStream.Position = 0;
  911. return ms;
  912. }
  913. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  914. {
  915. return SendXmlRpcCommand(url, methodName, args);
  916. }
  917. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  918. {
  919. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  920. return client.Send(url, 6000);
  921. }
  922. /// <summary>
  923. /// Returns an error message that the user could not be found in the database
  924. /// </summary>
  925. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  926. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  927. {
  928. XmlRpcResponse response = new XmlRpcResponse();
  929. Hashtable responseData = new Hashtable();
  930. responseData["error_type"] = "unknown_user";
  931. responseData["error_desc"] = "The user requested is not in the database";
  932. response.Value = responseData;
  933. return response;
  934. }
  935. /// <summary>
  936. /// Converts a byte array in big endian order into an ulong.
  937. /// </summary>
  938. /// <param name="bytes">
  939. /// The array of bytes
  940. /// </param>
  941. /// <returns>
  942. /// The extracted ulong
  943. /// </returns>
  944. public static ulong BytesToUInt64Big(byte[] bytes)
  945. {
  946. if (bytes.Length < 8) return 0;
  947. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  948. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  949. }
  950. // used for RemoteParcelRequest (for "About Landmark")
  951. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  952. {
  953. byte[] bytes =
  954. {
  955. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  956. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  957. (byte)x, (byte)(x >> 8), 0, 0,
  958. (byte)y, (byte)(y >> 8), 0, 0 };
  959. return new UUID(bytes, 0);
  960. }
  961. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  962. {
  963. byte[] bytes =
  964. {
  965. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  966. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  967. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  968. (byte)y, (byte)(y >> 8), 0, 0 };
  969. return new UUID(bytes, 0);
  970. }
  971. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  972. {
  973. byte[] bytes = parcelID.GetBytes();
  974. regionHandle = Utils.BytesToUInt64(bytes);
  975. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  976. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  977. }
  978. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  979. {
  980. byte[] bytes = parcelID.GetBytes();
  981. regionHandle = Utils.BytesToUInt64(bytes);
  982. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  983. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  984. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  985. }
  986. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  987. {
  988. ulong regionHandle;
  989. uint rx, ry;
  990. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  991. Utils.LongToUInts(regionHandle, out rx, out ry);
  992. x += rx;
  993. y += ry;
  994. }
  995. /// <summary>
  996. /// Get operating system information if available. Returns only the first 45 characters of information
  997. /// </summary>
  998. /// <returns>
  999. /// Operating system information. Returns an empty string if none was available.
  1000. /// </returns>
  1001. public static string GetOperatingSystemInformation()
  1002. {
  1003. string os = String.Empty;
  1004. if (Environment.OSVersion.Platform != PlatformID.Unix)
  1005. {
  1006. os = Environment.OSVersion.ToString();
  1007. }
  1008. else
  1009. {
  1010. os = ReadEtcIssue();
  1011. }
  1012. if (os.Length > 45)
  1013. {
  1014. os = os.Substring(0, 45);
  1015. }
  1016. return os;
  1017. }
  1018. public static string GetRuntimeInformation()
  1019. {
  1020. string ru = String.Empty;
  1021. if (Environment.OSVersion.Platform == PlatformID.Unix)
  1022. ru = "Unix/Mono";
  1023. else
  1024. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  1025. ru = "OSX/Mono";
  1026. else
  1027. {
  1028. if (Type.GetType("Mono.Runtime") != null)
  1029. ru = "Win/Mono";
  1030. else
  1031. ru = "Win/.NET";
  1032. }
  1033. return ru;
  1034. }
  1035. /// <summary>
  1036. /// Is the given string a UUID?
  1037. /// </summary>
  1038. /// <param name="s"></param>
  1039. /// <returns></returns>
  1040. public static bool isUUID(string s)
  1041. {
  1042. return UUIDPattern.IsMatch(s);
  1043. }
  1044. public static string GetDisplayConnectionString(string connectionString)
  1045. {
  1046. int passPosition = 0;
  1047. int passEndPosition = 0;
  1048. string displayConnectionString = null;
  1049. // hide the password in the connection string
  1050. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1051. passPosition = connectionString.IndexOf("=", passPosition);
  1052. if (passPosition < connectionString.Length)
  1053. passPosition += 1;
  1054. passEndPosition = connectionString.IndexOf(";", passPosition);
  1055. displayConnectionString = connectionString.Substring(0, passPosition);
  1056. displayConnectionString += "***";
  1057. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1058. return displayConnectionString;
  1059. }
  1060. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1061. {
  1062. Type settingsType = settingsClass.GetType();
  1063. FieldInfo[] fieldInfos = settingsType.GetFields();
  1064. foreach (FieldInfo fieldInfo in fieldInfos)
  1065. {
  1066. if (!fieldInfo.IsStatic)
  1067. {
  1068. if (fieldInfo.FieldType == typeof(System.String))
  1069. {
  1070. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1071. }
  1072. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1073. {
  1074. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1075. }
  1076. else if (fieldInfo.FieldType == typeof(System.Int32))
  1077. {
  1078. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1079. }
  1080. else if (fieldInfo.FieldType == typeof(System.Single))
  1081. {
  1082. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1083. }
  1084. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1085. {
  1086. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1087. }
  1088. }
  1089. }
  1090. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1091. foreach (PropertyInfo propInfo in propertyInfos)
  1092. {
  1093. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1094. {
  1095. if (propInfo.PropertyType == typeof(System.String))
  1096. {
  1097. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1098. }
  1099. else if (propInfo.PropertyType == typeof(System.Boolean))
  1100. {
  1101. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1102. }
  1103. else if (propInfo.PropertyType == typeof(System.Int32))
  1104. {
  1105. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1106. }
  1107. else if (propInfo.PropertyType == typeof(System.Single))
  1108. {
  1109. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1110. }
  1111. if (propInfo.PropertyType == typeof(System.UInt32))
  1112. {
  1113. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1114. }
  1115. }
  1116. }
  1117. return settingsClass;
  1118. }
  1119. public static string Base64ToString(string str)
  1120. {
  1121. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  1122. byte[] todecode_byte = Convert.FromBase64String(str);
  1123. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1124. char[] decoded_char = new char[charCount];
  1125. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1126. string result = new String(decoded_char);
  1127. return result;
  1128. }
  1129. public static Guid GetHashGuid(string data, string salt)
  1130. {
  1131. byte[] hash = ComputeMD5Hash(data + salt);
  1132. //string s = BitConverter.ToString(hash);
  1133. Guid guid = new Guid(hash);
  1134. return guid;
  1135. }
  1136. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1137. {
  1138. byte retVal = 0;
  1139. switch (maturity)
  1140. {
  1141. case 0: //PG
  1142. retVal = 13;
  1143. break;
  1144. case 1: //Mature
  1145. retVal = 21;
  1146. break;
  1147. case 2: // Adult
  1148. retVal = 42;
  1149. break;
  1150. }
  1151. return retVal;
  1152. }
  1153. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1154. {
  1155. if (maturity <= 13)
  1156. return 0;
  1157. else if (maturity <= 21)
  1158. return 1;
  1159. else
  1160. return 2;
  1161. }
  1162. /// <summary>
  1163. /// Produces an OSDMap from its string representation on a stream
  1164. /// </summary>
  1165. /// <param name="data">The stream</param>
  1166. /// <param name="length">The size of the data on the stream</param>
  1167. /// <returns>The OSDMap or an exception</returns>
  1168. public static OSDMap GetOSDMap(Stream stream, int length)
  1169. {
  1170. byte[] data = new byte[length];
  1171. stream.Read(data, 0, length);
  1172. string strdata = Util.UTF8.GetString(data);
  1173. OSDMap args = null;
  1174. OSD buffer;
  1175. buffer = OSDParser.DeserializeJson(strdata);
  1176. if (buffer.Type == OSDType.Map)
  1177. {
  1178. args = (OSDMap)buffer;
  1179. return args;
  1180. }
  1181. return null;
  1182. }
  1183. public static OSDMap GetOSDMap(string data)
  1184. {
  1185. OSDMap args = null;
  1186. try
  1187. {
  1188. OSD buffer;
  1189. // We should pay attention to the content-type, but let's assume we know it's Json
  1190. buffer = OSDParser.DeserializeJson(data);
  1191. if (buffer.Type == OSDType.Map)
  1192. {
  1193. args = (OSDMap)buffer;
  1194. return args;
  1195. }
  1196. else
  1197. {
  1198. // uh?
  1199. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1200. return null;
  1201. }
  1202. }
  1203. catch (Exception ex)
  1204. {
  1205. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1206. return null;
  1207. }
  1208. }
  1209. public static string[] Glob(string path)
  1210. {
  1211. string vol=String.Empty;
  1212. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1213. {
  1214. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1215. if (vcomps.Length > 1)
  1216. {
  1217. path = vcomps[1];
  1218. vol = vcomps[0];
  1219. }
  1220. }
  1221. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1222. // Glob
  1223. path = vol;
  1224. if (vol != String.Empty)
  1225. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1226. else
  1227. path = new String(new char[] {Path.DirectorySeparatorChar});
  1228. List<string> paths = new List<string>();
  1229. List<string> found = new List<string>();
  1230. paths.Add(path);
  1231. int compIndex = -1;
  1232. foreach (string c in comps)
  1233. {
  1234. compIndex++;
  1235. List<string> addpaths = new List<string>();
  1236. foreach (string p in paths)
  1237. {
  1238. string[] dirs = Directory.GetDirectories(p, c);
  1239. if (dirs.Length != 0)
  1240. {
  1241. foreach (string dir in dirs)
  1242. addpaths.Add(Path.Combine(path, dir));
  1243. }
  1244. // Only add files if that is the last path component
  1245. if (compIndex == comps.Length - 1)
  1246. {
  1247. string[] files = Directory.GetFiles(p, c);
  1248. foreach (string f in files)
  1249. found.Add(f);
  1250. }
  1251. }
  1252. paths = addpaths;
  1253. }
  1254. return found.ToArray();
  1255. }
  1256. public static string ServerURI(string uri)
  1257. {
  1258. if (uri == string.Empty)
  1259. return string.Empty;
  1260. // Get rid of eventual slashes at the end
  1261. uri = uri.TrimEnd('/');
  1262. IPAddress ipaddr1 = null;
  1263. string port1 = "";
  1264. try
  1265. {
  1266. ipaddr1 = Util.GetHostFromURL(uri);
  1267. }
  1268. catch { }
  1269. try
  1270. {
  1271. port1 = uri.Split(new char[] { ':' })[2];
  1272. }
  1273. catch { }
  1274. // We tried our best to convert the domain names to IP addresses
  1275. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1276. }
  1277. /// <summary>
  1278. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1279. /// </summary>
  1280. /// <param name="str">
  1281. /// If null or empty, then an bytes[0] is returned.
  1282. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1283. /// </param>
  1284. /// <param name="args">
  1285. /// Arguments to substitute into the string via the {} mechanism.
  1286. /// </param>
  1287. /// <returns></returns>
  1288. public static byte[] StringToBytes256(string str, params object[] args)
  1289. {
  1290. return StringToBytes256(string.Format(str, args));
  1291. }
  1292. /// <summary>
  1293. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1294. /// </summary>
  1295. /// <param name="str">
  1296. /// If null or empty, then an bytes[0] is returned.
  1297. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1298. /// </param>
  1299. /// <returns></returns>
  1300. public static byte[] StringToBytes256(string str)
  1301. {
  1302. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1303. if (str.Length > 254) str = str.Remove(254);
  1304. if (!str.EndsWith("\0")) { str += "\0"; }
  1305. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1306. // might have gotten an oversized array even after the string trim
  1307. byte[] data = UTF8.GetBytes(str);
  1308. if (data.Length > 256)
  1309. {
  1310. Array.Resize<byte>(ref data, 256);
  1311. data[255] = 0;
  1312. }
  1313. return data;
  1314. }
  1315. /// <summary>
  1316. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1317. /// </summary>
  1318. /// <param name="str">
  1319. /// If null or empty, then an bytes[0] is returned.
  1320. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1321. /// </param>
  1322. /// <param name="args">
  1323. /// Arguments to substitute into the string via the {} mechanism.
  1324. /// </param>
  1325. /// <returns></returns>
  1326. public static byte[] StringToBytes1024(string str, params object[] args)
  1327. {
  1328. return StringToBytes1024(string.Format(str, args));
  1329. }
  1330. /// <summary>
  1331. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1332. /// </summary>
  1333. /// <param name="str">
  1334. /// If null or empty, then an bytes[0] is returned.
  1335. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1336. /// </param>
  1337. /// <returns></returns>
  1338. public static byte[] StringToBytes1024(string str)
  1339. {
  1340. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1341. if (str.Length > 1023) str = str.Remove(1023);
  1342. if (!str.EndsWith("\0")) { str += "\0"; }
  1343. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1344. // might have gotten an oversized array even after the string trim
  1345. byte[] data = UTF8.GetBytes(str);
  1346. if (data.Length > 1024)
  1347. {
  1348. Array.Resize<byte>(ref data, 1024);
  1349. data[1023] = 0;
  1350. }
  1351. return data;
  1352. }
  1353. /// <summary>
  1354. /// Used to trigger an early library load on Windows systems.
  1355. /// </summary>
  1356. /// <remarks>
  1357. /// Required to get 32-bit and 64-bit processes to automatically use the
  1358. /// appropriate native library.
  1359. /// </remarks>
  1360. /// <param name="dllToLoad"></param>
  1361. /// <returns></returns>
  1362. [DllImport("kernel32.dll")]
  1363. public static extern IntPtr LoadLibrary(string dllToLoad);
  1364. /// <summary>
  1365. /// Determine whether the current process is 64 bit
  1366. /// </summary>
  1367. /// <returns>true if so, false if not</returns>
  1368. public static bool Is64BitProcess()
  1369. {
  1370. return IntPtr.Size == 8;
  1371. }
  1372. #region FireAndForget Threading Pattern
  1373. /// <summary>
  1374. /// Created to work around a limitation in Mono with nested delegates
  1375. /// </summary>
  1376. private sealed class FireAndForgetWrapper
  1377. {
  1378. private static volatile FireAndForgetWrapper instance;
  1379. private static object syncRoot = new Object();
  1380. public static FireAndForgetWrapper Instance {
  1381. get {
  1382. if (instance == null)
  1383. {
  1384. lock (syncRoot)
  1385. {
  1386. if (instance == null)
  1387. {
  1388. instance = new FireAndForgetWrapper();
  1389. }
  1390. }
  1391. }
  1392. return instance;
  1393. }
  1394. }
  1395. public void FireAndForget(System.Threading.WaitCallback callback)
  1396. {
  1397. callback.BeginInvoke(null, EndFireAndForget, callback);
  1398. }
  1399. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1400. {
  1401. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1402. }
  1403. private static void EndFireAndForget(IAsyncResult ar)
  1404. {
  1405. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1406. try { callback.EndInvoke(ar); }
  1407. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1408. ar.AsyncWaitHandle.Close();
  1409. }
  1410. }
  1411. public static void FireAndForget(System.Threading.WaitCallback callback)
  1412. {
  1413. FireAndForget(callback, null);
  1414. }
  1415. public static void InitThreadPool(int maxThreads)
  1416. {
  1417. if (maxThreads < 2)
  1418. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1419. if (m_ThreadPool != null)
  1420. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1421. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1422. }
  1423. public static int FireAndForgetCount()
  1424. {
  1425. const int MAX_SYSTEM_THREADS = 200;
  1426. switch (FireAndForgetMethod)
  1427. {
  1428. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1429. case FireAndForgetMethod.QueueUserWorkItem:
  1430. case FireAndForgetMethod.BeginInvoke:
  1431. int workerThreads, iocpThreads;
  1432. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1433. return workerThreads;
  1434. case FireAndForgetMethod.SmartThreadPool:
  1435. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1436. case FireAndForgetMethod.Thread:
  1437. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1438. default:
  1439. throw new NotImplementedException();
  1440. }
  1441. }
  1442. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1443. {
  1444. WaitCallback realCallback;
  1445. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  1446. {
  1447. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  1448. realCallback = o => { Culture.SetCurrentCulture(); callback(o); };
  1449. }
  1450. else
  1451. {
  1452. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  1453. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  1454. // for decimals places but is read by a culture that treats commas as number seperators.
  1455. realCallback = o =>
  1456. {
  1457. Culture.SetCurrentCulture();
  1458. try
  1459. {
  1460. callback(o);
  1461. }
  1462. catch (Exception e)
  1463. {
  1464. m_log.ErrorFormat(
  1465. "[UTIL]: Continuing after async_call_method thread terminated with exception {0}{1}",
  1466. e.Message, e.StackTrace);
  1467. }
  1468. };
  1469. }
  1470. switch (FireAndForgetMethod)
  1471. {
  1472. case FireAndForgetMethod.RegressionTest:
  1473. case FireAndForgetMethod.None:
  1474. realCallback.Invoke(obj);
  1475. break;
  1476. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1477. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  1478. break;
  1479. case FireAndForgetMethod.QueueUserWorkItem:
  1480. ThreadPool.QueueUserWorkItem(realCallback, obj);
  1481. break;
  1482. case FireAndForgetMethod.BeginInvoke:
  1483. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  1484. wrapper.FireAndForget(realCallback, obj);
  1485. break;
  1486. case FireAndForgetMethod.SmartThreadPool:
  1487. if (m_ThreadPool == null)
  1488. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1489. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { realCallback, obj });
  1490. break;
  1491. case FireAndForgetMethod.Thread:
  1492. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  1493. thread.Start(obj);
  1494. break;
  1495. default:
  1496. throw new NotImplementedException();
  1497. }
  1498. }
  1499. /// <summary>
  1500. /// Get a thread pool report.
  1501. /// </summary>
  1502. /// <returns></returns>
  1503. public static string GetThreadPoolReport()
  1504. {
  1505. string threadPoolUsed = null;
  1506. int maxThreads = 0;
  1507. int minThreads = 0;
  1508. int allocatedThreads = 0;
  1509. int inUseThreads = 0;
  1510. int waitingCallbacks = 0;
  1511. int completionPortThreads = 0;
  1512. StringBuilder sb = new StringBuilder();
  1513. if (FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  1514. {
  1515. threadPoolUsed = "SmartThreadPool";
  1516. maxThreads = m_ThreadPool.MaxThreads;
  1517. minThreads = m_ThreadPool.MinThreads;
  1518. inUseThreads = m_ThreadPool.InUseThreads;
  1519. allocatedThreads = m_ThreadPool.ActiveThreads;
  1520. waitingCallbacks = m_ThreadPool.WaitingCallbacks;
  1521. }
  1522. else if (
  1523. FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem
  1524. || FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  1525. {
  1526. threadPoolUsed = "BuiltInThreadPool";
  1527. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  1528. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  1529. int availableThreads;
  1530. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  1531. inUseThreads = maxThreads - availableThreads;
  1532. allocatedThreads = -1;
  1533. waitingCallbacks = -1;
  1534. }
  1535. if (threadPoolUsed != null)
  1536. {
  1537. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  1538. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  1539. sb.AppendFormat("Min threads : {0}\n", minThreads);
  1540. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  1541. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  1542. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  1543. }
  1544. else
  1545. {
  1546. sb.AppendFormat("Thread pool not used\n");
  1547. }
  1548. return sb.ToString();
  1549. }
  1550. private static object SmartThreadPoolCallback(object o)
  1551. {
  1552. object[] array = (object[])o;
  1553. WaitCallback callback = (WaitCallback)array[0];
  1554. object obj = array[1];
  1555. callback(obj);
  1556. return null;
  1557. }
  1558. #endregion FireAndForget Threading Pattern
  1559. /// <summary>
  1560. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1561. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1562. /// for the callers.
  1563. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1564. /// </summary>
  1565. /// <returns></returns>
  1566. public static Int32 EnvironmentTickCount()
  1567. {
  1568. return Environment.TickCount & EnvironmentTickCountMask;
  1569. }
  1570. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1571. /// <summary>
  1572. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1573. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1574. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1575. /// </summary>
  1576. /// <param name="newValue"></param>
  1577. /// <param name="prevValue"></param>
  1578. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1579. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  1580. {
  1581. Int32 diff = newValue - prevValue;
  1582. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1583. }
  1584. /// <summary>
  1585. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1586. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1587. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1588. /// </summary>
  1589. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1590. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1591. {
  1592. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  1593. }
  1594. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1595. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1596. // A positive return value indicates A occured later than B
  1597. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1598. {
  1599. // A, B and TC are all between 0 and 0x3fffffff
  1600. int tc = EnvironmentTickCount();
  1601. if (tc - tcA >= 0)
  1602. tcA += EnvironmentTickCountMask + 1;
  1603. if (tc - tcB >= 0)
  1604. tcB += EnvironmentTickCountMask + 1;
  1605. return tcA - tcB;
  1606. }
  1607. /// <summary>
  1608. /// Prints the call stack at any given point. Useful for debugging.
  1609. /// </summary>
  1610. public static void PrintCallStack()
  1611. {
  1612. StackTrace stackTrace = new StackTrace(true); // get call stack
  1613. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1614. // write call stack method names
  1615. foreach (StackFrame stackFrame in stackFrames)
  1616. {
  1617. MethodBase mb = stackFrame.GetMethod();
  1618. m_log.DebugFormat("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  1619. }
  1620. }
  1621. /// <summary>
  1622. /// Gets the client IP address
  1623. /// </summary>
  1624. /// <param name="xff"></param>
  1625. /// <returns></returns>
  1626. public static IPEndPoint GetClientIPFromXFF(string xff)
  1627. {
  1628. if (xff == string.Empty)
  1629. return null;
  1630. string[] parts = xff.Split(new char[] { ',' });
  1631. if (parts.Length > 0)
  1632. {
  1633. try
  1634. {
  1635. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1636. }
  1637. catch (Exception e)
  1638. {
  1639. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1640. }
  1641. }
  1642. return null;
  1643. }
  1644. public static string GetCallerIP(Hashtable req)
  1645. {
  1646. if (req.ContainsKey("headers"))
  1647. {
  1648. try
  1649. {
  1650. Hashtable headers = (Hashtable)req["headers"];
  1651. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1652. return headers["remote_addr"].ToString();
  1653. }
  1654. catch (Exception e)
  1655. {
  1656. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1657. }
  1658. }
  1659. return string.Empty;
  1660. }
  1661. #region Xml Serialization Utilities
  1662. public static bool ReadBoolean(XmlTextReader reader)
  1663. {
  1664. reader.ReadStartElement();
  1665. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1666. reader.ReadEndElement();
  1667. return result;
  1668. }
  1669. public static UUID ReadUUID(XmlTextReader reader, string name)
  1670. {
  1671. UUID id;
  1672. string idStr;
  1673. reader.ReadStartElement(name);
  1674. if (reader.Name == "Guid")
  1675. idStr = reader.ReadElementString("Guid");
  1676. else if (reader.Name == "UUID")
  1677. idStr = reader.ReadElementString("UUID");
  1678. else // no leading tag
  1679. idStr = reader.ReadContentAsString();
  1680. UUID.TryParse(idStr, out id);
  1681. reader.ReadEndElement();
  1682. return id;
  1683. }
  1684. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1685. {
  1686. Vector3 vec;
  1687. reader.ReadStartElement(name);
  1688. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1689. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1690. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1691. reader.ReadEndElement();
  1692. return vec;
  1693. }
  1694. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1695. {
  1696. Quaternion quat = new Quaternion();
  1697. reader.ReadStartElement(name);
  1698. while (reader.NodeType != XmlNodeType.EndElement)
  1699. {
  1700. switch (reader.Name.ToLower())
  1701. {
  1702. case "x":
  1703. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1704. break;
  1705. case "y":
  1706. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1707. break;
  1708. case "z":
  1709. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1710. break;
  1711. case "w":
  1712. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1713. break;
  1714. }
  1715. }
  1716. reader.ReadEndElement();
  1717. return quat;
  1718. }
  1719. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1720. {
  1721. string value = reader.ReadElementContentAsString(name, String.Empty);
  1722. // !!!!! to deal with flags without commas
  1723. if (value.Contains(" ") && !value.Contains(","))
  1724. value = value.Replace(" ", ", ");
  1725. return (T)Enum.Parse(typeof(T), value); ;
  1726. }
  1727. #endregion
  1728. #region Universal User Identifiers
  1729. /// <summary>
  1730. /// </summary>
  1731. /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
  1732. /// <param name="uuid">the uuid part</param>
  1733. /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
  1734. /// <param name="firstname">the first name part (e.g. Test)</param>
  1735. /// <param name="lastname">the last name part (e.g User)</param>
  1736. /// <param name="secret">the secret part</param>
  1737. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1738. {
  1739. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1740. string[] parts = value.Split(';');
  1741. if (parts.Length >= 1)
  1742. if (!UUID.TryParse(parts[0], out uuid))
  1743. return false;
  1744. if (parts.Length >= 2)
  1745. url = parts[1];
  1746. if (parts.Length >= 3)
  1747. {
  1748. string[] name = parts[2].Split();
  1749. if (name.Length == 2)
  1750. {
  1751. firstname = name[0];
  1752. lastname = name[1];
  1753. }
  1754. }
  1755. if (parts.Length >= 4)
  1756. secret = parts[3];
  1757. return true;
  1758. }
  1759. /// <summary>
  1760. /// Produces a universal (HG) system-facing identifier given the information
  1761. /// </summary>
  1762. /// <param name="acircuit"></param>
  1763. /// <returns>uuid[;homeURI[;first last]]</returns>
  1764. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1765. {
  1766. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1767. return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
  1768. else
  1769. return acircuit.AgentID.ToString();
  1770. }
  1771. /// <summary>
  1772. /// Produces a universal (HG) system-facing identifier given the information
  1773. /// </summary>
  1774. /// <param name="id">UUID of the user</param>
  1775. /// <param name="firstName">first name (e.g Test)</param>
  1776. /// <param name="lastName">last name (e.g. User)</param>
  1777. /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
  1778. /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
  1779. public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
  1780. {
  1781. string agentsURI = homeURI;
  1782. if (!agentsURI.EndsWith("/"))
  1783. agentsURI += "/";
  1784. // This is ugly, but there's no other way, given that the name is changed
  1785. // in the agent circuit data for foreigners
  1786. if (lastName.Contains("@"))
  1787. {
  1788. string[] parts = firstName.Split(new char[] { '.' });
  1789. if (parts.Length == 2)
  1790. return id.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1791. }
  1792. return id.ToString() + ";" + agentsURI + ";" + firstName + " " + lastName;
  1793. }
  1794. /// <summary>
  1795. /// Produces a universal (HG) user-facing name given the information
  1796. /// </summary>
  1797. /// <param name="firstName"></param>
  1798. /// <param name="lastName"></param>
  1799. /// <param name="homeURI"></param>
  1800. /// <returns>string of the form first.last @foo.com or first last</returns>
  1801. public static string UniversalName(String firstName, String lastName, String homeURI)
  1802. {
  1803. Uri uri = null;
  1804. try
  1805. {
  1806. uri = new Uri(homeURI);
  1807. }
  1808. catch (UriFormatException)
  1809. {
  1810. return firstName + " " + lastName;
  1811. }
  1812. return firstName + "." + lastName + " " + "@" + uri.Authority;
  1813. }
  1814. #endregion
  1815. }
  1816. }