Util.cs 16 KB

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