Util.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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.Globalization;
  32. using System.IO;
  33. using System.IO.Compression;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using System.Reflection;
  37. using System.Runtime.Serialization;
  38. using System.Runtime.Serialization.Formatters.Binary;
  39. using System.Security.Cryptography;
  40. using System.Text;
  41. using System.Text.RegularExpressions;
  42. using System.Xml;
  43. using log4net;
  44. using Nini.Config;
  45. using Nwc.XmlRpc;
  46. using OpenMetaverse;
  47. using OpenMetaverse.StructuredData;
  48. namespace OpenSim.Framework
  49. {
  50. /// <summary>
  51. /// Miscellaneous utility functions
  52. /// </summary>
  53. public class Util
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. private static uint nextXferID = 5000;
  57. private static Random randomClass = new Random();
  58. // Get a list of invalid file characters (OS dependent)
  59. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  60. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  61. private static object XferLock = new object();
  62. // 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.
  63. private static readonly DateTime unixEpoch =
  64. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  65. public static readonly Regex UUIDPattern
  66. = 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}$");
  67. /// <summary>
  68. /// Linear interpolates B<->C using percent A
  69. /// </summary>
  70. /// <param name="a"></param>
  71. /// <param name="b"></param>
  72. /// <param name="c"></param>
  73. /// <returns></returns>
  74. public static double lerp(double a, double b, double c)
  75. {
  76. return (b*a) + (c*(1 - a));
  77. }
  78. /// <summary>
  79. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  80. /// Layout:
  81. /// A B
  82. /// C D
  83. /// A<->C = Y
  84. /// C<->D = X
  85. /// </summary>
  86. /// <param name="x"></param>
  87. /// <param name="y"></param>
  88. /// <param name="a"></param>
  89. /// <param name="b"></param>
  90. /// <param name="c"></param>
  91. /// <param name="d"></param>
  92. /// <returns></returns>
  93. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  94. {
  95. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  96. }
  97. /// <value>
  98. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  99. /// </value>
  100. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  101. #region Vector Equations
  102. /// <summary>
  103. /// Get the distance between two 3d vectors
  104. /// </summary>
  105. /// <param name="a">A 3d vector</param>
  106. /// <param name="b">A 3d vector</param>
  107. /// <returns>The distance between the two vectors</returns>
  108. public static double GetDistanceTo(Vector3 a, Vector3 b)
  109. {
  110. float dx = a.X - b.X;
  111. float dy = a.Y - b.Y;
  112. float dz = a.Z - b.Z;
  113. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  114. }
  115. /// <summary>
  116. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  117. /// </summary>
  118. /// <param name="a"></param>
  119. /// <param name="b"></param>
  120. /// <param name="amount"></param>
  121. /// <returns></returns>
  122. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  123. {
  124. float dx = a.X - b.X;
  125. float dy = a.Y - b.Y;
  126. float dz = a.Z - b.Z;
  127. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  128. }
  129. /// <summary>
  130. /// Get the magnitude of a 3d vector
  131. /// </summary>
  132. /// <param name="a">A 3d vector</param>
  133. /// <returns>The magnitude of the vector</returns>
  134. public static double GetMagnitude(Vector3 a)
  135. {
  136. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  137. }
  138. /// <summary>
  139. /// Get a normalized form of a 3d vector
  140. /// </summary>
  141. /// <param name="a">A 3d vector</param>
  142. /// <returns>A new vector which is normalized form of the vector</returns>
  143. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  144. public static Vector3 GetNormalizedVector(Vector3 a)
  145. {
  146. if (IsZeroVector(a))
  147. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  148. float Mag = (float) GetMagnitude(a);
  149. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  150. }
  151. /// <summary>
  152. /// Returns if a vector is a zero vector (has all zero components)
  153. /// </summary>
  154. /// <returns></returns>
  155. public static bool IsZeroVector(Vector3 v)
  156. {
  157. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  158. {
  159. return true;
  160. }
  161. return false;
  162. }
  163. # endregion
  164. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  165. {
  166. float s;
  167. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  168. if (tr >= 1.0)
  169. {
  170. s = (float) (0.5 / Math.Sqrt(tr));
  171. return new Quaternion(
  172. (left.Z - up.Y) * s,
  173. (up.X - fwd.Z) * s,
  174. (fwd.Y - left.X) * s,
  175. (float) 0.25 / s);
  176. }
  177. else
  178. {
  179. float max = (left.Y > up.Z) ? left.Y : up.Z;
  180. if (max < fwd.X)
  181. {
  182. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  183. float x = (float) (s * 0.5);
  184. s = (float) (0.5 / s);
  185. return new Quaternion(
  186. x,
  187. (fwd.Y + left.X) * s,
  188. (up.X + fwd.Z) * s,
  189. (left.Z - up.Y) * s);
  190. }
  191. else if (max == left.Y)
  192. {
  193. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  194. float y = (float) (s * 0.5);
  195. s = (float) (0.5 / s);
  196. return new Quaternion(
  197. (fwd.Y + left.X) * s,
  198. y,
  199. (left.Z + up.Y) * s,
  200. (up.X - fwd.Z) * s);
  201. }
  202. else
  203. {
  204. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  205. float z = (float) (s * 0.5);
  206. s = (float) (0.5 / s);
  207. return new Quaternion(
  208. (up.X + fwd.Z) * s,
  209. (left.Z + up.Y) * s,
  210. z,
  211. (fwd.Y - left.X) * s);
  212. }
  213. }
  214. }
  215. public static Random RandomClass
  216. {
  217. get { return randomClass; }
  218. }
  219. public static ulong UIntsToLong(uint X, uint Y)
  220. {
  221. return Utils.UIntsToLong(X, Y);
  222. }
  223. public static T Clamp<T>(T x, T min, T max)
  224. where T : IComparable<T>
  225. {
  226. return x.CompareTo(max) > 0 ? max :
  227. x.CompareTo(min) < 0 ? min :
  228. x;
  229. }
  230. public static uint GetNextXferID()
  231. {
  232. uint id = 0;
  233. lock (XferLock)
  234. {
  235. id = nextXferID;
  236. nextXferID++;
  237. }
  238. return id;
  239. }
  240. public static string GetFileName(string file)
  241. {
  242. // Return just the filename on UNIX platforms
  243. // TODO: this should be customisable with a prefix, but that's something to do later.
  244. if (Environment.OSVersion.Platform == PlatformID.Unix)
  245. {
  246. return file;
  247. }
  248. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  249. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  250. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  251. {
  252. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  253. {
  254. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  255. }
  256. return "%APPDATA%\\OpenSim\\" + file;
  257. }
  258. // Catch all - covers older windows versions
  259. // (but those probably wont work anyway)
  260. return file;
  261. }
  262. /// <summary>
  263. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  264. ///
  265. /// Please don't delete me even if I appear currently unused!
  266. /// </summary>
  267. /// <param name="rawXml"></param>
  268. /// <returns></returns>
  269. public static string GetFormattedXml(string rawXml)
  270. {
  271. XmlDocument xd = new XmlDocument();
  272. xd.LoadXml(rawXml);
  273. StringBuilder sb = new StringBuilder();
  274. StringWriter sw = new StringWriter(sb);
  275. XmlTextWriter xtw = new XmlTextWriter(sw);
  276. xtw.Formatting = Formatting.Indented;
  277. try
  278. {
  279. xd.WriteTo(xtw);
  280. }
  281. finally
  282. {
  283. xtw.Close();
  284. }
  285. return sb.ToString();
  286. }
  287. public static bool IsEnvironmentSupported(ref string reason)
  288. {
  289. // Must have .NET 2.0 (Generics / libsl)
  290. if (Environment.Version.Major < 2)
  291. {
  292. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  293. return false;
  294. }
  295. // Windows 95/98/ME are unsupported
  296. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  297. Environment.OSVersion.Platform != PlatformID.Win32NT)
  298. {
  299. reason = "Windows 95/98/ME will not run OpenSim";
  300. return false;
  301. }
  302. // Windows 2000 / Pre-SP2 XP
  303. if (Environment.OSVersion.Version.Major == 5 &&
  304. Environment.OSVersion.Version.Minor == 0)
  305. {
  306. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  307. return false;
  308. }
  309. return true;
  310. }
  311. public static int UnixTimeSinceEpoch()
  312. {
  313. return ToUnixTime(DateTime.UtcNow);
  314. }
  315. public static int ToUnixTime(DateTime stamp)
  316. {
  317. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  318. return (int) t.TotalSeconds;
  319. }
  320. public static DateTime ToDateTime(ulong seconds)
  321. {
  322. DateTime epoch = unixEpoch;
  323. return epoch.AddSeconds(seconds);
  324. }
  325. public static DateTime ToDateTime(int seconds)
  326. {
  327. DateTime epoch = unixEpoch;
  328. return epoch.AddSeconds(seconds);
  329. }
  330. /// <summary>
  331. /// Return an md5 hash of the given string
  332. /// </summary>
  333. /// <param name="data"></param>
  334. /// <returns></returns>
  335. public static string Md5Hash(string data)
  336. {
  337. byte[] dataMd5 = ComputeMD5Hash(data);
  338. StringBuilder sb = new StringBuilder();
  339. for (int i = 0; i < dataMd5.Length; i++)
  340. sb.AppendFormat("{0:x2}", dataMd5[i]);
  341. return sb.ToString();
  342. }
  343. private static byte[] ComputeMD5Hash(string data)
  344. {
  345. MD5 md5 = MD5.Create();
  346. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  347. }
  348. /// <summary>
  349. /// Return an SHA1 hash of the given string
  350. /// </summary>
  351. /// <param name="data"></param>
  352. /// <returns></returns>
  353. public static string SHA1Hash(string data)
  354. {
  355. byte[] hash = ComputeSHA1Hash(data);
  356. return BitConverter.ToString(hash).Replace("-", String.Empty);
  357. }
  358. private static byte[] ComputeSHA1Hash(string src)
  359. {
  360. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  361. return SHA1.ComputeHash(Encoding.Default.GetBytes(src));
  362. }
  363. public static int fast_distance2d(int x, int y)
  364. {
  365. x = Math.Abs(x);
  366. y = Math.Abs(y);
  367. int min = Math.Min(x, y);
  368. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  369. }
  370. public static bool IsOutsideView(uint oldx, uint newx, uint oldy, uint newy)
  371. {
  372. // Eventually this will be a function of the draw distance / camera position too.
  373. return (((int)Math.Abs((int)(oldx - newx)) > 1) || ((int)Math.Abs((int)(oldy - newy)) > 1));
  374. }
  375. public static string FieldToString(byte[] bytes)
  376. {
  377. return FieldToString(bytes, String.Empty);
  378. }
  379. /// <summary>
  380. /// Convert a variable length field (byte array) to a string, with a
  381. /// field name prepended to each line of the output
  382. /// </summary>
  383. /// <remarks>If the byte array has unprintable characters in it, a
  384. /// hex dump will be put in the string instead</remarks>
  385. /// <param name="bytes">The byte array to convert to a string</param>
  386. /// <param name="fieldName">A field name to prepend to each line of output</param>
  387. /// <returns>An ASCII string or a string containing a hex dump, minus
  388. /// the null terminator</returns>
  389. public static string FieldToString(byte[] bytes, string fieldName)
  390. {
  391. // Check for a common case
  392. if (bytes.Length == 0) return String.Empty;
  393. StringBuilder output = new StringBuilder();
  394. bool printable = true;
  395. for (int i = 0; i < bytes.Length; ++i)
  396. {
  397. // Check if there are any unprintable characters in the array
  398. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  399. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  400. {
  401. printable = false;
  402. break;
  403. }
  404. }
  405. if (printable)
  406. {
  407. if (fieldName.Length > 0)
  408. {
  409. output.Append(fieldName);
  410. output.Append(": ");
  411. }
  412. output.Append(CleanString(Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  413. }
  414. else
  415. {
  416. for (int i = 0; i < bytes.Length; i += 16)
  417. {
  418. if (i != 0)
  419. output.Append(Environment.NewLine);
  420. if (fieldName.Length > 0)
  421. {
  422. output.Append(fieldName);
  423. output.Append(": ");
  424. }
  425. for (int j = 0; j < 16; j++)
  426. {
  427. if ((i + j) < bytes.Length)
  428. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  429. else
  430. output.Append(" ");
  431. }
  432. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  433. {
  434. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  435. output.Append((char) bytes[i + j]);
  436. else
  437. output.Append(".");
  438. }
  439. }
  440. }
  441. return output.ToString();
  442. }
  443. /// <summary>
  444. /// Converts a URL to a IPAddress
  445. /// </summary>
  446. /// <param name="url">URL Standard Format</param>
  447. /// <returns>A resolved IP Address</returns>
  448. public static IPAddress GetHostFromURL(string url)
  449. {
  450. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  451. }
  452. /// <summary>
  453. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  454. /// </summary>
  455. /// <param name="dnsAddress">DNS Hostname</param>
  456. /// <returns>An IP address, or null</returns>
  457. public static IPAddress GetHostFromDNS(string dnsAddress)
  458. {
  459. // Is it already a valid IP? No need to look it up.
  460. IPAddress ipa;
  461. if (IPAddress.TryParse(dnsAddress, out ipa))
  462. return ipa;
  463. IPAddress[] hosts = null;
  464. // Not an IP, lookup required
  465. try
  466. {
  467. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  468. }
  469. catch (Exception e)
  470. {
  471. m_log.ErrorFormat("[UTIL]: An error occurred while resolving {0}, {1}", dnsAddress, e);
  472. // Still going to throw the exception on for now, since this was what was happening in the first place
  473. throw e;
  474. }
  475. foreach (IPAddress host in hosts)
  476. {
  477. if (host.AddressFamily == AddressFamily.InterNetwork)
  478. {
  479. return host;
  480. }
  481. }
  482. if (hosts.Length > 0)
  483. return hosts[0];
  484. return null;
  485. }
  486. public static Uri GetURI(string protocol, string hostname, int port, string path)
  487. {
  488. return new UriBuilder(protocol, hostname, port, path).Uri;
  489. }
  490. /// <summary>
  491. /// Gets a list of all local system IP addresses
  492. /// </summary>
  493. /// <returns></returns>
  494. public static IPAddress[] GetLocalHosts()
  495. {
  496. return Dns.GetHostAddresses(Dns.GetHostName());
  497. }
  498. public static IPAddress GetLocalHost()
  499. {
  500. string dnsAddress = "localhost";
  501. IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  502. foreach (IPAddress host in hosts)
  503. {
  504. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  505. {
  506. return host;
  507. }
  508. }
  509. if (hosts.Length > 0)
  510. {
  511. foreach (IPAddress host in hosts)
  512. {
  513. if (host.AddressFamily == AddressFamily.InterNetwork)
  514. return host;
  515. }
  516. // Well all else failed...
  517. return hosts[0];
  518. }
  519. return null;
  520. }
  521. /// <summary>
  522. /// Removes all invalid path chars (OS dependent)
  523. /// </summary>
  524. /// <param name="path">path</param>
  525. /// <returns>safe path</returns>
  526. public static string safePath(string path)
  527. {
  528. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  529. }
  530. /// <summary>
  531. /// Removes all invalid filename chars (OS dependent)
  532. /// </summary>
  533. /// <param name="path">filename</param>
  534. /// <returns>safe filename</returns>
  535. public static string safeFileName(string filename)
  536. {
  537. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  538. ;
  539. }
  540. //
  541. // directory locations
  542. //
  543. public static string homeDir()
  544. {
  545. string temp;
  546. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  547. // temp = Path.Combine(personal,".OpenSim");
  548. temp = ".";
  549. return temp;
  550. }
  551. public static string assetsDir()
  552. {
  553. return Path.Combine(configDir(), "assets");
  554. }
  555. public static string inventoryDir()
  556. {
  557. return Path.Combine(configDir(), "inventory");
  558. }
  559. public static string configDir()
  560. {
  561. return ".";
  562. }
  563. public static string dataDir()
  564. {
  565. return ".";
  566. }
  567. public static string logDir()
  568. {
  569. return ".";
  570. }
  571. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  572. public static string GetUniqueFilename(string FileName)
  573. {
  574. int count = 0;
  575. string Name;
  576. if (File.Exists(FileName))
  577. {
  578. FileInfo f = new FileInfo(FileName);
  579. if (!String.IsNullOrEmpty(f.Extension))
  580. {
  581. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  582. }
  583. else
  584. {
  585. Name = f.FullName;
  586. }
  587. while (File.Exists(FileName))
  588. {
  589. count++;
  590. FileName = Name + count + f.Extension;
  591. }
  592. }
  593. return FileName;
  594. }
  595. // Nini (config) related Methods
  596. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  597. {
  598. if (!File.Exists(fileName))
  599. {
  600. //create new file
  601. }
  602. XmlConfigSource config = new XmlConfigSource(fileName);
  603. AddDataRowToConfig(config, row);
  604. config.Save();
  605. return config;
  606. }
  607. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  608. {
  609. config.Configs.Add((string) row[0]);
  610. for (int i = 0; i < row.Table.Columns.Count; i++)
  611. {
  612. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  613. }
  614. }
  615. public static float Clip(float x, float min, float max)
  616. {
  617. return Math.Min(Math.Max(x, min), max);
  618. }
  619. public static int Clip(int x, int min, int max)
  620. {
  621. return Math.Min(Math.Max(x, min), max);
  622. }
  623. /// <summary>
  624. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  625. /// </summary>
  626. /// <param name="UUID"></param>
  627. /// <returns></returns>
  628. public static String ToRawUuidString(UUID UUID)
  629. {
  630. return UUID.Guid.ToString("n");
  631. }
  632. public static string CleanString(string input)
  633. {
  634. if (input.Length == 0)
  635. return input;
  636. int clip = input.Length;
  637. // Test for ++ string terminator
  638. int pos = input.IndexOf("\0");
  639. if (pos != -1 && pos < clip)
  640. clip = pos;
  641. // Test for CR
  642. pos = input.IndexOf("\r");
  643. if (pos != -1 && pos < clip)
  644. clip = pos;
  645. // Test for LF
  646. pos = input.IndexOf("\n");
  647. if (pos != -1 && pos < clip)
  648. clip = pos;
  649. // Truncate string before first end-of-line character found
  650. return input.Substring(0, clip);
  651. }
  652. /// <summary>
  653. /// returns the contents of /etc/issue on Unix Systems
  654. /// Use this for where it's absolutely necessary to implement platform specific stuff
  655. /// </summary>
  656. /// <returns></returns>
  657. public static string ReadEtcIssue()
  658. {
  659. try
  660. {
  661. StreamReader sr = new StreamReader("/etc/issue.net");
  662. string issue = sr.ReadToEnd();
  663. sr.Close();
  664. return issue;
  665. }
  666. catch (Exception)
  667. {
  668. return "";
  669. }
  670. }
  671. public static void SerializeToFile(string filename, Object obj)
  672. {
  673. IFormatter formatter = new BinaryFormatter();
  674. Stream stream = null;
  675. try
  676. {
  677. stream = new FileStream(
  678. filename, FileMode.Create,
  679. FileAccess.Write, FileShare.None);
  680. formatter.Serialize(stream, obj);
  681. }
  682. catch (Exception e)
  683. {
  684. m_log.Error(e.ToString());
  685. }
  686. finally
  687. {
  688. if (stream != null)
  689. {
  690. stream.Close();
  691. }
  692. }
  693. }
  694. public static Object DeserializeFromFile(string filename)
  695. {
  696. IFormatter formatter = new BinaryFormatter();
  697. Stream stream = null;
  698. Object ret = null;
  699. try
  700. {
  701. stream = new FileStream(
  702. filename, FileMode.Open,
  703. FileAccess.Read, FileShare.None);
  704. ret = formatter.Deserialize(stream);
  705. }
  706. catch (Exception e)
  707. {
  708. m_log.Error(e.ToString());
  709. }
  710. finally
  711. {
  712. if (stream != null)
  713. {
  714. stream.Close();
  715. }
  716. }
  717. return ret;
  718. }
  719. public static string Compress(string text)
  720. {
  721. byte[] buffer = Encoding.UTF8.GetBytes(text);
  722. MemoryStream memory = new MemoryStream();
  723. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  724. {
  725. compressor.Write(buffer, 0, buffer.Length);
  726. }
  727. memory.Position = 0;
  728. byte[] compressed = new byte[memory.Length];
  729. memory.Read(compressed, 0, compressed.Length);
  730. byte[] compressedBuffer = new byte[compressed.Length + 4];
  731. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  732. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  733. return Convert.ToBase64String(compressedBuffer);
  734. }
  735. public static string Decompress(string compressedText)
  736. {
  737. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  738. using (MemoryStream memory = new MemoryStream())
  739. {
  740. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  741. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  742. byte[] buffer = new byte[msgLength];
  743. memory.Position = 0;
  744. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  745. {
  746. decompressor.Read(buffer, 0, buffer.Length);
  747. }
  748. return Encoding.UTF8.GetString(buffer);
  749. }
  750. }
  751. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  752. {
  753. return SendXmlRpcCommand(url, methodName, args);
  754. }
  755. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  756. {
  757. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  758. return client.Send(url, 6000);
  759. }
  760. /// <summary>
  761. /// Returns an error message that the user could not be found in the database
  762. /// </summary>
  763. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  764. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  765. {
  766. XmlRpcResponse response = new XmlRpcResponse();
  767. Hashtable responseData = new Hashtable();
  768. responseData["error_type"] = "unknown_user";
  769. responseData["error_desc"] = "The user requested is not in the database";
  770. response.Value = responseData;
  771. return response;
  772. }
  773. /// <summary>
  774. /// Converts a byte array in big endian order into an ulong.
  775. /// </summary>
  776. /// <param name="bytes">
  777. /// The array of bytes
  778. /// </param>
  779. /// <returns>
  780. /// The extracted ulong
  781. /// </returns>
  782. public static ulong BytesToUInt64Big(byte[] bytes)
  783. {
  784. if (bytes.Length < 8) return 0;
  785. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  786. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  787. }
  788. // used for RemoteParcelRequest (for "About Landmark")
  789. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  790. {
  791. byte[] bytes =
  792. {
  793. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  794. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  795. (byte)x, (byte)(x >> 8), 0, 0,
  796. (byte)y, (byte)(y >> 8), 0, 0 };
  797. return new UUID(bytes, 0);
  798. }
  799. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  800. {
  801. byte[] bytes =
  802. {
  803. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  804. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  805. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  806. (byte)y, (byte)(y >> 8), 0, 0 };
  807. return new UUID(bytes, 0);
  808. }
  809. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  810. {
  811. byte[] bytes = parcelID.GetBytes();
  812. regionHandle = Utils.BytesToUInt64(bytes);
  813. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  814. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  815. }
  816. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  817. {
  818. byte[] bytes = parcelID.GetBytes();
  819. regionHandle = Utils.BytesToUInt64(bytes);
  820. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  821. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  822. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  823. }
  824. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  825. {
  826. ulong regionHandle;
  827. uint rx, ry;
  828. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  829. Utils.LongToUInts(regionHandle, out rx, out ry);
  830. x += rx;
  831. y += ry;
  832. }
  833. /// <summary>
  834. /// Get operating system information if available. Returns only the first 45 characters of information
  835. /// </summary>
  836. /// <returns>
  837. /// Operating system information. Returns an empty string if none was available.
  838. /// </returns>
  839. public static string GetOperatingSystemInformation()
  840. {
  841. string os = String.Empty;
  842. if (Environment.OSVersion.Platform != PlatformID.Unix)
  843. {
  844. os = Environment.OSVersion.ToString();
  845. }
  846. else
  847. {
  848. os = ReadEtcIssue();
  849. }
  850. if (os.Length > 45)
  851. {
  852. os = os.Substring(0, 45);
  853. }
  854. return os;
  855. }
  856. /// <summary>
  857. /// Is the given string a UUID?
  858. /// </summary>
  859. /// <param name="s"></param>
  860. /// <returns></returns>
  861. public static bool isUUID(string s)
  862. {
  863. return UUIDPattern.IsMatch(s);
  864. }
  865. public static string GetDisplayConnectionString(string connectionString)
  866. {
  867. int passPosition = 0;
  868. int passEndPosition = 0;
  869. string displayConnectionString = null;
  870. // hide the password in the connection string
  871. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  872. passPosition = connectionString.IndexOf("=", passPosition);
  873. if (passPosition < connectionString.Length)
  874. passPosition += 1;
  875. passEndPosition = connectionString.IndexOf(";", passPosition);
  876. displayConnectionString = connectionString.Substring(0, passPosition);
  877. displayConnectionString += "***";
  878. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  879. return displayConnectionString;
  880. }
  881. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  882. {
  883. Type settingsType = settingsClass.GetType();
  884. FieldInfo[] fieldInfos = settingsType.GetFields();
  885. foreach (FieldInfo fieldInfo in fieldInfos)
  886. {
  887. if (!fieldInfo.IsStatic)
  888. {
  889. if (fieldInfo.FieldType == typeof(System.String))
  890. {
  891. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  892. }
  893. else if (fieldInfo.FieldType == typeof(System.Boolean))
  894. {
  895. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  896. }
  897. else if (fieldInfo.FieldType == typeof(System.Int32))
  898. {
  899. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  900. }
  901. else if (fieldInfo.FieldType == typeof(System.Single))
  902. {
  903. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  904. }
  905. else if (fieldInfo.FieldType == typeof(System.UInt32))
  906. {
  907. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  908. }
  909. }
  910. }
  911. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  912. foreach (PropertyInfo propInfo in propertyInfos)
  913. {
  914. if ((propInfo.CanRead) && (propInfo.CanWrite))
  915. {
  916. if (propInfo.PropertyType == typeof(System.String))
  917. {
  918. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  919. }
  920. else if (propInfo.PropertyType == typeof(System.Boolean))
  921. {
  922. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  923. }
  924. else if (propInfo.PropertyType == typeof(System.Int32))
  925. {
  926. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  927. }
  928. else if (propInfo.PropertyType == typeof(System.Single))
  929. {
  930. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  931. }
  932. if (propInfo.PropertyType == typeof(System.UInt32))
  933. {
  934. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  935. }
  936. }
  937. }
  938. return settingsClass;
  939. }
  940. public static string Base64ToString(string str)
  941. {
  942. UTF8Encoding encoder = new UTF8Encoding();
  943. Decoder utf8Decode = encoder.GetDecoder();
  944. byte[] todecode_byte = Convert.FromBase64String(str);
  945. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  946. char[] decoded_char = new char[charCount];
  947. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  948. string result = new String(decoded_char);
  949. return result;
  950. }
  951. public static Guid GetHashGuid(string data, string salt)
  952. {
  953. byte[] hash = ComputeMD5Hash(data + salt);
  954. //string s = BitConverter.ToString(hash);
  955. Guid guid = new Guid(hash);
  956. return guid;
  957. }
  958. public static byte ConvertMaturityToAccessLevel(uint maturity)
  959. {
  960. byte retVal = 0;
  961. switch (maturity)
  962. {
  963. case 0: //PG
  964. retVal = 13;
  965. break;
  966. case 1: //Mature
  967. retVal = 21;
  968. break;
  969. case 2: // Adult
  970. retVal = 42;
  971. break;
  972. }
  973. return retVal;
  974. }
  975. /// <summary>
  976. /// Produces an OSDMap from its string representation on a stream
  977. /// </summary>
  978. /// <param name="data">The stream</param>
  979. /// <param name="length">The size of the data on the stream</param>
  980. /// <returns>The OSDMap or an exception</returns>
  981. public static OSDMap GetOSDMap(Stream stream, int length)
  982. {
  983. byte[] data = new byte[length];
  984. stream.Read(data, 0, length);
  985. string strdata = Encoding.UTF8.GetString(data);
  986. OSDMap args = null;
  987. OSD buffer;
  988. buffer = OSDParser.DeserializeJson(strdata);
  989. if (buffer.Type == OSDType.Map)
  990. {
  991. args = (OSDMap)buffer;
  992. return args;
  993. }
  994. return null;
  995. }
  996. public static string[] Glob(string path)
  997. {
  998. string vol=String.Empty;
  999. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1000. {
  1001. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1002. if (vcomps.Length > 1)
  1003. {
  1004. path = vcomps[1];
  1005. vol = vcomps[0];
  1006. }
  1007. }
  1008. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1009. // Glob
  1010. path = vol;
  1011. if (vol != String.Empty)
  1012. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1013. else
  1014. path = new String(new char[] {Path.DirectorySeparatorChar});
  1015. List<string> paths = new List<string>();
  1016. List<string> found = new List<string>();
  1017. paths.Add(path);
  1018. int compIndex = -1;
  1019. foreach (string c in comps)
  1020. {
  1021. compIndex++;
  1022. List<string> addpaths = new List<string>();
  1023. foreach (string p in paths)
  1024. {
  1025. string[] dirs = Directory.GetDirectories(p, c);
  1026. if (dirs.Length != 0)
  1027. {
  1028. foreach (string dir in dirs)
  1029. addpaths.Add(Path.Combine(path, dir));
  1030. }
  1031. // Only add files if that is the last path component
  1032. if (compIndex == comps.Length - 1)
  1033. {
  1034. string[] files = Directory.GetFiles(p, c);
  1035. foreach (string f in files)
  1036. found.Add(f);
  1037. }
  1038. }
  1039. paths = addpaths;
  1040. }
  1041. return found.ToArray();
  1042. }
  1043. #region FireAndForget Threading Pattern
  1044. public static void FireAndForget(System.Threading.WaitCallback callback)
  1045. {
  1046. callback.BeginInvoke(null, EndFireAndForget, callback);
  1047. }
  1048. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1049. {
  1050. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1051. }
  1052. private static void EndFireAndForget(IAsyncResult ar)
  1053. {
  1054. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1055. callback.EndInvoke(ar);
  1056. ar.AsyncWaitHandle.Close();
  1057. }
  1058. #endregion FireAndForget Threading Pattern
  1059. }
  1060. }