Util.cs 61 KB

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