Util.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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 OpenSim 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.Data;
  29. using System.IO;
  30. using System.Net;
  31. using System.Net.Sockets;
  32. using System.Reflection;
  33. using System.Runtime.Serialization;
  34. using System.Runtime.Serialization.Formatters.Binary;
  35. using System.Security.Cryptography;
  36. using System.Text;
  37. using System.Text.RegularExpressions;
  38. using System.Xml;
  39. using libsecondlife;
  40. using log4net;
  41. using Nini.Config;
  42. using Nwc.XmlRpc;
  43. namespace OpenSim.Framework
  44. {
  45. /// <summary>
  46. /// Miscellaneous utility functions
  47. /// </summary>
  48. public class Util
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. private static uint nextXferID = 5000;
  52. private static Random randomClass = new Random();
  53. // Get a list of invalid file characters (OS dependent)
  54. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  55. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  56. private static object XferLock = new object();
  57. #region Vector Equations
  58. /// <summary>
  59. /// Get the distance between two 3d vectors
  60. /// </summary>
  61. /// <param name="a">A 3d vector</param>
  62. /// <param name="b">A 3d vector</param>
  63. /// <returns>The distance between the two vectors</returns>
  64. public static double GetDistanceTo(LLVector3 a, LLVector3 b)
  65. {
  66. float dx = a.X - b.X;
  67. float dy = a.Y - b.Y;
  68. float dz = a.Z - b.Z;
  69. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  70. }
  71. /// <summary>
  72. /// Get the magnitude of a 3d vector
  73. /// </summary>
  74. /// <param name="a">A 3d vector</param>
  75. /// <returns>The magnitude of the vector</returns>
  76. public static double GetMagnitude(LLVector3 a)
  77. {
  78. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  79. }
  80. /// <summary>
  81. /// Get a normalized form of a 3d vector
  82. /// </summary>
  83. /// <param name="a">A 3d vector</param>
  84. /// <returns>A new vector which is normalized form of the vector</returns>
  85. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  86. public static LLVector3 GetNormalizedVector(LLVector3 a)
  87. {
  88. if (IsZeroVector(a))
  89. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  90. float Mag = (float) GetMagnitude(a);
  91. return new LLVector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  92. }
  93. /// <summary>
  94. /// Returns if a vector is a zero vector (has all zero components)
  95. /// </summary>
  96. /// <returns></returns>
  97. public static bool IsZeroVector(LLVector3 v)
  98. {
  99. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  100. {
  101. return true;
  102. }
  103. return false;
  104. }
  105. # endregion
  106. public Util()
  107. {
  108. }
  109. public static Random RandomClass
  110. {
  111. get { return randomClass; }
  112. }
  113. public static ulong UIntsToLong(uint X, uint Y)
  114. {
  115. return Helpers.UIntsToLong(X, Y);
  116. }
  117. public static uint GetNextXferID()
  118. {
  119. uint id = 0;
  120. lock (XferLock)
  121. {
  122. id = nextXferID;
  123. nextXferID++;
  124. }
  125. return id;
  126. }
  127. public static string GetFileName(string file)
  128. {
  129. // Return just the filename on UNIX platforms
  130. // TODO: this should be customisable with a prefix, but that's something to do later.
  131. if (Environment.OSVersion.Platform == PlatformID.Unix)
  132. {
  133. return file;
  134. }
  135. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  136. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  137. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  138. {
  139. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  140. {
  141. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  142. }
  143. return "%APPDATA%\\OpenSim\\" + file;
  144. }
  145. // Catch all - covers older windows versions
  146. // (but those probably wont work anyway)
  147. return file;
  148. }
  149. /// <summary>
  150. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  151. ///
  152. /// Please don't delete me even if I appear currently unused!
  153. /// </summary>
  154. /// <param name="rawXml"></param>
  155. /// <returns></returns>
  156. public static string GetFormattedXml(string rawXml)
  157. {
  158. XmlDocument xd = new XmlDocument();
  159. xd.LoadXml(rawXml);
  160. StringBuilder sb = new StringBuilder();
  161. StringWriter sw = new StringWriter(sb);
  162. XmlTextWriter xtw = new XmlTextWriter(sw);
  163. xtw.Formatting = Formatting.Indented;
  164. try
  165. {
  166. xd.WriteTo(xtw);
  167. }
  168. finally
  169. {
  170. xtw.Close();
  171. }
  172. return sb.ToString();
  173. }
  174. public static bool IsEnvironmentSupported(ref string reason)
  175. {
  176. // Must have .NET 2.0 (Generics / libsl)
  177. if (Environment.Version.Major < 2)
  178. {
  179. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  180. return false;
  181. }
  182. // Windows 95/98/ME are unsupported
  183. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  184. Environment.OSVersion.Platform != PlatformID.Win32NT)
  185. {
  186. reason = "Windows 95/98/ME will not run OpenSim";
  187. return false;
  188. }
  189. // Windows 2000 / Pre-SP2 XP
  190. if (Environment.OSVersion.Version.Major == 5 &&
  191. Environment.OSVersion.Version.Minor == 0)
  192. {
  193. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  194. return false;
  195. }
  196. return true;
  197. }
  198. public static int UnixTimeSinceEpoch()
  199. {
  200. return ToUnixTime(DateTime.UtcNow);
  201. }
  202. public static int ToUnixTime(DateTime stamp)
  203. {
  204. TimeSpan t = (stamp.ToUniversalTime() - Convert.ToDateTime("1/1/1970 8:00:00 AM"));
  205. return (int) t.TotalSeconds;
  206. }
  207. public static DateTime ToDateTime(ulong seconds)
  208. {
  209. DateTime epoch = Convert.ToDateTime("1/1/1970 8:00:00 AM");
  210. return epoch.AddSeconds(seconds);
  211. }
  212. public static DateTime ToDateTime(int seconds)
  213. {
  214. DateTime epoch = Convert.ToDateTime("1/1/1970 8:00:00 AM");
  215. return epoch.AddSeconds(seconds);
  216. }
  217. public static string Md5Hash(string pass)
  218. {
  219. MD5 md5 = MD5CryptoServiceProvider.Create();
  220. byte[] dataMd5 = md5.ComputeHash(Encoding.Default.GetBytes(pass));
  221. StringBuilder sb = new StringBuilder();
  222. for (int i = 0; i < dataMd5.Length; i++)
  223. sb.AppendFormat("{0:x2}", dataMd5[i]);
  224. return sb.ToString();
  225. }
  226. public static string GetRandomCapsPath()
  227. {
  228. LLUUID caps = LLUUID.Random();
  229. string capsPath = caps.ToString();
  230. capsPath = capsPath.Remove(capsPath.Length - 4, 4);
  231. return capsPath;
  232. }
  233. public static int fast_distance2d(int x, int y)
  234. {
  235. x = Math.Abs(x);
  236. y = Math.Abs(y);
  237. int min = Math.Min(x, y);
  238. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  239. }
  240. public static string FieldToString(byte[] bytes)
  241. {
  242. return FieldToString(bytes, String.Empty);
  243. }
  244. /// <summary>
  245. /// Convert a variable length field (byte array) to a string, with a
  246. /// field name prepended to each line of the output
  247. /// </summary>
  248. /// <remarks>If the byte array has unprintable characters in it, a
  249. /// hex dump will be put in the string instead</remarks>
  250. /// <param name="bytes">The byte array to convert to a string</param>
  251. /// <param name="fieldName">A field name to prepend to each line of output</param>
  252. /// <returns>An ASCII string or a string containing a hex dump, minus
  253. /// the null terminator</returns>
  254. public static string FieldToString(byte[] bytes, string fieldName)
  255. {
  256. // Check for a common case
  257. if (bytes.Length == 0) return String.Empty;
  258. StringBuilder output = new StringBuilder();
  259. bool printable = true;
  260. for (int i = 0; i < bytes.Length; ++i)
  261. {
  262. // Check if there are any unprintable characters in the array
  263. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  264. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  265. {
  266. printable = false;
  267. break;
  268. }
  269. }
  270. if (printable)
  271. {
  272. if (fieldName.Length > 0)
  273. {
  274. output.Append(fieldName);
  275. output.Append(": ");
  276. }
  277. output.Append(CleanString(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  278. }
  279. else
  280. {
  281. for (int i = 0; i < bytes.Length; i += 16)
  282. {
  283. if (i != 0)
  284. output.Append(Environment.NewLine);
  285. if (fieldName.Length > 0)
  286. {
  287. output.Append(fieldName);
  288. output.Append(": ");
  289. }
  290. for (int j = 0; j < 16; j++)
  291. {
  292. if ((i + j) < bytes.Length)
  293. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  294. else
  295. output.Append(" ");
  296. }
  297. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  298. {
  299. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  300. output.Append((char) bytes[i + j]);
  301. else
  302. output.Append(".");
  303. }
  304. }
  305. }
  306. return output.ToString();
  307. }
  308. /// <summary>
  309. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  310. /// </summary>
  311. /// <param name="dnsAddress">DNS Hostname</param>
  312. /// <returns>An IP address, or null</returns>
  313. public static IPAddress GetHostFromDNS(string dnsAddress)
  314. {
  315. // Is it already a valid IP? No need to look it up.
  316. IPAddress ipa;
  317. if (IPAddress.TryParse(dnsAddress, out ipa))
  318. return ipa;
  319. IPAddress[] hosts = null;
  320. // Not an IP, lookup required
  321. try
  322. {
  323. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  324. }
  325. catch (Exception e)
  326. {
  327. m_log.ErrorFormat("[UTIL]: An error occurred while resolving {0}, {1}", dnsAddress, e);
  328. // Still going to throw the exception on for now, since this was what was happening in the first place
  329. throw e;
  330. }
  331. foreach (IPAddress host in hosts)
  332. {
  333. if (host.AddressFamily == AddressFamily.InterNetwork)
  334. {
  335. return host;
  336. }
  337. }
  338. if (hosts.Length > 0)
  339. return hosts[0];
  340. return null;
  341. }
  342. public static IPAddress GetLocalHost()
  343. {
  344. string dnsAddress = "localhost";
  345. IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  346. foreach (IPAddress host in hosts)
  347. {
  348. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  349. {
  350. return host;
  351. }
  352. }
  353. if (hosts.Length > 0)
  354. return hosts[0];
  355. return null;
  356. }
  357. /// <summary>
  358. /// Removes all invalid path chars (OS dependent)
  359. /// </summary>
  360. /// <param name="path">path</param>
  361. /// <returns>safe path</returns>
  362. public static string safePath(string path)
  363. {
  364. return Regex.Replace(path, @regexInvalidPathChars, string.Empty);
  365. }
  366. /// <summary>
  367. /// Removes all invalid filename chars (OS dependent)
  368. /// </summary>
  369. /// <param name="path">filename</param>
  370. /// <returns>safe filename</returns>
  371. public static string safeFileName(string filename)
  372. {
  373. return Regex.Replace(filename, @regexInvalidFileChars, string.Empty);
  374. ;
  375. }
  376. //
  377. // directory locations
  378. //
  379. public static string homeDir()
  380. {
  381. string temp;
  382. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  383. // temp = Path.Combine(personal,".OpenSim");
  384. temp = ".";
  385. return temp;
  386. }
  387. public static string assetsDir()
  388. {
  389. return Path.Combine(configDir(), "assets");
  390. }
  391. public static string inventoryDir()
  392. {
  393. return Path.Combine(configDir(), "inventory");
  394. }
  395. public static string configDir()
  396. {
  397. return ".";
  398. }
  399. public static string dataDir()
  400. {
  401. return ".";
  402. }
  403. public static string logDir()
  404. {
  405. return ".";
  406. }
  407. // Nini (config) related Methods
  408. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  409. {
  410. if (!File.Exists(fileName))
  411. {
  412. //create new file
  413. }
  414. XmlConfigSource config = new XmlConfigSource(fileName);
  415. AddDataRowToConfig(config, row);
  416. config.Save();
  417. return config;
  418. }
  419. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  420. {
  421. config.Configs.Add((string) row[0]);
  422. for (int i = 0; i < row.Table.Columns.Count; i++)
  423. {
  424. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  425. }
  426. }
  427. public static float Clip(float x, float min, float max)
  428. {
  429. return Math.Min(Math.Max(x, min), max);
  430. }
  431. public static int Clip(int x, int min, int max)
  432. {
  433. return Math.Min(Math.Max(x, min), max);
  434. }
  435. /// <summary>
  436. /// Convert an LLUUID to a raw uuid string. Right now this is a string without hyphens.
  437. /// </summary>
  438. /// <param name="lluuid"></param>
  439. /// <returns></returns>
  440. public static String ToRawUuidString(LLUUID lluuid)
  441. {
  442. return lluuid.UUID.ToString("n");
  443. }
  444. public static string CleanString(string input)
  445. {
  446. if (input.Length == 0)
  447. return input;
  448. int clip = input.Length;
  449. // Test for ++ string terminator
  450. int pos = input.IndexOf("\0");
  451. if (pos != -1 && pos < clip)
  452. clip = pos;
  453. // Test for CR
  454. pos = input.IndexOf("\r");
  455. if (pos != -1 && pos < clip)
  456. clip = pos;
  457. // Test for LF
  458. pos = input.IndexOf("\n");
  459. if (pos != -1 && pos < clip)
  460. clip = pos;
  461. // Truncate string before first end-of-line character found
  462. return input.Substring(0, clip);
  463. }
  464. /// <summary>
  465. /// returns the contents of /etc/issue on Unix Systems
  466. /// Use this for where it's absolutely necessary to implement platform specific stuff
  467. /// </summary>
  468. /// <returns></returns>
  469. public static string ReadEtcIssue()
  470. {
  471. try
  472. {
  473. StreamReader sr = new StreamReader("/etc/issue.net");
  474. string issue = sr.ReadToEnd();
  475. sr.Close();
  476. return issue;
  477. }
  478. catch (Exception)
  479. {
  480. return "";
  481. }
  482. }
  483. public static void SerializeToFile(string filename, Object obj)
  484. {
  485. IFormatter formatter = new BinaryFormatter();
  486. Stream stream = null;
  487. try
  488. {
  489. stream = new FileStream(
  490. filename, FileMode.Create,
  491. FileAccess.Write, FileShare.None);
  492. formatter.Serialize(stream, obj);
  493. }
  494. catch (Exception e)
  495. {
  496. System.Console.WriteLine(e.Message);
  497. System.Console.WriteLine(e.StackTrace);
  498. }
  499. finally
  500. {
  501. if (stream != null)
  502. {
  503. stream.Close();
  504. }
  505. }
  506. }
  507. public static Object DeserializeFromFile(string filename)
  508. {
  509. IFormatter formatter = new BinaryFormatter();
  510. Stream stream = null;
  511. Object ret = null;
  512. try
  513. {
  514. stream = new FileStream(
  515. filename, FileMode.Open,
  516. FileAccess.Read, FileShare.None);
  517. ret = formatter.Deserialize(stream);
  518. }
  519. catch (Exception e)
  520. {
  521. System.Console.WriteLine(e.Message);
  522. System.Console.WriteLine(e.StackTrace);
  523. }
  524. finally
  525. {
  526. if (stream != null)
  527. {
  528. stream.Close();
  529. }
  530. }
  531. return ret;
  532. }
  533. public static string[] ParseStartLocationRequest(string startLocationRequest)
  534. {
  535. string[] returnstring = new string[4];
  536. // format uri:RegionName&X&Y&Z
  537. returnstring[0] = "last";
  538. returnstring[1] = "127";
  539. returnstring[2] = "127";
  540. returnstring[3] = "0";
  541. // This is the crappy way of doing it.
  542. if (startLocationRequest.Contains(":") && startLocationRequest.Contains("&"))
  543. {
  544. //System.Console.WriteLine("StartLocationRequest Contains proper elements");
  545. string[] splitstr = startLocationRequest.Split(':'); //,2,StringSplitOptions.RemoveEmptyEntries);
  546. //System.Console.WriteLine("Found " + splitstr.GetLength(0) + " elements in 1st split result");
  547. if (splitstr.GetLength(0) == 2)
  548. {
  549. string[] splitstr2 = splitstr[1].Split('&'); //, 4, StringSplitOptions.RemoveEmptyEntries);
  550. //System.Console.WriteLine("Found " + splitstr2.GetLength(0) + " elements in 2nd split result");
  551. int len = Math.Min(splitstr2.GetLength(0), 4);
  552. for (int i = 0; i < 4; ++i)
  553. {
  554. if (len > i)
  555. {
  556. returnstring[i] = splitstr2[i];
  557. }
  558. }
  559. }
  560. }
  561. return returnstring;
  562. }
  563. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  564. {
  565. return SendXmlRpcCommand(url, methodName, args);
  566. }
  567. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  568. {
  569. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  570. return client.Send(url, 6000);
  571. }
  572. }
  573. }