Util.cs 40 KB

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