Util.cs 62 KB

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