Util.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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. }
  967. }