Util.cs 68 KB

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