Util.cs 21 KB

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