Util.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  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. /// <value>
  139. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  140. /// </value>
  141. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  142. #region Vector Equations
  143. /// <summary>
  144. /// Get the distance between two 3d vectors
  145. /// </summary>
  146. /// <param name="a">A 3d vector</param>
  147. /// <param name="b">A 3d vector</param>
  148. /// <returns>The distance between the two vectors</returns>
  149. public static double GetDistanceTo(Vector3 a, Vector3 b)
  150. {
  151. float dx = a.X - b.X;
  152. float dy = a.Y - b.Y;
  153. float dz = a.Z - b.Z;
  154. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  155. }
  156. /// <summary>
  157. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  158. /// </summary>
  159. /// <param name="a"></param>
  160. /// <param name="b"></param>
  161. /// <param name="amount"></param>
  162. /// <returns></returns>
  163. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  164. {
  165. float dx = a.X - b.X;
  166. float dy = a.Y - b.Y;
  167. float dz = a.Z - b.Z;
  168. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  169. }
  170. /// <summary>
  171. /// Get the magnitude of a 3d vector
  172. /// </summary>
  173. /// <param name="a">A 3d vector</param>
  174. /// <returns>The magnitude of the vector</returns>
  175. public static double GetMagnitude(Vector3 a)
  176. {
  177. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  178. }
  179. /// <summary>
  180. /// Get a normalized form of a 3d vector
  181. /// </summary>
  182. /// <param name="a">A 3d vector</param>
  183. /// <returns>A new vector which is normalized form of the vector</returns>
  184. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  185. public static Vector3 GetNormalizedVector(Vector3 a)
  186. {
  187. if (IsZeroVector(a))
  188. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  189. float Mag = (float) GetMagnitude(a);
  190. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  191. }
  192. /// <summary>
  193. /// Returns if a vector is a zero vector (has all zero components)
  194. /// </summary>
  195. /// <returns></returns>
  196. public static bool IsZeroVector(Vector3 v)
  197. {
  198. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  199. {
  200. return true;
  201. }
  202. return false;
  203. }
  204. # endregion
  205. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  206. {
  207. float s;
  208. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  209. if (tr >= 1.0)
  210. {
  211. s = (float) (0.5 / Math.Sqrt(tr));
  212. return new Quaternion(
  213. (left.Z - up.Y) * s,
  214. (up.X - fwd.Z) * s,
  215. (fwd.Y - left.X) * s,
  216. (float) 0.25 / s);
  217. }
  218. else
  219. {
  220. float max = (left.Y > up.Z) ? left.Y : up.Z;
  221. if (max < fwd.X)
  222. {
  223. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  224. float x = (float) (s * 0.5);
  225. s = (float) (0.5 / s);
  226. return new Quaternion(
  227. x,
  228. (fwd.Y + left.X) * s,
  229. (up.X + fwd.Z) * s,
  230. (left.Z - up.Y) * s);
  231. }
  232. else if (max == left.Y)
  233. {
  234. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  235. float y = (float) (s * 0.5);
  236. s = (float) (0.5 / s);
  237. return new Quaternion(
  238. (fwd.Y + left.X) * s,
  239. y,
  240. (left.Z + up.Y) * s,
  241. (up.X - fwd.Z) * s);
  242. }
  243. else
  244. {
  245. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  246. float z = (float) (s * 0.5);
  247. s = (float) (0.5 / s);
  248. return new Quaternion(
  249. (up.X + fwd.Z) * s,
  250. (left.Z + up.Y) * s,
  251. z,
  252. (fwd.Y - left.X) * s);
  253. }
  254. }
  255. }
  256. public static Random RandomClass
  257. {
  258. get { return randomClass; }
  259. }
  260. public static ulong UIntsToLong(uint X, uint Y)
  261. {
  262. return Utils.UIntsToLong(X, Y);
  263. }
  264. public static T Clamp<T>(T x, T min, T max)
  265. where T : IComparable<T>
  266. {
  267. return x.CompareTo(max) > 0 ? max :
  268. x.CompareTo(min) < 0 ? min :
  269. x;
  270. }
  271. public static uint GetNextXferID()
  272. {
  273. uint id = 0;
  274. lock (XferLock)
  275. {
  276. id = nextXferID;
  277. nextXferID++;
  278. }
  279. return id;
  280. }
  281. public static string GetFileName(string file)
  282. {
  283. // Return just the filename on UNIX platforms
  284. // TODO: this should be customisable with a prefix, but that's something to do later.
  285. if (Environment.OSVersion.Platform == PlatformID.Unix)
  286. {
  287. return file;
  288. }
  289. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  290. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  291. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  292. {
  293. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  294. {
  295. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  296. }
  297. return "%APPDATA%\\OpenSim\\" + file;
  298. }
  299. // Catch all - covers older windows versions
  300. // (but those probably wont work anyway)
  301. return file;
  302. }
  303. /// <summary>
  304. /// Debug utility function to convert OSD into formatted XML for debugging purposes.
  305. /// </summary>
  306. /// <param name="osd">
  307. /// A <see cref="OSD"/>
  308. /// </param>
  309. /// <returns>
  310. /// A <see cref="System.String"/>
  311. /// </returns>
  312. public static string GetFormattedXml(OSD osd)
  313. {
  314. return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
  315. }
  316. /// <summary>
  317. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  318. /// </summary>
  319. /// <remarks>
  320. /// Please don't delete me even if I appear currently unused!
  321. /// </remarks>
  322. /// <param name="rawXml"></param>
  323. /// <returns></returns>
  324. public static string GetFormattedXml(string rawXml)
  325. {
  326. XmlDocument xd = new XmlDocument();
  327. xd.LoadXml(rawXml);
  328. StringBuilder sb = new StringBuilder();
  329. StringWriter sw = new StringWriter(sb);
  330. XmlTextWriter xtw = new XmlTextWriter(sw);
  331. xtw.Formatting = Formatting.Indented;
  332. try
  333. {
  334. xd.WriteTo(xtw);
  335. }
  336. finally
  337. {
  338. xtw.Close();
  339. }
  340. return sb.ToString();
  341. }
  342. /// <summary>
  343. /// Is the platform Windows?
  344. /// </summary>
  345. /// <returns>true if so, false otherwise</returns>
  346. public static bool IsWindows()
  347. {
  348. PlatformID platformId = Environment.OSVersion.Platform;
  349. return (platformId == PlatformID.Win32NT
  350. || platformId == PlatformID.Win32S
  351. || platformId == PlatformID.Win32Windows
  352. || platformId == PlatformID.WinCE);
  353. }
  354. public static bool LoadArchSpecificWindowsDll(string libraryName)
  355. {
  356. // We do this so that OpenSimulator on Windows loads the correct native library depending on whether
  357. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  358. // will find it already loaded later on.
  359. //
  360. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  361. // controlled in config files.
  362. string nativeLibraryPath;
  363. if (Util.Is64BitProcess())
  364. nativeLibraryPath = "lib64/" + libraryName;
  365. else
  366. nativeLibraryPath = "lib32/" + libraryName;
  367. m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
  368. if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
  369. {
  370. m_log.ErrorFormat(
  371. "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
  372. return false;
  373. }
  374. else
  375. {
  376. return true;
  377. }
  378. }
  379. public static bool IsEnvironmentSupported(ref string reason)
  380. {
  381. // Must have .NET 2.0 (Generics / libsl)
  382. if (Environment.Version.Major < 2)
  383. {
  384. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  385. return false;
  386. }
  387. // Windows 95/98/ME are unsupported
  388. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  389. Environment.OSVersion.Platform != PlatformID.Win32NT)
  390. {
  391. reason = "Windows 95/98/ME will not run OpenSim";
  392. return false;
  393. }
  394. // Windows 2000 / Pre-SP2 XP
  395. if (Environment.OSVersion.Version.Major == 5 &&
  396. Environment.OSVersion.Version.Minor == 0)
  397. {
  398. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  399. return false;
  400. }
  401. return true;
  402. }
  403. public static int UnixTimeSinceEpoch()
  404. {
  405. return ToUnixTime(DateTime.UtcNow);
  406. }
  407. public static int ToUnixTime(DateTime stamp)
  408. {
  409. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  410. return (int) t.TotalSeconds;
  411. }
  412. public static DateTime ToDateTime(ulong seconds)
  413. {
  414. DateTime epoch = unixEpoch;
  415. return epoch.AddSeconds(seconds);
  416. }
  417. public static DateTime ToDateTime(int seconds)
  418. {
  419. DateTime epoch = unixEpoch;
  420. return epoch.AddSeconds(seconds);
  421. }
  422. /// <summary>
  423. /// Return an md5 hash of the given string
  424. /// </summary>
  425. /// <param name="data"></param>
  426. /// <returns></returns>
  427. public static string Md5Hash(string data)
  428. {
  429. byte[] dataMd5 = ComputeMD5Hash(data);
  430. StringBuilder sb = new StringBuilder();
  431. for (int i = 0; i < dataMd5.Length; i++)
  432. sb.AppendFormat("{0:x2}", dataMd5[i]);
  433. return sb.ToString();
  434. }
  435. private static byte[] ComputeMD5Hash(string data)
  436. {
  437. MD5 md5 = MD5.Create();
  438. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  439. }
  440. /// <summary>
  441. /// Return an SHA1 hash
  442. /// </summary>
  443. /// <param name="data"></param>
  444. /// <returns></returns>
  445. public static string SHA1Hash(string data)
  446. {
  447. return SHA1Hash(Encoding.Default.GetBytes(data));
  448. }
  449. /// <summary>
  450. /// Return an SHA1 hash
  451. /// </summary>
  452. /// <param name="data"></param>
  453. /// <returns></returns>
  454. public static string SHA1Hash(byte[] data)
  455. {
  456. byte[] hash = ComputeSHA1Hash(data);
  457. return BitConverter.ToString(hash).Replace("-", String.Empty);
  458. }
  459. private static byte[] ComputeSHA1Hash(byte[] src)
  460. {
  461. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  462. return SHA1.ComputeHash(src);
  463. }
  464. public static int fast_distance2d(int x, int y)
  465. {
  466. x = Math.Abs(x);
  467. y = Math.Abs(y);
  468. int min = Math.Min(x, y);
  469. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  470. }
  471. /// <summary>
  472. /// Are the co-ordinates of the new region visible from the old region?
  473. /// </summary>
  474. /// <param name="oldx">Old region x-coord</param>
  475. /// <param name="newx">New region x-coord</param>
  476. /// <param name="oldy">Old region y-coord</param>
  477. /// <param name="newy">New region y-coord</param>
  478. /// <returns></returns>
  479. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy)
  480. {
  481. int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize);
  482. int startX = (int)oldx - dd;
  483. int startY = (int)oldy - dd;
  484. int endX = (int)oldx + dd;
  485. int endY = (int)oldy + dd;
  486. return (newx < startX || endX < newx || newy < startY || endY < newy);
  487. }
  488. public static string FieldToString(byte[] bytes)
  489. {
  490. return FieldToString(bytes, String.Empty);
  491. }
  492. /// <summary>
  493. /// Convert a variable length field (byte array) to a string, with a
  494. /// field name prepended to each line of the output
  495. /// </summary>
  496. /// <remarks>If the byte array has unprintable characters in it, a
  497. /// hex dump will be put in the string instead</remarks>
  498. /// <param name="bytes">The byte array to convert to a string</param>
  499. /// <param name="fieldName">A field name to prepend to each line of output</param>
  500. /// <returns>An ASCII string or a string containing a hex dump, minus
  501. /// the null terminator</returns>
  502. public static string FieldToString(byte[] bytes, string fieldName)
  503. {
  504. // Check for a common case
  505. if (bytes.Length == 0) return String.Empty;
  506. StringBuilder output = new StringBuilder();
  507. bool printable = true;
  508. for (int i = 0; i < bytes.Length; ++i)
  509. {
  510. // Check if there are any unprintable characters in the array
  511. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  512. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  513. {
  514. printable = false;
  515. break;
  516. }
  517. }
  518. if (printable)
  519. {
  520. if (fieldName.Length > 0)
  521. {
  522. output.Append(fieldName);
  523. output.Append(": ");
  524. }
  525. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  526. }
  527. else
  528. {
  529. for (int i = 0; i < bytes.Length; i += 16)
  530. {
  531. if (i != 0)
  532. output.Append(Environment.NewLine);
  533. if (fieldName.Length > 0)
  534. {
  535. output.Append(fieldName);
  536. output.Append(": ");
  537. }
  538. for (int j = 0; j < 16; j++)
  539. {
  540. if ((i + j) < bytes.Length)
  541. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  542. else
  543. output.Append(" ");
  544. }
  545. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  546. {
  547. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  548. output.Append((char) bytes[i + j]);
  549. else
  550. output.Append(".");
  551. }
  552. }
  553. }
  554. return output.ToString();
  555. }
  556. /// <summary>
  557. /// Converts a URL to a IPAddress
  558. /// </summary>
  559. /// <param name="url">URL Standard Format</param>
  560. /// <returns>A resolved IP Address</returns>
  561. public static IPAddress GetHostFromURL(string url)
  562. {
  563. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  564. }
  565. /// <summary>
  566. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  567. /// </summary>
  568. /// <param name="dnsAddress">DNS Hostname</param>
  569. /// <returns>An IP address, or null</returns>
  570. public static IPAddress GetHostFromDNS(string dnsAddress)
  571. {
  572. // Is it already a valid IP? No need to look it up.
  573. IPAddress ipa;
  574. if (IPAddress.TryParse(dnsAddress, out ipa))
  575. return ipa;
  576. IPAddress[] hosts = null;
  577. // Not an IP, lookup required
  578. try
  579. {
  580. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  581. }
  582. catch (Exception e)
  583. {
  584. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  585. // Still going to throw the exception on for now, since this was what was happening in the first place
  586. throw e;
  587. }
  588. foreach (IPAddress host in hosts)
  589. {
  590. if (host.AddressFamily == AddressFamily.InterNetwork)
  591. {
  592. return host;
  593. }
  594. }
  595. if (hosts.Length > 0)
  596. return hosts[0];
  597. return null;
  598. }
  599. public static Uri GetURI(string protocol, string hostname, int port, string path)
  600. {
  601. return new UriBuilder(protocol, hostname, port, path).Uri;
  602. }
  603. /// <summary>
  604. /// Gets a list of all local system IP addresses
  605. /// </summary>
  606. /// <returns></returns>
  607. public static IPAddress[] GetLocalHosts()
  608. {
  609. return Dns.GetHostAddresses(Dns.GetHostName());
  610. }
  611. public static IPAddress GetLocalHost()
  612. {
  613. IPAddress[] iplist = GetLocalHosts();
  614. if (iplist.Length == 0) // No accessible external interfaces
  615. {
  616. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  617. IPAddress localhost = loopback[0];
  618. return localhost;
  619. }
  620. foreach (IPAddress host in iplist)
  621. {
  622. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  623. {
  624. return host;
  625. }
  626. }
  627. if (iplist.Length > 0)
  628. {
  629. foreach (IPAddress host in iplist)
  630. {
  631. if (host.AddressFamily == AddressFamily.InterNetwork)
  632. return host;
  633. }
  634. // Well all else failed...
  635. return iplist[0];
  636. }
  637. return null;
  638. }
  639. /// <summary>
  640. /// Removes all invalid path chars (OS dependent)
  641. /// </summary>
  642. /// <param name="path">path</param>
  643. /// <returns>safe path</returns>
  644. public static string safePath(string path)
  645. {
  646. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  647. }
  648. /// <summary>
  649. /// Removes all invalid filename chars (OS dependent)
  650. /// </summary>
  651. /// <param name="path">filename</param>
  652. /// <returns>safe filename</returns>
  653. public static string safeFileName(string filename)
  654. {
  655. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  656. ;
  657. }
  658. //
  659. // directory locations
  660. //
  661. public static string homeDir()
  662. {
  663. string temp;
  664. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  665. // temp = Path.Combine(personal,".OpenSim");
  666. temp = ".";
  667. return temp;
  668. }
  669. public static string assetsDir()
  670. {
  671. return Path.Combine(configDir(), "assets");
  672. }
  673. public static string inventoryDir()
  674. {
  675. return Path.Combine(configDir(), "inventory");
  676. }
  677. public static string configDir()
  678. {
  679. return ".";
  680. }
  681. public static string dataDir()
  682. {
  683. return ".";
  684. }
  685. public static string logDir()
  686. {
  687. return ".";
  688. }
  689. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  690. public static string GetUniqueFilename(string FileName)
  691. {
  692. int count = 0;
  693. string Name;
  694. if (File.Exists(FileName))
  695. {
  696. FileInfo f = new FileInfo(FileName);
  697. if (!String.IsNullOrEmpty(f.Extension))
  698. {
  699. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  700. }
  701. else
  702. {
  703. Name = f.FullName;
  704. }
  705. while (File.Exists(FileName))
  706. {
  707. count++;
  708. FileName = Name + count + f.Extension;
  709. }
  710. }
  711. return FileName;
  712. }
  713. // Nini (config) related Methods
  714. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  715. {
  716. if (!File.Exists(fileName))
  717. {
  718. //create new file
  719. }
  720. XmlConfigSource config = new XmlConfigSource(fileName);
  721. AddDataRowToConfig(config, row);
  722. config.Save();
  723. return config;
  724. }
  725. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  726. {
  727. config.Configs.Add((string) row[0]);
  728. for (int i = 0; i < row.Table.Columns.Count; i++)
  729. {
  730. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  731. }
  732. }
  733. public static float Clip(float x, float min, float max)
  734. {
  735. return Math.Min(Math.Max(x, min), max);
  736. }
  737. public static int Clip(int x, int min, int max)
  738. {
  739. return Math.Min(Math.Max(x, min), max);
  740. }
  741. /// <summary>
  742. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  743. /// </summary>
  744. /// <param name="UUID"></param>
  745. /// <returns></returns>
  746. public static String ToRawUuidString(UUID UUID)
  747. {
  748. return UUID.Guid.ToString("n");
  749. }
  750. public static string CleanString(string input)
  751. {
  752. if (input.Length == 0)
  753. return input;
  754. int clip = input.Length;
  755. // Test for ++ string terminator
  756. int pos = input.IndexOf("\0");
  757. if (pos != -1 && pos < clip)
  758. clip = pos;
  759. // Test for CR
  760. pos = input.IndexOf("\r");
  761. if (pos != -1 && pos < clip)
  762. clip = pos;
  763. // Test for LF
  764. pos = input.IndexOf("\n");
  765. if (pos != -1 && pos < clip)
  766. clip = pos;
  767. // Truncate string before first end-of-line character found
  768. return input.Substring(0, clip);
  769. }
  770. /// <summary>
  771. /// returns the contents of /etc/issue on Unix Systems
  772. /// Use this for where it's absolutely necessary to implement platform specific stuff
  773. /// </summary>
  774. /// <returns></returns>
  775. public static string ReadEtcIssue()
  776. {
  777. try
  778. {
  779. StreamReader sr = new StreamReader("/etc/issue.net");
  780. string issue = sr.ReadToEnd();
  781. sr.Close();
  782. return issue;
  783. }
  784. catch (Exception)
  785. {
  786. return "";
  787. }
  788. }
  789. public static void SerializeToFile(string filename, Object obj)
  790. {
  791. IFormatter formatter = new BinaryFormatter();
  792. Stream stream = null;
  793. try
  794. {
  795. stream = new FileStream(
  796. filename, FileMode.Create,
  797. FileAccess.Write, FileShare.None);
  798. formatter.Serialize(stream, obj);
  799. }
  800. catch (Exception e)
  801. {
  802. m_log.Error(e.ToString());
  803. }
  804. finally
  805. {
  806. if (stream != null)
  807. {
  808. stream.Close();
  809. }
  810. }
  811. }
  812. public static Object DeserializeFromFile(string filename)
  813. {
  814. IFormatter formatter = new BinaryFormatter();
  815. Stream stream = null;
  816. Object ret = null;
  817. try
  818. {
  819. stream = new FileStream(
  820. filename, FileMode.Open,
  821. FileAccess.Read, FileShare.None);
  822. ret = formatter.Deserialize(stream);
  823. }
  824. catch (Exception e)
  825. {
  826. m_log.Error(e.ToString());
  827. }
  828. finally
  829. {
  830. if (stream != null)
  831. {
  832. stream.Close();
  833. }
  834. }
  835. return ret;
  836. }
  837. public static string Compress(string text)
  838. {
  839. byte[] buffer = Util.UTF8.GetBytes(text);
  840. MemoryStream memory = new MemoryStream();
  841. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  842. {
  843. compressor.Write(buffer, 0, buffer.Length);
  844. }
  845. memory.Position = 0;
  846. byte[] compressed = new byte[memory.Length];
  847. memory.Read(compressed, 0, compressed.Length);
  848. byte[] compressedBuffer = new byte[compressed.Length + 4];
  849. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  850. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  851. return Convert.ToBase64String(compressedBuffer);
  852. }
  853. public static string Decompress(string compressedText)
  854. {
  855. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  856. using (MemoryStream memory = new MemoryStream())
  857. {
  858. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  859. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  860. byte[] buffer = new byte[msgLength];
  861. memory.Position = 0;
  862. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  863. {
  864. decompressor.Read(buffer, 0, buffer.Length);
  865. }
  866. return Util.UTF8.GetString(buffer);
  867. }
  868. }
  869. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  870. {
  871. return SendXmlRpcCommand(url, methodName, args);
  872. }
  873. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  874. {
  875. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  876. return client.Send(url, 6000);
  877. }
  878. /// <summary>
  879. /// Returns an error message that the user could not be found in the database
  880. /// </summary>
  881. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  882. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  883. {
  884. XmlRpcResponse response = new XmlRpcResponse();
  885. Hashtable responseData = new Hashtable();
  886. responseData["error_type"] = "unknown_user";
  887. responseData["error_desc"] = "The user requested is not in the database";
  888. response.Value = responseData;
  889. return response;
  890. }
  891. /// <summary>
  892. /// Converts a byte array in big endian order into an ulong.
  893. /// </summary>
  894. /// <param name="bytes">
  895. /// The array of bytes
  896. /// </param>
  897. /// <returns>
  898. /// The extracted ulong
  899. /// </returns>
  900. public static ulong BytesToUInt64Big(byte[] bytes)
  901. {
  902. if (bytes.Length < 8) return 0;
  903. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  904. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  905. }
  906. // used for RemoteParcelRequest (for "About Landmark")
  907. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  908. {
  909. byte[] bytes =
  910. {
  911. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  912. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  913. (byte)x, (byte)(x >> 8), 0, 0,
  914. (byte)y, (byte)(y >> 8), 0, 0 };
  915. return new UUID(bytes, 0);
  916. }
  917. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  918. {
  919. byte[] bytes =
  920. {
  921. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  922. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  923. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  924. (byte)y, (byte)(y >> 8), 0, 0 };
  925. return new UUID(bytes, 0);
  926. }
  927. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  928. {
  929. byte[] bytes = parcelID.GetBytes();
  930. regionHandle = Utils.BytesToUInt64(bytes);
  931. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  932. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  933. }
  934. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  935. {
  936. byte[] bytes = parcelID.GetBytes();
  937. regionHandle = Utils.BytesToUInt64(bytes);
  938. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  939. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  940. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  941. }
  942. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  943. {
  944. ulong regionHandle;
  945. uint rx, ry;
  946. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  947. Utils.LongToUInts(regionHandle, out rx, out ry);
  948. x += rx;
  949. y += ry;
  950. }
  951. /// <summary>
  952. /// Get operating system information if available. Returns only the first 45 characters of information
  953. /// </summary>
  954. /// <returns>
  955. /// Operating system information. Returns an empty string if none was available.
  956. /// </returns>
  957. public static string GetOperatingSystemInformation()
  958. {
  959. string os = String.Empty;
  960. if (Environment.OSVersion.Platform != PlatformID.Unix)
  961. {
  962. os = Environment.OSVersion.ToString();
  963. }
  964. else
  965. {
  966. os = ReadEtcIssue();
  967. }
  968. if (os.Length > 45)
  969. {
  970. os = os.Substring(0, 45);
  971. }
  972. return os;
  973. }
  974. public static string GetRuntimeInformation()
  975. {
  976. string ru = String.Empty;
  977. if (Environment.OSVersion.Platform == PlatformID.Unix)
  978. ru = "Unix/Mono";
  979. else
  980. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  981. ru = "OSX/Mono";
  982. else
  983. {
  984. if (Type.GetType("Mono.Runtime") != null)
  985. ru = "Win/Mono";
  986. else
  987. ru = "Win/.NET";
  988. }
  989. return ru;
  990. }
  991. /// <summary>
  992. /// Is the given string a UUID?
  993. /// </summary>
  994. /// <param name="s"></param>
  995. /// <returns></returns>
  996. public static bool isUUID(string s)
  997. {
  998. return UUIDPattern.IsMatch(s);
  999. }
  1000. public static string GetDisplayConnectionString(string connectionString)
  1001. {
  1002. int passPosition = 0;
  1003. int passEndPosition = 0;
  1004. string displayConnectionString = null;
  1005. // hide the password in the connection string
  1006. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1007. passPosition = connectionString.IndexOf("=", passPosition);
  1008. if (passPosition < connectionString.Length)
  1009. passPosition += 1;
  1010. passEndPosition = connectionString.IndexOf(";", passPosition);
  1011. displayConnectionString = connectionString.Substring(0, passPosition);
  1012. displayConnectionString += "***";
  1013. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1014. return displayConnectionString;
  1015. }
  1016. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1017. {
  1018. Type settingsType = settingsClass.GetType();
  1019. FieldInfo[] fieldInfos = settingsType.GetFields();
  1020. foreach (FieldInfo fieldInfo in fieldInfos)
  1021. {
  1022. if (!fieldInfo.IsStatic)
  1023. {
  1024. if (fieldInfo.FieldType == typeof(System.String))
  1025. {
  1026. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1027. }
  1028. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1029. {
  1030. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1031. }
  1032. else if (fieldInfo.FieldType == typeof(System.Int32))
  1033. {
  1034. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1035. }
  1036. else if (fieldInfo.FieldType == typeof(System.Single))
  1037. {
  1038. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1039. }
  1040. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1041. {
  1042. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1043. }
  1044. }
  1045. }
  1046. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1047. foreach (PropertyInfo propInfo in propertyInfos)
  1048. {
  1049. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1050. {
  1051. if (propInfo.PropertyType == typeof(System.String))
  1052. {
  1053. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1054. }
  1055. else if (propInfo.PropertyType == typeof(System.Boolean))
  1056. {
  1057. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1058. }
  1059. else if (propInfo.PropertyType == typeof(System.Int32))
  1060. {
  1061. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1062. }
  1063. else if (propInfo.PropertyType == typeof(System.Single))
  1064. {
  1065. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1066. }
  1067. if (propInfo.PropertyType == typeof(System.UInt32))
  1068. {
  1069. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1070. }
  1071. }
  1072. }
  1073. return settingsClass;
  1074. }
  1075. public static string Base64ToString(string str)
  1076. {
  1077. UTF8Encoding encoder = new UTF8Encoding();
  1078. Decoder utf8Decode = encoder.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. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1534. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1535. {
  1536. Int32 diff = EnvironmentTickCount() - prevValue;
  1537. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1538. }
  1539. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1540. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1541. // A positive return value indicates A occured later than B
  1542. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1543. {
  1544. // A, B and TC are all between 0 and 0x3fffffff
  1545. int tc = EnvironmentTickCount();
  1546. if (tc - tcA >= 0)
  1547. tcA += EnvironmentTickCountMask + 1;
  1548. if (tc - tcB >= 0)
  1549. tcB += EnvironmentTickCountMask + 1;
  1550. return tcA - tcB;
  1551. }
  1552. /// <summary>
  1553. /// Prints the call stack at any given point. Useful for debugging.
  1554. /// </summary>
  1555. public static void PrintCallStack()
  1556. {
  1557. StackTrace stackTrace = new StackTrace(true); // get call stack
  1558. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1559. // write call stack method names
  1560. foreach (StackFrame stackFrame in stackFrames)
  1561. {
  1562. MethodBase mb = stackFrame.GetMethod();
  1563. m_log.DebugFormat("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  1564. }
  1565. }
  1566. /// <summary>
  1567. /// Gets the client IP address
  1568. /// </summary>
  1569. /// <param name="xff"></param>
  1570. /// <returns></returns>
  1571. public static IPEndPoint GetClientIPFromXFF(string xff)
  1572. {
  1573. if (xff == string.Empty)
  1574. return null;
  1575. string[] parts = xff.Split(new char[] { ',' });
  1576. if (parts.Length > 0)
  1577. {
  1578. try
  1579. {
  1580. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1581. }
  1582. catch (Exception e)
  1583. {
  1584. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1585. }
  1586. }
  1587. return null;
  1588. }
  1589. public static string GetCallerIP(Hashtable req)
  1590. {
  1591. if (req.ContainsKey("headers"))
  1592. {
  1593. try
  1594. {
  1595. Hashtable headers = (Hashtable)req["headers"];
  1596. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1597. return headers["remote_addr"].ToString();
  1598. }
  1599. catch (Exception e)
  1600. {
  1601. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1602. }
  1603. }
  1604. return string.Empty;
  1605. }
  1606. #region Xml Serialization Utilities
  1607. public static bool ReadBoolean(XmlTextReader reader)
  1608. {
  1609. reader.ReadStartElement();
  1610. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1611. reader.ReadEndElement();
  1612. return result;
  1613. }
  1614. public static UUID ReadUUID(XmlTextReader reader, string name)
  1615. {
  1616. UUID id;
  1617. string idStr;
  1618. reader.ReadStartElement(name);
  1619. if (reader.Name == "Guid")
  1620. idStr = reader.ReadElementString("Guid");
  1621. else if (reader.Name == "UUID")
  1622. idStr = reader.ReadElementString("UUID");
  1623. else // no leading tag
  1624. idStr = reader.ReadContentAsString();
  1625. UUID.TryParse(idStr, out id);
  1626. reader.ReadEndElement();
  1627. return id;
  1628. }
  1629. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1630. {
  1631. Vector3 vec;
  1632. reader.ReadStartElement(name);
  1633. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1634. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1635. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1636. reader.ReadEndElement();
  1637. return vec;
  1638. }
  1639. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1640. {
  1641. Quaternion quat = new Quaternion();
  1642. reader.ReadStartElement(name);
  1643. while (reader.NodeType != XmlNodeType.EndElement)
  1644. {
  1645. switch (reader.Name.ToLower())
  1646. {
  1647. case "x":
  1648. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1649. break;
  1650. case "y":
  1651. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1652. break;
  1653. case "z":
  1654. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1655. break;
  1656. case "w":
  1657. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1658. break;
  1659. }
  1660. }
  1661. reader.ReadEndElement();
  1662. return quat;
  1663. }
  1664. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1665. {
  1666. string value = reader.ReadElementContentAsString(name, String.Empty);
  1667. // !!!!! to deal with flags without commas
  1668. if (value.Contains(" ") && !value.Contains(","))
  1669. value = value.Replace(" ", ", ");
  1670. return (T)Enum.Parse(typeof(T), value); ;
  1671. }
  1672. #endregion
  1673. #region Universal User Identifiers
  1674. /// <summary>
  1675. /// </summary>
  1676. /// <param name="value">uuid[;endpoint[;name]]</param>
  1677. /// <param name="uuid"></param>
  1678. /// <param name="url"></param>
  1679. /// <param name="firstname"></param>
  1680. /// <param name="lastname"></param>
  1681. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1682. {
  1683. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1684. string[] parts = value.Split(';');
  1685. if (parts.Length >= 1)
  1686. if (!UUID.TryParse(parts[0], out uuid))
  1687. return false;
  1688. if (parts.Length >= 2)
  1689. url = parts[1];
  1690. if (parts.Length >= 3)
  1691. {
  1692. string[] name = parts[2].Split();
  1693. if (name.Length == 2)
  1694. {
  1695. firstname = name[0];
  1696. lastname = name[1];
  1697. }
  1698. }
  1699. if (parts.Length >= 4)
  1700. secret = parts[3];
  1701. return true;
  1702. }
  1703. /// <summary>
  1704. ///
  1705. /// </summary>
  1706. /// <param name="acircuit"></param>
  1707. /// <returns>uuid[;endpoint[;name]]</returns>
  1708. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1709. {
  1710. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1711. {
  1712. string agentsURI = acircuit.ServiceURLs["HomeURI"].ToString();
  1713. if (!agentsURI.EndsWith("/"))
  1714. agentsURI += "/";
  1715. // This is ugly, but there's no other way, given that the name is changed
  1716. // in the agent circuit data for foreigners
  1717. if (acircuit.lastname.Contains("@"))
  1718. {
  1719. string[] parts = acircuit.firstname.Split(new char[] { '.' });
  1720. if (parts.Length == 2)
  1721. return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1722. }
  1723. return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + acircuit.firstname + " " + acircuit.lastname;
  1724. }
  1725. else
  1726. return acircuit.AgentID.ToString();
  1727. }
  1728. #endregion
  1729. }
  1730. }