Util.cs 15 KB

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