Util.cs 20 KB

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