Util.cs 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  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. /// Are the co-ordinates of the new region visible from the old region?
  474. /// </summary>
  475. /// <param name="oldx">Old region x-coord</param>
  476. /// <param name="newx">New region x-coord</param>
  477. /// <param name="oldy">Old region y-coord</param>
  478. /// <param name="newy">New region y-coord</param>
  479. /// <returns></returns>
  480. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy)
  481. {
  482. int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize);
  483. int startX = (int)oldx - dd;
  484. int startY = (int)oldy - dd;
  485. int endX = (int)oldx + dd;
  486. int endY = (int)oldy + dd;
  487. return (newx < startX || endX < newx || newy < startY || endY < newy);
  488. }
  489. public static string FieldToString(byte[] bytes)
  490. {
  491. return FieldToString(bytes, String.Empty);
  492. }
  493. /// <summary>
  494. /// Convert a variable length field (byte array) to a string, with a
  495. /// field name prepended to each line of the output
  496. /// </summary>
  497. /// <remarks>If the byte array has unprintable characters in it, a
  498. /// hex dump will be put in the string instead</remarks>
  499. /// <param name="bytes">The byte array to convert to a string</param>
  500. /// <param name="fieldName">A field name to prepend to each line of output</param>
  501. /// <returns>An ASCII string or a string containing a hex dump, minus
  502. /// the null terminator</returns>
  503. public static string FieldToString(byte[] bytes, string fieldName)
  504. {
  505. // Check for a common case
  506. if (bytes.Length == 0) return String.Empty;
  507. StringBuilder output = new StringBuilder();
  508. bool printable = true;
  509. for (int i = 0; i < bytes.Length; ++i)
  510. {
  511. // Check if there are any unprintable characters in the array
  512. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  513. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  514. {
  515. printable = false;
  516. break;
  517. }
  518. }
  519. if (printable)
  520. {
  521. if (fieldName.Length > 0)
  522. {
  523. output.Append(fieldName);
  524. output.Append(": ");
  525. }
  526. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  527. }
  528. else
  529. {
  530. for (int i = 0; i < bytes.Length; i += 16)
  531. {
  532. if (i != 0)
  533. output.Append(Environment.NewLine);
  534. if (fieldName.Length > 0)
  535. {
  536. output.Append(fieldName);
  537. output.Append(": ");
  538. }
  539. for (int j = 0; j < 16; j++)
  540. {
  541. if ((i + j) < bytes.Length)
  542. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  543. else
  544. output.Append(" ");
  545. }
  546. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  547. {
  548. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  549. output.Append((char) bytes[i + j]);
  550. else
  551. output.Append(".");
  552. }
  553. }
  554. }
  555. return output.ToString();
  556. }
  557. /// <summary>
  558. /// Converts a URL to a IPAddress
  559. /// </summary>
  560. /// <param name="url">URL Standard Format</param>
  561. /// <returns>A resolved IP Address</returns>
  562. public static IPAddress GetHostFromURL(string url)
  563. {
  564. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  565. }
  566. /// <summary>
  567. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  568. /// </summary>
  569. /// <param name="dnsAddress">DNS Hostname</param>
  570. /// <returns>An IP address, or null</returns>
  571. public static IPAddress GetHostFromDNS(string dnsAddress)
  572. {
  573. // Is it already a valid IP? No need to look it up.
  574. IPAddress ipa;
  575. if (IPAddress.TryParse(dnsAddress, out ipa))
  576. return ipa;
  577. IPAddress[] hosts = null;
  578. // Not an IP, lookup required
  579. try
  580. {
  581. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  582. }
  583. catch (Exception e)
  584. {
  585. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  586. // Still going to throw the exception on for now, since this was what was happening in the first place
  587. throw e;
  588. }
  589. foreach (IPAddress host in hosts)
  590. {
  591. if (host.AddressFamily == AddressFamily.InterNetwork)
  592. {
  593. return host;
  594. }
  595. }
  596. if (hosts.Length > 0)
  597. return hosts[0];
  598. return null;
  599. }
  600. public static Uri GetURI(string protocol, string hostname, int port, string path)
  601. {
  602. return new UriBuilder(protocol, hostname, port, path).Uri;
  603. }
  604. /// <summary>
  605. /// Gets a list of all local system IP addresses
  606. /// </summary>
  607. /// <returns></returns>
  608. public static IPAddress[] GetLocalHosts()
  609. {
  610. return Dns.GetHostAddresses(Dns.GetHostName());
  611. }
  612. public static IPAddress GetLocalHost()
  613. {
  614. IPAddress[] iplist = GetLocalHosts();
  615. if (iplist.Length == 0) // No accessible external interfaces
  616. {
  617. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  618. IPAddress localhost = loopback[0];
  619. return localhost;
  620. }
  621. foreach (IPAddress host in iplist)
  622. {
  623. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  624. {
  625. return host;
  626. }
  627. }
  628. if (iplist.Length > 0)
  629. {
  630. foreach (IPAddress host in iplist)
  631. {
  632. if (host.AddressFamily == AddressFamily.InterNetwork)
  633. return host;
  634. }
  635. // Well all else failed...
  636. return iplist[0];
  637. }
  638. return null;
  639. }
  640. /// <summary>
  641. /// Removes all invalid path chars (OS dependent)
  642. /// </summary>
  643. /// <param name="path">path</param>
  644. /// <returns>safe path</returns>
  645. public static string safePath(string path)
  646. {
  647. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  648. }
  649. /// <summary>
  650. /// Removes all invalid filename chars (OS dependent)
  651. /// </summary>
  652. /// <param name="path">filename</param>
  653. /// <returns>safe filename</returns>
  654. public static string safeFileName(string filename)
  655. {
  656. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  657. ;
  658. }
  659. //
  660. // directory locations
  661. //
  662. public static string homeDir()
  663. {
  664. string temp;
  665. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  666. // temp = Path.Combine(personal,".OpenSim");
  667. temp = ".";
  668. return temp;
  669. }
  670. public static string assetsDir()
  671. {
  672. return Path.Combine(configDir(), "assets");
  673. }
  674. public static string inventoryDir()
  675. {
  676. return Path.Combine(configDir(), "inventory");
  677. }
  678. public static string configDir()
  679. {
  680. return ".";
  681. }
  682. public static string dataDir()
  683. {
  684. return ".";
  685. }
  686. public static string logDir()
  687. {
  688. return ".";
  689. }
  690. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  691. public static string GetUniqueFilename(string FileName)
  692. {
  693. int count = 0;
  694. string Name;
  695. if (File.Exists(FileName))
  696. {
  697. FileInfo f = new FileInfo(FileName);
  698. if (!String.IsNullOrEmpty(f.Extension))
  699. {
  700. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  701. }
  702. else
  703. {
  704. Name = f.FullName;
  705. }
  706. while (File.Exists(FileName))
  707. {
  708. count++;
  709. FileName = Name + count + f.Extension;
  710. }
  711. }
  712. return FileName;
  713. }
  714. // Nini (config) related Methods
  715. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  716. {
  717. if (!File.Exists(fileName))
  718. {
  719. //create new file
  720. }
  721. XmlConfigSource config = new XmlConfigSource(fileName);
  722. AddDataRowToConfig(config, row);
  723. config.Save();
  724. return config;
  725. }
  726. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  727. {
  728. config.Configs.Add((string) row[0]);
  729. for (int i = 0; i < row.Table.Columns.Count; i++)
  730. {
  731. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  732. }
  733. }
  734. public static float Clip(float x, float min, float max)
  735. {
  736. return Math.Min(Math.Max(x, min), max);
  737. }
  738. public static int Clip(int x, int min, int max)
  739. {
  740. return Math.Min(Math.Max(x, min), max);
  741. }
  742. /// <summary>
  743. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  744. /// </summary>
  745. /// <param name="UUID"></param>
  746. /// <returns></returns>
  747. public static String ToRawUuidString(UUID UUID)
  748. {
  749. return UUID.Guid.ToString("n");
  750. }
  751. public static string CleanString(string input)
  752. {
  753. if (input.Length == 0)
  754. return input;
  755. int clip = input.Length;
  756. // Test for ++ string terminator
  757. int pos = input.IndexOf("\0");
  758. if (pos != -1 && pos < clip)
  759. clip = pos;
  760. // Test for CR
  761. pos = input.IndexOf("\r");
  762. if (pos != -1 && pos < clip)
  763. clip = pos;
  764. // Test for LF
  765. pos = input.IndexOf("\n");
  766. if (pos != -1 && pos < clip)
  767. clip = pos;
  768. // Truncate string before first end-of-line character found
  769. return input.Substring(0, clip);
  770. }
  771. /// <summary>
  772. /// returns the contents of /etc/issue on Unix Systems
  773. /// Use this for where it's absolutely necessary to implement platform specific stuff
  774. /// </summary>
  775. /// <returns></returns>
  776. public static string ReadEtcIssue()
  777. {
  778. try
  779. {
  780. StreamReader sr = new StreamReader("/etc/issue.net");
  781. string issue = sr.ReadToEnd();
  782. sr.Close();
  783. return issue;
  784. }
  785. catch (Exception)
  786. {
  787. return "";
  788. }
  789. }
  790. public static void SerializeToFile(string filename, Object obj)
  791. {
  792. IFormatter formatter = new BinaryFormatter();
  793. Stream stream = null;
  794. try
  795. {
  796. stream = new FileStream(
  797. filename, FileMode.Create,
  798. FileAccess.Write, FileShare.None);
  799. formatter.Serialize(stream, obj);
  800. }
  801. catch (Exception e)
  802. {
  803. m_log.Error(e.ToString());
  804. }
  805. finally
  806. {
  807. if (stream != null)
  808. {
  809. stream.Close();
  810. }
  811. }
  812. }
  813. public static Object DeserializeFromFile(string filename)
  814. {
  815. IFormatter formatter = new BinaryFormatter();
  816. Stream stream = null;
  817. Object ret = null;
  818. try
  819. {
  820. stream = new FileStream(
  821. filename, FileMode.Open,
  822. FileAccess.Read, FileShare.None);
  823. ret = formatter.Deserialize(stream);
  824. }
  825. catch (Exception e)
  826. {
  827. m_log.Error(e.ToString());
  828. }
  829. finally
  830. {
  831. if (stream != null)
  832. {
  833. stream.Close();
  834. }
  835. }
  836. return ret;
  837. }
  838. public static string Compress(string text)
  839. {
  840. byte[] buffer = Util.UTF8.GetBytes(text);
  841. MemoryStream memory = new MemoryStream();
  842. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  843. {
  844. compressor.Write(buffer, 0, buffer.Length);
  845. }
  846. memory.Position = 0;
  847. byte[] compressed = new byte[memory.Length];
  848. memory.Read(compressed, 0, compressed.Length);
  849. byte[] compressedBuffer = new byte[compressed.Length + 4];
  850. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  851. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  852. return Convert.ToBase64String(compressedBuffer);
  853. }
  854. public static string Decompress(string compressedText)
  855. {
  856. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  857. using (MemoryStream memory = new MemoryStream())
  858. {
  859. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  860. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  861. byte[] buffer = new byte[msgLength];
  862. memory.Position = 0;
  863. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  864. {
  865. decompressor.Read(buffer, 0, buffer.Length);
  866. }
  867. return Util.UTF8.GetString(buffer);
  868. }
  869. }
  870. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  871. {
  872. return SendXmlRpcCommand(url, methodName, args);
  873. }
  874. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  875. {
  876. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  877. return client.Send(url, 6000);
  878. }
  879. /// <summary>
  880. /// Returns an error message that the user could not be found in the database
  881. /// </summary>
  882. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  883. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  884. {
  885. XmlRpcResponse response = new XmlRpcResponse();
  886. Hashtable responseData = new Hashtable();
  887. responseData["error_type"] = "unknown_user";
  888. responseData["error_desc"] = "The user requested is not in the database";
  889. response.Value = responseData;
  890. return response;
  891. }
  892. /// <summary>
  893. /// Converts a byte array in big endian order into an ulong.
  894. /// </summary>
  895. /// <param name="bytes">
  896. /// The array of bytes
  897. /// </param>
  898. /// <returns>
  899. /// The extracted ulong
  900. /// </returns>
  901. public static ulong BytesToUInt64Big(byte[] bytes)
  902. {
  903. if (bytes.Length < 8) return 0;
  904. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  905. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  906. }
  907. // used for RemoteParcelRequest (for "About Landmark")
  908. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  909. {
  910. byte[] bytes =
  911. {
  912. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  913. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  914. (byte)x, (byte)(x >> 8), 0, 0,
  915. (byte)y, (byte)(y >> 8), 0, 0 };
  916. return new UUID(bytes, 0);
  917. }
  918. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  919. {
  920. byte[] bytes =
  921. {
  922. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  923. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  924. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  925. (byte)y, (byte)(y >> 8), 0, 0 };
  926. return new UUID(bytes, 0);
  927. }
  928. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  929. {
  930. byte[] bytes = parcelID.GetBytes();
  931. regionHandle = Utils.BytesToUInt64(bytes);
  932. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  933. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  934. }
  935. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  936. {
  937. byte[] bytes = parcelID.GetBytes();
  938. regionHandle = Utils.BytesToUInt64(bytes);
  939. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  940. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  941. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  942. }
  943. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  944. {
  945. ulong regionHandle;
  946. uint rx, ry;
  947. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  948. Utils.LongToUInts(regionHandle, out rx, out ry);
  949. x += rx;
  950. y += ry;
  951. }
  952. /// <summary>
  953. /// Get operating system information if available. Returns only the first 45 characters of information
  954. /// </summary>
  955. /// <returns>
  956. /// Operating system information. Returns an empty string if none was available.
  957. /// </returns>
  958. public static string GetOperatingSystemInformation()
  959. {
  960. string os = String.Empty;
  961. if (Environment.OSVersion.Platform != PlatformID.Unix)
  962. {
  963. os = Environment.OSVersion.ToString();
  964. }
  965. else
  966. {
  967. os = ReadEtcIssue();
  968. }
  969. if (os.Length > 45)
  970. {
  971. os = os.Substring(0, 45);
  972. }
  973. return os;
  974. }
  975. public static string GetRuntimeInformation()
  976. {
  977. string ru = String.Empty;
  978. if (Environment.OSVersion.Platform == PlatformID.Unix)
  979. ru = "Unix/Mono";
  980. else
  981. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  982. ru = "OSX/Mono";
  983. else
  984. {
  985. if (Type.GetType("Mono.Runtime") != null)
  986. ru = "Win/Mono";
  987. else
  988. ru = "Win/.NET";
  989. }
  990. return ru;
  991. }
  992. /// <summary>
  993. /// Is the given string a UUID?
  994. /// </summary>
  995. /// <param name="s"></param>
  996. /// <returns></returns>
  997. public static bool isUUID(string s)
  998. {
  999. return UUIDPattern.IsMatch(s);
  1000. }
  1001. public static string GetDisplayConnectionString(string connectionString)
  1002. {
  1003. int passPosition = 0;
  1004. int passEndPosition = 0;
  1005. string displayConnectionString = null;
  1006. // hide the password in the connection string
  1007. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1008. passPosition = connectionString.IndexOf("=", passPosition);
  1009. if (passPosition < connectionString.Length)
  1010. passPosition += 1;
  1011. passEndPosition = connectionString.IndexOf(";", passPosition);
  1012. displayConnectionString = connectionString.Substring(0, passPosition);
  1013. displayConnectionString += "***";
  1014. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1015. return displayConnectionString;
  1016. }
  1017. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1018. {
  1019. Type settingsType = settingsClass.GetType();
  1020. FieldInfo[] fieldInfos = settingsType.GetFields();
  1021. foreach (FieldInfo fieldInfo in fieldInfos)
  1022. {
  1023. if (!fieldInfo.IsStatic)
  1024. {
  1025. if (fieldInfo.FieldType == typeof(System.String))
  1026. {
  1027. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1028. }
  1029. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1030. {
  1031. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1032. }
  1033. else if (fieldInfo.FieldType == typeof(System.Int32))
  1034. {
  1035. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1036. }
  1037. else if (fieldInfo.FieldType == typeof(System.Single))
  1038. {
  1039. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1040. }
  1041. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1042. {
  1043. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1044. }
  1045. }
  1046. }
  1047. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1048. foreach (PropertyInfo propInfo in propertyInfos)
  1049. {
  1050. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1051. {
  1052. if (propInfo.PropertyType == typeof(System.String))
  1053. {
  1054. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1055. }
  1056. else if (propInfo.PropertyType == typeof(System.Boolean))
  1057. {
  1058. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1059. }
  1060. else if (propInfo.PropertyType == typeof(System.Int32))
  1061. {
  1062. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1063. }
  1064. else if (propInfo.PropertyType == typeof(System.Single))
  1065. {
  1066. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1067. }
  1068. if (propInfo.PropertyType == typeof(System.UInt32))
  1069. {
  1070. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1071. }
  1072. }
  1073. }
  1074. return settingsClass;
  1075. }
  1076. public static string Base64ToString(string str)
  1077. {
  1078. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  1079. byte[] todecode_byte = Convert.FromBase64String(str);
  1080. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1081. char[] decoded_char = new char[charCount];
  1082. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1083. string result = new String(decoded_char);
  1084. return result;
  1085. }
  1086. public static Guid GetHashGuid(string data, string salt)
  1087. {
  1088. byte[] hash = ComputeMD5Hash(data + salt);
  1089. //string s = BitConverter.ToString(hash);
  1090. Guid guid = new Guid(hash);
  1091. return guid;
  1092. }
  1093. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1094. {
  1095. byte retVal = 0;
  1096. switch (maturity)
  1097. {
  1098. case 0: //PG
  1099. retVal = 13;
  1100. break;
  1101. case 1: //Mature
  1102. retVal = 21;
  1103. break;
  1104. case 2: // Adult
  1105. retVal = 42;
  1106. break;
  1107. }
  1108. return retVal;
  1109. }
  1110. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1111. {
  1112. if (maturity <= 13)
  1113. return 0;
  1114. else if (maturity <= 21)
  1115. return 1;
  1116. else
  1117. return 2;
  1118. }
  1119. /// <summary>
  1120. /// Produces an OSDMap from its string representation on a stream
  1121. /// </summary>
  1122. /// <param name="data">The stream</param>
  1123. /// <param name="length">The size of the data on the stream</param>
  1124. /// <returns>The OSDMap or an exception</returns>
  1125. public static OSDMap GetOSDMap(Stream stream, int length)
  1126. {
  1127. byte[] data = new byte[length];
  1128. stream.Read(data, 0, length);
  1129. string strdata = Util.UTF8.GetString(data);
  1130. OSDMap args = null;
  1131. OSD buffer;
  1132. buffer = OSDParser.DeserializeJson(strdata);
  1133. if (buffer.Type == OSDType.Map)
  1134. {
  1135. args = (OSDMap)buffer;
  1136. return args;
  1137. }
  1138. return null;
  1139. }
  1140. public static OSDMap GetOSDMap(string data)
  1141. {
  1142. OSDMap args = null;
  1143. try
  1144. {
  1145. OSD buffer;
  1146. // We should pay attention to the content-type, but let's assume we know it's Json
  1147. buffer = OSDParser.DeserializeJson(data);
  1148. if (buffer.Type == OSDType.Map)
  1149. {
  1150. args = (OSDMap)buffer;
  1151. return args;
  1152. }
  1153. else
  1154. {
  1155. // uh?
  1156. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1157. return null;
  1158. }
  1159. }
  1160. catch (Exception ex)
  1161. {
  1162. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1163. return null;
  1164. }
  1165. }
  1166. public static string[] Glob(string path)
  1167. {
  1168. string vol=String.Empty;
  1169. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1170. {
  1171. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1172. if (vcomps.Length > 1)
  1173. {
  1174. path = vcomps[1];
  1175. vol = vcomps[0];
  1176. }
  1177. }
  1178. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1179. // Glob
  1180. path = vol;
  1181. if (vol != String.Empty)
  1182. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1183. else
  1184. path = new String(new char[] {Path.DirectorySeparatorChar});
  1185. List<string> paths = new List<string>();
  1186. List<string> found = new List<string>();
  1187. paths.Add(path);
  1188. int compIndex = -1;
  1189. foreach (string c in comps)
  1190. {
  1191. compIndex++;
  1192. List<string> addpaths = new List<string>();
  1193. foreach (string p in paths)
  1194. {
  1195. string[] dirs = Directory.GetDirectories(p, c);
  1196. if (dirs.Length != 0)
  1197. {
  1198. foreach (string dir in dirs)
  1199. addpaths.Add(Path.Combine(path, dir));
  1200. }
  1201. // Only add files if that is the last path component
  1202. if (compIndex == comps.Length - 1)
  1203. {
  1204. string[] files = Directory.GetFiles(p, c);
  1205. foreach (string f in files)
  1206. found.Add(f);
  1207. }
  1208. }
  1209. paths = addpaths;
  1210. }
  1211. return found.ToArray();
  1212. }
  1213. public static string ServerURI(string uri)
  1214. {
  1215. if (uri == string.Empty)
  1216. return string.Empty;
  1217. // Get rid of eventual slashes at the end
  1218. uri = uri.TrimEnd('/');
  1219. IPAddress ipaddr1 = null;
  1220. string port1 = "";
  1221. try
  1222. {
  1223. ipaddr1 = Util.GetHostFromURL(uri);
  1224. }
  1225. catch { }
  1226. try
  1227. {
  1228. port1 = uri.Split(new char[] { ':' })[2];
  1229. }
  1230. catch { }
  1231. // We tried our best to convert the domain names to IP addresses
  1232. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1233. }
  1234. /// <summary>
  1235. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1236. /// </summary>
  1237. /// <param name="str">
  1238. /// If null or empty, then an bytes[0] is returned.
  1239. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1240. /// </param>
  1241. /// <param name="args">
  1242. /// Arguments to substitute into the string via the {} mechanism.
  1243. /// </param>
  1244. /// <returns></returns>
  1245. public static byte[] StringToBytes256(string str, params object[] args)
  1246. {
  1247. return StringToBytes256(string.Format(str, args));
  1248. }
  1249. /// <summary>
  1250. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1251. /// </summary>
  1252. /// <param name="str">
  1253. /// If null or empty, then an bytes[0] is returned.
  1254. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1255. /// </param>
  1256. /// <returns></returns>
  1257. public static byte[] StringToBytes256(string str)
  1258. {
  1259. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1260. if (str.Length > 254) str = str.Remove(254);
  1261. if (!str.EndsWith("\0")) { str += "\0"; }
  1262. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1263. // might have gotten an oversized array even after the string trim
  1264. byte[] data = UTF8.GetBytes(str);
  1265. if (data.Length > 256)
  1266. {
  1267. Array.Resize<byte>(ref data, 256);
  1268. data[255] = 0;
  1269. }
  1270. return data;
  1271. }
  1272. /// <summary>
  1273. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1274. /// </summary>
  1275. /// <param name="str">
  1276. /// If null or empty, then an bytes[0] is returned.
  1277. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1278. /// </param>
  1279. /// <param name="args">
  1280. /// Arguments to substitute into the string via the {} mechanism.
  1281. /// </param>
  1282. /// <returns></returns>
  1283. public static byte[] StringToBytes1024(string str, params object[] args)
  1284. {
  1285. return StringToBytes1024(string.Format(str, args));
  1286. }
  1287. /// <summary>
  1288. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1289. /// </summary>
  1290. /// <param name="str">
  1291. /// If null or empty, then an bytes[0] is returned.
  1292. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1293. /// </param>
  1294. /// <returns></returns>
  1295. public static byte[] StringToBytes1024(string str)
  1296. {
  1297. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1298. if (str.Length > 1023) str = str.Remove(1023);
  1299. if (!str.EndsWith("\0")) { str += "\0"; }
  1300. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1301. // might have gotten an oversized array even after the string trim
  1302. byte[] data = UTF8.GetBytes(str);
  1303. if (data.Length > 1024)
  1304. {
  1305. Array.Resize<byte>(ref data, 1024);
  1306. data[1023] = 0;
  1307. }
  1308. return data;
  1309. }
  1310. /// <summary>
  1311. /// Used to trigger an early library load on Windows systems.
  1312. /// </summary>
  1313. /// <remarks>
  1314. /// Required to get 32-bit and 64-bit processes to automatically use the
  1315. /// appropriate native library.
  1316. /// </remarks>
  1317. /// <param name="dllToLoad"></param>
  1318. /// <returns></returns>
  1319. [DllImport("kernel32.dll")]
  1320. public static extern IntPtr LoadLibrary(string dllToLoad);
  1321. /// <summary>
  1322. /// Determine whether the current process is 64 bit
  1323. /// </summary>
  1324. /// <returns>true if so, false if not</returns>
  1325. public static bool Is64BitProcess()
  1326. {
  1327. return IntPtr.Size == 8;
  1328. }
  1329. #region FireAndForget Threading Pattern
  1330. /// <summary>
  1331. /// Created to work around a limitation in Mono with nested delegates
  1332. /// </summary>
  1333. private sealed class FireAndForgetWrapper
  1334. {
  1335. private static volatile FireAndForgetWrapper instance;
  1336. private static object syncRoot = new Object();
  1337. public static FireAndForgetWrapper Instance {
  1338. get {
  1339. if (instance == null)
  1340. {
  1341. lock (syncRoot)
  1342. {
  1343. if (instance == null)
  1344. {
  1345. instance = new FireAndForgetWrapper();
  1346. }
  1347. }
  1348. }
  1349. return instance;
  1350. }
  1351. }
  1352. public void FireAndForget(System.Threading.WaitCallback callback)
  1353. {
  1354. callback.BeginInvoke(null, EndFireAndForget, callback);
  1355. }
  1356. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1357. {
  1358. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1359. }
  1360. private static void EndFireAndForget(IAsyncResult ar)
  1361. {
  1362. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1363. try { callback.EndInvoke(ar); }
  1364. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1365. ar.AsyncWaitHandle.Close();
  1366. }
  1367. }
  1368. public static void FireAndForget(System.Threading.WaitCallback callback)
  1369. {
  1370. FireAndForget(callback, null);
  1371. }
  1372. public static void InitThreadPool(int maxThreads)
  1373. {
  1374. if (maxThreads < 2)
  1375. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1376. if (m_ThreadPool != null)
  1377. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1378. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1379. }
  1380. public static int FireAndForgetCount()
  1381. {
  1382. const int MAX_SYSTEM_THREADS = 200;
  1383. switch (FireAndForgetMethod)
  1384. {
  1385. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1386. case FireAndForgetMethod.QueueUserWorkItem:
  1387. case FireAndForgetMethod.BeginInvoke:
  1388. int workerThreads, iocpThreads;
  1389. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1390. return workerThreads;
  1391. case FireAndForgetMethod.SmartThreadPool:
  1392. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1393. case FireAndForgetMethod.Thread:
  1394. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1395. default:
  1396. throw new NotImplementedException();
  1397. }
  1398. }
  1399. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1400. {
  1401. WaitCallback realCallback;
  1402. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  1403. {
  1404. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  1405. realCallback = o => { Culture.SetCurrentCulture(); callback(o); };
  1406. }
  1407. else
  1408. {
  1409. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  1410. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  1411. // for decimals places but is read by a culture that treats commas as number seperators.
  1412. realCallback = o =>
  1413. {
  1414. Culture.SetCurrentCulture();
  1415. try
  1416. {
  1417. callback(o);
  1418. }
  1419. catch (Exception e)
  1420. {
  1421. m_log.ErrorFormat(
  1422. "[UTIL]: Continuing after async_call_method thread terminated with exception {0}{1}",
  1423. e.Message, e.StackTrace);
  1424. }
  1425. };
  1426. }
  1427. switch (FireAndForgetMethod)
  1428. {
  1429. case FireAndForgetMethod.RegressionTest:
  1430. case FireAndForgetMethod.None:
  1431. realCallback.Invoke(obj);
  1432. break;
  1433. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1434. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  1435. break;
  1436. case FireAndForgetMethod.QueueUserWorkItem:
  1437. ThreadPool.QueueUserWorkItem(realCallback, obj);
  1438. break;
  1439. case FireAndForgetMethod.BeginInvoke:
  1440. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  1441. wrapper.FireAndForget(realCallback, obj);
  1442. break;
  1443. case FireAndForgetMethod.SmartThreadPool:
  1444. if (m_ThreadPool == null)
  1445. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1446. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { realCallback, obj });
  1447. break;
  1448. case FireAndForgetMethod.Thread:
  1449. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  1450. thread.Start(obj);
  1451. break;
  1452. default:
  1453. throw new NotImplementedException();
  1454. }
  1455. }
  1456. /// <summary>
  1457. /// Get a thread pool report.
  1458. /// </summary>
  1459. /// <returns></returns>
  1460. public static string GetThreadPoolReport()
  1461. {
  1462. string threadPoolUsed = null;
  1463. int maxThreads = 0;
  1464. int minThreads = 0;
  1465. int allocatedThreads = 0;
  1466. int inUseThreads = 0;
  1467. int waitingCallbacks = 0;
  1468. int completionPortThreads = 0;
  1469. StringBuilder sb = new StringBuilder();
  1470. if (FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  1471. {
  1472. threadPoolUsed = "SmartThreadPool";
  1473. maxThreads = m_ThreadPool.MaxThreads;
  1474. minThreads = m_ThreadPool.MinThreads;
  1475. inUseThreads = m_ThreadPool.InUseThreads;
  1476. allocatedThreads = m_ThreadPool.ActiveThreads;
  1477. waitingCallbacks = m_ThreadPool.WaitingCallbacks;
  1478. }
  1479. else if (
  1480. FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem
  1481. || FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  1482. {
  1483. threadPoolUsed = "BuiltInThreadPool";
  1484. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  1485. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  1486. int availableThreads;
  1487. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  1488. inUseThreads = maxThreads - availableThreads;
  1489. allocatedThreads = -1;
  1490. waitingCallbacks = -1;
  1491. }
  1492. if (threadPoolUsed != null)
  1493. {
  1494. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  1495. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  1496. sb.AppendFormat("Min threads : {0}\n", minThreads);
  1497. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  1498. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  1499. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  1500. }
  1501. else
  1502. {
  1503. sb.AppendFormat("Thread pool not used\n");
  1504. }
  1505. return sb.ToString();
  1506. }
  1507. private static object SmartThreadPoolCallback(object o)
  1508. {
  1509. object[] array = (object[])o;
  1510. WaitCallback callback = (WaitCallback)array[0];
  1511. object obj = array[1];
  1512. callback(obj);
  1513. return null;
  1514. }
  1515. #endregion FireAndForget Threading Pattern
  1516. /// <summary>
  1517. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1518. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1519. /// for the callers.
  1520. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1521. /// </summary>
  1522. /// <returns></returns>
  1523. public static Int32 EnvironmentTickCount()
  1524. {
  1525. return Environment.TickCount & EnvironmentTickCountMask;
  1526. }
  1527. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1528. /// <summary>
  1529. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1530. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1531. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1532. /// </summary>
  1533. /// <param name="newValue"></param>
  1534. /// <param name="prevValue"></param>
  1535. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1536. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  1537. {
  1538. Int32 diff = newValue - prevValue;
  1539. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1540. }
  1541. /// <summary>
  1542. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1543. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1544. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1545. /// </summary>
  1546. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1547. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1548. {
  1549. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  1550. }
  1551. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1552. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1553. // A positive return value indicates A occured later than B
  1554. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1555. {
  1556. // A, B and TC are all between 0 and 0x3fffffff
  1557. int tc = EnvironmentTickCount();
  1558. if (tc - tcA >= 0)
  1559. tcA += EnvironmentTickCountMask + 1;
  1560. if (tc - tcB >= 0)
  1561. tcB += EnvironmentTickCountMask + 1;
  1562. return tcA - tcB;
  1563. }
  1564. /// <summary>
  1565. /// Prints the call stack at any given point. Useful for debugging.
  1566. /// </summary>
  1567. public static void PrintCallStack()
  1568. {
  1569. StackTrace stackTrace = new StackTrace(true); // get call stack
  1570. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1571. // write call stack method names
  1572. foreach (StackFrame stackFrame in stackFrames)
  1573. {
  1574. MethodBase mb = stackFrame.GetMethod();
  1575. m_log.DebugFormat("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  1576. }
  1577. }
  1578. /// <summary>
  1579. /// Gets the client IP address
  1580. /// </summary>
  1581. /// <param name="xff"></param>
  1582. /// <returns></returns>
  1583. public static IPEndPoint GetClientIPFromXFF(string xff)
  1584. {
  1585. if (xff == string.Empty)
  1586. return null;
  1587. string[] parts = xff.Split(new char[] { ',' });
  1588. if (parts.Length > 0)
  1589. {
  1590. try
  1591. {
  1592. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1593. }
  1594. catch (Exception e)
  1595. {
  1596. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1597. }
  1598. }
  1599. return null;
  1600. }
  1601. public static string GetCallerIP(Hashtable req)
  1602. {
  1603. if (req.ContainsKey("headers"))
  1604. {
  1605. try
  1606. {
  1607. Hashtable headers = (Hashtable)req["headers"];
  1608. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1609. return headers["remote_addr"].ToString();
  1610. }
  1611. catch (Exception e)
  1612. {
  1613. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1614. }
  1615. }
  1616. return string.Empty;
  1617. }
  1618. #region Xml Serialization Utilities
  1619. public static bool ReadBoolean(XmlTextReader reader)
  1620. {
  1621. reader.ReadStartElement();
  1622. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1623. reader.ReadEndElement();
  1624. return result;
  1625. }
  1626. public static UUID ReadUUID(XmlTextReader reader, string name)
  1627. {
  1628. UUID id;
  1629. string idStr;
  1630. reader.ReadStartElement(name);
  1631. if (reader.Name == "Guid")
  1632. idStr = reader.ReadElementString("Guid");
  1633. else if (reader.Name == "UUID")
  1634. idStr = reader.ReadElementString("UUID");
  1635. else // no leading tag
  1636. idStr = reader.ReadContentAsString();
  1637. UUID.TryParse(idStr, out id);
  1638. reader.ReadEndElement();
  1639. return id;
  1640. }
  1641. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1642. {
  1643. Vector3 vec;
  1644. reader.ReadStartElement(name);
  1645. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1646. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1647. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1648. reader.ReadEndElement();
  1649. return vec;
  1650. }
  1651. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1652. {
  1653. Quaternion quat = new Quaternion();
  1654. reader.ReadStartElement(name);
  1655. while (reader.NodeType != XmlNodeType.EndElement)
  1656. {
  1657. switch (reader.Name.ToLower())
  1658. {
  1659. case "x":
  1660. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1661. break;
  1662. case "y":
  1663. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1664. break;
  1665. case "z":
  1666. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1667. break;
  1668. case "w":
  1669. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1670. break;
  1671. }
  1672. }
  1673. reader.ReadEndElement();
  1674. return quat;
  1675. }
  1676. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1677. {
  1678. string value = reader.ReadElementContentAsString(name, String.Empty);
  1679. // !!!!! to deal with flags without commas
  1680. if (value.Contains(" ") && !value.Contains(","))
  1681. value = value.Replace(" ", ", ");
  1682. return (T)Enum.Parse(typeof(T), value); ;
  1683. }
  1684. #endregion
  1685. #region Universal User Identifiers
  1686. /// <summary>
  1687. /// </summary>
  1688. /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
  1689. /// <param name="uuid">the uuid part</param>
  1690. /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
  1691. /// <param name="firstname">the first name part (e.g. Test)</param>
  1692. /// <param name="lastname">the last name part (e.g User)</param>
  1693. /// <param name="secret">the secret part</param>
  1694. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1695. {
  1696. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1697. string[] parts = value.Split(';');
  1698. if (parts.Length >= 1)
  1699. if (!UUID.TryParse(parts[0], out uuid))
  1700. return false;
  1701. if (parts.Length >= 2)
  1702. url = parts[1];
  1703. if (parts.Length >= 3)
  1704. {
  1705. string[] name = parts[2].Split();
  1706. if (name.Length == 2)
  1707. {
  1708. firstname = name[0];
  1709. lastname = name[1];
  1710. }
  1711. }
  1712. if (parts.Length >= 4)
  1713. secret = parts[3];
  1714. return true;
  1715. }
  1716. /// <summary>
  1717. /// Produces a universal (HG) system-facing identifier given the information
  1718. /// </summary>
  1719. /// <param name="acircuit"></param>
  1720. /// <returns>uuid[;homeURI[;first last]]</returns>
  1721. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1722. {
  1723. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1724. return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
  1725. else
  1726. return acircuit.AgentID.ToString();
  1727. }
  1728. /// <summary>
  1729. /// Produces a universal (HG) system-facing identifier given the information
  1730. /// </summary>
  1731. /// <param name="id">UUID of the user</param>
  1732. /// <param name="firstName">first name (e.g Test)</param>
  1733. /// <param name="lastName">last name (e.g. User)</param>
  1734. /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
  1735. /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
  1736. public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
  1737. {
  1738. string agentsURI = homeURI;
  1739. if (!agentsURI.EndsWith("/"))
  1740. agentsURI += "/";
  1741. // This is ugly, but there's no other way, given that the name is changed
  1742. // in the agent circuit data for foreigners
  1743. if (lastName.Contains("@"))
  1744. {
  1745. string[] parts = firstName.Split(new char[] { '.' });
  1746. if (parts.Length == 2)
  1747. return id.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1748. }
  1749. return id.ToString() + ";" + agentsURI + ";" + firstName + " " + lastName;
  1750. }
  1751. /// <summary>
  1752. /// Produces a universal (HG) user-facing name given the information
  1753. /// </summary>
  1754. /// <param name="firstName"></param>
  1755. /// <param name="lastName"></param>
  1756. /// <param name="homeURI"></param>
  1757. /// <returns>string of the form first.last @foo.com or first last</returns>
  1758. public static string UniversalName(String firstName, String lastName, String homeURI)
  1759. {
  1760. Uri uri = null;
  1761. try
  1762. {
  1763. uri = new Uri(homeURI);
  1764. }
  1765. catch (UriFormatException)
  1766. {
  1767. return firstName + " " + lastName;
  1768. }
  1769. return firstName + "." + lastName + " " + "@" + uri.Authority;
  1770. }
  1771. #endregion
  1772. }
  1773. }