Util.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  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. /// <summary>
  871. /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
  872. /// </summary>
  873. /// <param name='inputStream'>
  874. /// Input stream. Must be seekable.
  875. /// </param>
  876. /// <exception cref='ArgumentException'>
  877. /// Thrown if the input stream is not seekable.
  878. /// </exception>
  879. public static Stream Copy(Stream inputStream)
  880. {
  881. if (!inputStream.CanSeek)
  882. throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
  883. const int readSize = 256;
  884. byte[] buffer = new byte[readSize];
  885. MemoryStream ms = new MemoryStream();
  886. int count = inputStream.Read(buffer, 0, readSize);
  887. while (count > 0)
  888. {
  889. ms.Write(buffer, 0, count);
  890. count = inputStream.Read(buffer, 0, readSize);
  891. }
  892. ms.Position = 0;
  893. inputStream.Position = 0;
  894. return ms;
  895. }
  896. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  897. {
  898. return SendXmlRpcCommand(url, methodName, args);
  899. }
  900. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  901. {
  902. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  903. return client.Send(url, 6000);
  904. }
  905. /// <summary>
  906. /// Returns an error message that the user could not be found in the database
  907. /// </summary>
  908. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  909. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  910. {
  911. XmlRpcResponse response = new XmlRpcResponse();
  912. Hashtable responseData = new Hashtable();
  913. responseData["error_type"] = "unknown_user";
  914. responseData["error_desc"] = "The user requested is not in the database";
  915. response.Value = responseData;
  916. return response;
  917. }
  918. /// <summary>
  919. /// Converts a byte array in big endian order into an ulong.
  920. /// </summary>
  921. /// <param name="bytes">
  922. /// The array of bytes
  923. /// </param>
  924. /// <returns>
  925. /// The extracted ulong
  926. /// </returns>
  927. public static ulong BytesToUInt64Big(byte[] bytes)
  928. {
  929. if (bytes.Length < 8) return 0;
  930. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  931. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  932. }
  933. // used for RemoteParcelRequest (for "About Landmark")
  934. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  935. {
  936. byte[] bytes =
  937. {
  938. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  939. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  940. (byte)x, (byte)(x >> 8), 0, 0,
  941. (byte)y, (byte)(y >> 8), 0, 0 };
  942. return new UUID(bytes, 0);
  943. }
  944. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  945. {
  946. byte[] bytes =
  947. {
  948. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  949. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  950. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  951. (byte)y, (byte)(y >> 8), 0, 0 };
  952. return new UUID(bytes, 0);
  953. }
  954. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  955. {
  956. byte[] bytes = parcelID.GetBytes();
  957. regionHandle = Utils.BytesToUInt64(bytes);
  958. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  959. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  960. }
  961. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  962. {
  963. byte[] bytes = parcelID.GetBytes();
  964. regionHandle = Utils.BytesToUInt64(bytes);
  965. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  966. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  967. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  968. }
  969. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  970. {
  971. ulong regionHandle;
  972. uint rx, ry;
  973. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  974. Utils.LongToUInts(regionHandle, out rx, out ry);
  975. x += rx;
  976. y += ry;
  977. }
  978. /// <summary>
  979. /// Get operating system information if available. Returns only the first 45 characters of information
  980. /// </summary>
  981. /// <returns>
  982. /// Operating system information. Returns an empty string if none was available.
  983. /// </returns>
  984. public static string GetOperatingSystemInformation()
  985. {
  986. string os = String.Empty;
  987. if (Environment.OSVersion.Platform != PlatformID.Unix)
  988. {
  989. os = Environment.OSVersion.ToString();
  990. }
  991. else
  992. {
  993. os = ReadEtcIssue();
  994. }
  995. if (os.Length > 45)
  996. {
  997. os = os.Substring(0, 45);
  998. }
  999. return os;
  1000. }
  1001. public static string GetRuntimeInformation()
  1002. {
  1003. string ru = String.Empty;
  1004. if (Environment.OSVersion.Platform == PlatformID.Unix)
  1005. ru = "Unix/Mono";
  1006. else
  1007. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  1008. ru = "OSX/Mono";
  1009. else
  1010. {
  1011. if (Type.GetType("Mono.Runtime") != null)
  1012. ru = "Win/Mono";
  1013. else
  1014. ru = "Win/.NET";
  1015. }
  1016. return ru;
  1017. }
  1018. /// <summary>
  1019. /// Is the given string a UUID?
  1020. /// </summary>
  1021. /// <param name="s"></param>
  1022. /// <returns></returns>
  1023. public static bool isUUID(string s)
  1024. {
  1025. return UUIDPattern.IsMatch(s);
  1026. }
  1027. public static string GetDisplayConnectionString(string connectionString)
  1028. {
  1029. int passPosition = 0;
  1030. int passEndPosition = 0;
  1031. string displayConnectionString = null;
  1032. // hide the password in the connection string
  1033. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1034. passPosition = connectionString.IndexOf("=", passPosition);
  1035. if (passPosition < connectionString.Length)
  1036. passPosition += 1;
  1037. passEndPosition = connectionString.IndexOf(";", passPosition);
  1038. displayConnectionString = connectionString.Substring(0, passPosition);
  1039. displayConnectionString += "***";
  1040. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1041. return displayConnectionString;
  1042. }
  1043. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1044. {
  1045. Type settingsType = settingsClass.GetType();
  1046. FieldInfo[] fieldInfos = settingsType.GetFields();
  1047. foreach (FieldInfo fieldInfo in fieldInfos)
  1048. {
  1049. if (!fieldInfo.IsStatic)
  1050. {
  1051. if (fieldInfo.FieldType == typeof(System.String))
  1052. {
  1053. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1054. }
  1055. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1056. {
  1057. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1058. }
  1059. else if (fieldInfo.FieldType == typeof(System.Int32))
  1060. {
  1061. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1062. }
  1063. else if (fieldInfo.FieldType == typeof(System.Single))
  1064. {
  1065. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1066. }
  1067. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1068. {
  1069. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1070. }
  1071. }
  1072. }
  1073. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1074. foreach (PropertyInfo propInfo in propertyInfos)
  1075. {
  1076. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1077. {
  1078. if (propInfo.PropertyType == typeof(System.String))
  1079. {
  1080. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1081. }
  1082. else if (propInfo.PropertyType == typeof(System.Boolean))
  1083. {
  1084. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1085. }
  1086. else if (propInfo.PropertyType == typeof(System.Int32))
  1087. {
  1088. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1089. }
  1090. else if (propInfo.PropertyType == typeof(System.Single))
  1091. {
  1092. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1093. }
  1094. if (propInfo.PropertyType == typeof(System.UInt32))
  1095. {
  1096. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1097. }
  1098. }
  1099. }
  1100. return settingsClass;
  1101. }
  1102. public static string Base64ToString(string str)
  1103. {
  1104. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  1105. byte[] todecode_byte = Convert.FromBase64String(str);
  1106. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1107. char[] decoded_char = new char[charCount];
  1108. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1109. string result = new String(decoded_char);
  1110. return result;
  1111. }
  1112. public static Guid GetHashGuid(string data, string salt)
  1113. {
  1114. byte[] hash = ComputeMD5Hash(data + salt);
  1115. //string s = BitConverter.ToString(hash);
  1116. Guid guid = new Guid(hash);
  1117. return guid;
  1118. }
  1119. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1120. {
  1121. byte retVal = 0;
  1122. switch (maturity)
  1123. {
  1124. case 0: //PG
  1125. retVal = 13;
  1126. break;
  1127. case 1: //Mature
  1128. retVal = 21;
  1129. break;
  1130. case 2: // Adult
  1131. retVal = 42;
  1132. break;
  1133. }
  1134. return retVal;
  1135. }
  1136. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1137. {
  1138. if (maturity <= 13)
  1139. return 0;
  1140. else if (maturity <= 21)
  1141. return 1;
  1142. else
  1143. return 2;
  1144. }
  1145. /// <summary>
  1146. /// Produces an OSDMap from its string representation on a stream
  1147. /// </summary>
  1148. /// <param name="data">The stream</param>
  1149. /// <param name="length">The size of the data on the stream</param>
  1150. /// <returns>The OSDMap or an exception</returns>
  1151. public static OSDMap GetOSDMap(Stream stream, int length)
  1152. {
  1153. byte[] data = new byte[length];
  1154. stream.Read(data, 0, length);
  1155. string strdata = Util.UTF8.GetString(data);
  1156. OSDMap args = null;
  1157. OSD buffer;
  1158. buffer = OSDParser.DeserializeJson(strdata);
  1159. if (buffer.Type == OSDType.Map)
  1160. {
  1161. args = (OSDMap)buffer;
  1162. return args;
  1163. }
  1164. return null;
  1165. }
  1166. public static OSDMap GetOSDMap(string data)
  1167. {
  1168. OSDMap args = null;
  1169. try
  1170. {
  1171. OSD buffer;
  1172. // We should pay attention to the content-type, but let's assume we know it's Json
  1173. buffer = OSDParser.DeserializeJson(data);
  1174. if (buffer.Type == OSDType.Map)
  1175. {
  1176. args = (OSDMap)buffer;
  1177. return args;
  1178. }
  1179. else
  1180. {
  1181. // uh?
  1182. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1183. return null;
  1184. }
  1185. }
  1186. catch (Exception ex)
  1187. {
  1188. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1189. return null;
  1190. }
  1191. }
  1192. public static string[] Glob(string path)
  1193. {
  1194. string vol=String.Empty;
  1195. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1196. {
  1197. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1198. if (vcomps.Length > 1)
  1199. {
  1200. path = vcomps[1];
  1201. vol = vcomps[0];
  1202. }
  1203. }
  1204. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1205. // Glob
  1206. path = vol;
  1207. if (vol != String.Empty)
  1208. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1209. else
  1210. path = new String(new char[] {Path.DirectorySeparatorChar});
  1211. List<string> paths = new List<string>();
  1212. List<string> found = new List<string>();
  1213. paths.Add(path);
  1214. int compIndex = -1;
  1215. foreach (string c in comps)
  1216. {
  1217. compIndex++;
  1218. List<string> addpaths = new List<string>();
  1219. foreach (string p in paths)
  1220. {
  1221. string[] dirs = Directory.GetDirectories(p, c);
  1222. if (dirs.Length != 0)
  1223. {
  1224. foreach (string dir in dirs)
  1225. addpaths.Add(Path.Combine(path, dir));
  1226. }
  1227. // Only add files if that is the last path component
  1228. if (compIndex == comps.Length - 1)
  1229. {
  1230. string[] files = Directory.GetFiles(p, c);
  1231. foreach (string f in files)
  1232. found.Add(f);
  1233. }
  1234. }
  1235. paths = addpaths;
  1236. }
  1237. return found.ToArray();
  1238. }
  1239. public static string ServerURI(string uri)
  1240. {
  1241. if (uri == string.Empty)
  1242. return string.Empty;
  1243. // Get rid of eventual slashes at the end
  1244. uri = uri.TrimEnd('/');
  1245. IPAddress ipaddr1 = null;
  1246. string port1 = "";
  1247. try
  1248. {
  1249. ipaddr1 = Util.GetHostFromURL(uri);
  1250. }
  1251. catch { }
  1252. try
  1253. {
  1254. port1 = uri.Split(new char[] { ':' })[2];
  1255. }
  1256. catch { }
  1257. // We tried our best to convert the domain names to IP addresses
  1258. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1259. }
  1260. /// <summary>
  1261. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1262. /// </summary>
  1263. /// <param name="str">
  1264. /// If null or empty, then an bytes[0] is returned.
  1265. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1266. /// </param>
  1267. /// <param name="args">
  1268. /// Arguments to substitute into the string via the {} mechanism.
  1269. /// </param>
  1270. /// <returns></returns>
  1271. public static byte[] StringToBytes256(string str, params object[] args)
  1272. {
  1273. return StringToBytes256(string.Format(str, args));
  1274. }
  1275. /// <summary>
  1276. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1277. /// </summary>
  1278. /// <param name="str">
  1279. /// If null or empty, then an bytes[0] is returned.
  1280. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1281. /// </param>
  1282. /// <returns></returns>
  1283. public static byte[] StringToBytes256(string str)
  1284. {
  1285. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1286. if (str.Length > 254) str = str.Remove(254);
  1287. if (!str.EndsWith("\0")) { str += "\0"; }
  1288. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1289. // might have gotten an oversized array even after the string trim
  1290. byte[] data = UTF8.GetBytes(str);
  1291. if (data.Length > 256)
  1292. {
  1293. Array.Resize<byte>(ref data, 256);
  1294. data[255] = 0;
  1295. }
  1296. return data;
  1297. }
  1298. /// <summary>
  1299. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1300. /// </summary>
  1301. /// <param name="str">
  1302. /// If null or empty, then an bytes[0] is returned.
  1303. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1304. /// </param>
  1305. /// <param name="args">
  1306. /// Arguments to substitute into the string via the {} mechanism.
  1307. /// </param>
  1308. /// <returns></returns>
  1309. public static byte[] StringToBytes1024(string str, params object[] args)
  1310. {
  1311. return StringToBytes1024(string.Format(str, args));
  1312. }
  1313. /// <summary>
  1314. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1315. /// </summary>
  1316. /// <param name="str">
  1317. /// If null or empty, then an bytes[0] is returned.
  1318. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1319. /// </param>
  1320. /// <returns></returns>
  1321. public static byte[] StringToBytes1024(string str)
  1322. {
  1323. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1324. if (str.Length > 1023) str = str.Remove(1023);
  1325. if (!str.EndsWith("\0")) { str += "\0"; }
  1326. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1327. // might have gotten an oversized array even after the string trim
  1328. byte[] data = UTF8.GetBytes(str);
  1329. if (data.Length > 1024)
  1330. {
  1331. Array.Resize<byte>(ref data, 1024);
  1332. data[1023] = 0;
  1333. }
  1334. return data;
  1335. }
  1336. /// <summary>
  1337. /// Used to trigger an early library load on Windows systems.
  1338. /// </summary>
  1339. /// <remarks>
  1340. /// Required to get 32-bit and 64-bit processes to automatically use the
  1341. /// appropriate native library.
  1342. /// </remarks>
  1343. /// <param name="dllToLoad"></param>
  1344. /// <returns></returns>
  1345. [DllImport("kernel32.dll")]
  1346. public static extern IntPtr LoadLibrary(string dllToLoad);
  1347. /// <summary>
  1348. /// Determine whether the current process is 64 bit
  1349. /// </summary>
  1350. /// <returns>true if so, false if not</returns>
  1351. public static bool Is64BitProcess()
  1352. {
  1353. return IntPtr.Size == 8;
  1354. }
  1355. #region FireAndForget Threading Pattern
  1356. /// <summary>
  1357. /// Created to work around a limitation in Mono with nested delegates
  1358. /// </summary>
  1359. private sealed class FireAndForgetWrapper
  1360. {
  1361. private static volatile FireAndForgetWrapper instance;
  1362. private static object syncRoot = new Object();
  1363. public static FireAndForgetWrapper Instance {
  1364. get {
  1365. if (instance == null)
  1366. {
  1367. lock (syncRoot)
  1368. {
  1369. if (instance == null)
  1370. {
  1371. instance = new FireAndForgetWrapper();
  1372. }
  1373. }
  1374. }
  1375. return instance;
  1376. }
  1377. }
  1378. public void FireAndForget(System.Threading.WaitCallback callback)
  1379. {
  1380. callback.BeginInvoke(null, EndFireAndForget, callback);
  1381. }
  1382. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1383. {
  1384. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1385. }
  1386. private static void EndFireAndForget(IAsyncResult ar)
  1387. {
  1388. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1389. try { callback.EndInvoke(ar); }
  1390. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1391. ar.AsyncWaitHandle.Close();
  1392. }
  1393. }
  1394. public static void FireAndForget(System.Threading.WaitCallback callback)
  1395. {
  1396. FireAndForget(callback, null);
  1397. }
  1398. public static void InitThreadPool(int maxThreads)
  1399. {
  1400. if (maxThreads < 2)
  1401. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1402. if (m_ThreadPool != null)
  1403. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1404. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1405. }
  1406. public static int FireAndForgetCount()
  1407. {
  1408. const int MAX_SYSTEM_THREADS = 200;
  1409. switch (FireAndForgetMethod)
  1410. {
  1411. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1412. case FireAndForgetMethod.QueueUserWorkItem:
  1413. case FireAndForgetMethod.BeginInvoke:
  1414. int workerThreads, iocpThreads;
  1415. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1416. return workerThreads;
  1417. case FireAndForgetMethod.SmartThreadPool:
  1418. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1419. case FireAndForgetMethod.Thread:
  1420. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1421. default:
  1422. throw new NotImplementedException();
  1423. }
  1424. }
  1425. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1426. {
  1427. WaitCallback realCallback;
  1428. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  1429. {
  1430. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  1431. realCallback = o => { Culture.SetCurrentCulture(); callback(o); };
  1432. }
  1433. else
  1434. {
  1435. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  1436. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  1437. // for decimals places but is read by a culture that treats commas as number seperators.
  1438. realCallback = o =>
  1439. {
  1440. Culture.SetCurrentCulture();
  1441. try
  1442. {
  1443. callback(o);
  1444. }
  1445. catch (Exception e)
  1446. {
  1447. m_log.ErrorFormat(
  1448. "[UTIL]: Continuing after async_call_method thread terminated with exception {0}{1}",
  1449. e.Message, e.StackTrace);
  1450. }
  1451. };
  1452. }
  1453. switch (FireAndForgetMethod)
  1454. {
  1455. case FireAndForgetMethod.RegressionTest:
  1456. case FireAndForgetMethod.None:
  1457. realCallback.Invoke(obj);
  1458. break;
  1459. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1460. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  1461. break;
  1462. case FireAndForgetMethod.QueueUserWorkItem:
  1463. ThreadPool.QueueUserWorkItem(realCallback, obj);
  1464. break;
  1465. case FireAndForgetMethod.BeginInvoke:
  1466. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  1467. wrapper.FireAndForget(realCallback, obj);
  1468. break;
  1469. case FireAndForgetMethod.SmartThreadPool:
  1470. if (m_ThreadPool == null)
  1471. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1472. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { realCallback, obj });
  1473. break;
  1474. case FireAndForgetMethod.Thread:
  1475. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  1476. thread.Start(obj);
  1477. break;
  1478. default:
  1479. throw new NotImplementedException();
  1480. }
  1481. }
  1482. /// <summary>
  1483. /// Get a thread pool report.
  1484. /// </summary>
  1485. /// <returns></returns>
  1486. public static string GetThreadPoolReport()
  1487. {
  1488. string threadPoolUsed = null;
  1489. int maxThreads = 0;
  1490. int minThreads = 0;
  1491. int allocatedThreads = 0;
  1492. int inUseThreads = 0;
  1493. int waitingCallbacks = 0;
  1494. int completionPortThreads = 0;
  1495. StringBuilder sb = new StringBuilder();
  1496. if (FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  1497. {
  1498. threadPoolUsed = "SmartThreadPool";
  1499. maxThreads = m_ThreadPool.MaxThreads;
  1500. minThreads = m_ThreadPool.MinThreads;
  1501. inUseThreads = m_ThreadPool.InUseThreads;
  1502. allocatedThreads = m_ThreadPool.ActiveThreads;
  1503. waitingCallbacks = m_ThreadPool.WaitingCallbacks;
  1504. }
  1505. else if (
  1506. FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem
  1507. || FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  1508. {
  1509. threadPoolUsed = "BuiltInThreadPool";
  1510. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  1511. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  1512. int availableThreads;
  1513. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  1514. inUseThreads = maxThreads - availableThreads;
  1515. allocatedThreads = -1;
  1516. waitingCallbacks = -1;
  1517. }
  1518. if (threadPoolUsed != null)
  1519. {
  1520. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  1521. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  1522. sb.AppendFormat("Min threads : {0}\n", minThreads);
  1523. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  1524. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  1525. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  1526. }
  1527. else
  1528. {
  1529. sb.AppendFormat("Thread pool not used\n");
  1530. }
  1531. return sb.ToString();
  1532. }
  1533. private static object SmartThreadPoolCallback(object o)
  1534. {
  1535. object[] array = (object[])o;
  1536. WaitCallback callback = (WaitCallback)array[0];
  1537. object obj = array[1];
  1538. callback(obj);
  1539. return null;
  1540. }
  1541. #endregion FireAndForget Threading Pattern
  1542. /// <summary>
  1543. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1544. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1545. /// for the callers.
  1546. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1547. /// </summary>
  1548. /// <returns></returns>
  1549. public static Int32 EnvironmentTickCount()
  1550. {
  1551. return Environment.TickCount & EnvironmentTickCountMask;
  1552. }
  1553. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1554. /// <summary>
  1555. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1556. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1557. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1558. /// </summary>
  1559. /// <param name="newValue"></param>
  1560. /// <param name="prevValue"></param>
  1561. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1562. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  1563. {
  1564. Int32 diff = newValue - prevValue;
  1565. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1566. }
  1567. /// <summary>
  1568. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1569. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1570. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1571. /// </summary>
  1572. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1573. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1574. {
  1575. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  1576. }
  1577. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1578. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1579. // A positive return value indicates A occured later than B
  1580. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1581. {
  1582. // A, B and TC are all between 0 and 0x3fffffff
  1583. int tc = EnvironmentTickCount();
  1584. if (tc - tcA >= 0)
  1585. tcA += EnvironmentTickCountMask + 1;
  1586. if (tc - tcB >= 0)
  1587. tcB += EnvironmentTickCountMask + 1;
  1588. return tcA - tcB;
  1589. }
  1590. /// <summary>
  1591. /// Prints the call stack at any given point. Useful for debugging.
  1592. /// </summary>
  1593. public static void PrintCallStack()
  1594. {
  1595. StackTrace stackTrace = new StackTrace(true); // get call stack
  1596. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1597. // write call stack method names
  1598. foreach (StackFrame stackFrame in stackFrames)
  1599. {
  1600. MethodBase mb = stackFrame.GetMethod();
  1601. m_log.DebugFormat("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  1602. }
  1603. }
  1604. /// <summary>
  1605. /// Gets the client IP address
  1606. /// </summary>
  1607. /// <param name="xff"></param>
  1608. /// <returns></returns>
  1609. public static IPEndPoint GetClientIPFromXFF(string xff)
  1610. {
  1611. if (xff == string.Empty)
  1612. return null;
  1613. string[] parts = xff.Split(new char[] { ',' });
  1614. if (parts.Length > 0)
  1615. {
  1616. try
  1617. {
  1618. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1619. }
  1620. catch (Exception e)
  1621. {
  1622. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1623. }
  1624. }
  1625. return null;
  1626. }
  1627. public static string GetCallerIP(Hashtable req)
  1628. {
  1629. if (req.ContainsKey("headers"))
  1630. {
  1631. try
  1632. {
  1633. Hashtable headers = (Hashtable)req["headers"];
  1634. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1635. return headers["remote_addr"].ToString();
  1636. }
  1637. catch (Exception e)
  1638. {
  1639. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1640. }
  1641. }
  1642. return string.Empty;
  1643. }
  1644. #region Xml Serialization Utilities
  1645. public static bool ReadBoolean(XmlTextReader reader)
  1646. {
  1647. reader.ReadStartElement();
  1648. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1649. reader.ReadEndElement();
  1650. return result;
  1651. }
  1652. public static UUID ReadUUID(XmlTextReader reader, string name)
  1653. {
  1654. UUID id;
  1655. string idStr;
  1656. reader.ReadStartElement(name);
  1657. if (reader.Name == "Guid")
  1658. idStr = reader.ReadElementString("Guid");
  1659. else if (reader.Name == "UUID")
  1660. idStr = reader.ReadElementString("UUID");
  1661. else // no leading tag
  1662. idStr = reader.ReadContentAsString();
  1663. UUID.TryParse(idStr, out id);
  1664. reader.ReadEndElement();
  1665. return id;
  1666. }
  1667. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1668. {
  1669. Vector3 vec;
  1670. reader.ReadStartElement(name);
  1671. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1672. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1673. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1674. reader.ReadEndElement();
  1675. return vec;
  1676. }
  1677. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1678. {
  1679. Quaternion quat = new Quaternion();
  1680. reader.ReadStartElement(name);
  1681. while (reader.NodeType != XmlNodeType.EndElement)
  1682. {
  1683. switch (reader.Name.ToLower())
  1684. {
  1685. case "x":
  1686. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1687. break;
  1688. case "y":
  1689. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1690. break;
  1691. case "z":
  1692. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1693. break;
  1694. case "w":
  1695. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1696. break;
  1697. }
  1698. }
  1699. reader.ReadEndElement();
  1700. return quat;
  1701. }
  1702. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1703. {
  1704. string value = reader.ReadElementContentAsString(name, String.Empty);
  1705. // !!!!! to deal with flags without commas
  1706. if (value.Contains(" ") && !value.Contains(","))
  1707. value = value.Replace(" ", ", ");
  1708. return (T)Enum.Parse(typeof(T), value); ;
  1709. }
  1710. #endregion
  1711. #region Universal User Identifiers
  1712. /// <summary>
  1713. /// </summary>
  1714. /// <param name="value">uuid[;endpoint[;name]]</param>
  1715. /// <param name="uuid"></param>
  1716. /// <param name="url"></param>
  1717. /// <param name="firstname"></param>
  1718. /// <param name="lastname"></param>
  1719. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1720. {
  1721. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1722. string[] parts = value.Split(';');
  1723. if (parts.Length >= 1)
  1724. if (!UUID.TryParse(parts[0], out uuid))
  1725. return false;
  1726. if (parts.Length >= 2)
  1727. url = parts[1];
  1728. if (parts.Length >= 3)
  1729. {
  1730. string[] name = parts[2].Split();
  1731. if (name.Length == 2)
  1732. {
  1733. firstname = name[0];
  1734. lastname = name[1];
  1735. }
  1736. }
  1737. if (parts.Length >= 4)
  1738. secret = parts[3];
  1739. return true;
  1740. }
  1741. /// <summary>
  1742. ///
  1743. /// </summary>
  1744. /// <param name="acircuit"></param>
  1745. /// <returns>uuid[;endpoint[;name]]</returns>
  1746. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1747. {
  1748. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1749. {
  1750. string agentsURI = acircuit.ServiceURLs["HomeURI"].ToString();
  1751. if (!agentsURI.EndsWith("/"))
  1752. agentsURI += "/";
  1753. // This is ugly, but there's no other way, given that the name is changed
  1754. // in the agent circuit data for foreigners
  1755. if (acircuit.lastname.Contains("@"))
  1756. {
  1757. string[] parts = acircuit.firstname.Split(new char[] { '.' });
  1758. if (parts.Length == 2)
  1759. return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1760. }
  1761. return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + acircuit.firstname + " " + acircuit.lastname;
  1762. }
  1763. else
  1764. return acircuit.AgentID.ToString();
  1765. }
  1766. #endregion
  1767. }
  1768. }