1
0

Util.cs 65 KB

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