Util.cs 61 KB

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