Util.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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 OpenSimulator 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;
  29. using System.Collections.Generic;
  30. using System.Data;
  31. using System.Diagnostics;
  32. using System.Globalization;
  33. using System.IO;
  34. using System.IO.Compression;
  35. using System.Net;
  36. using System.Net.Sockets;
  37. using System.Reflection;
  38. using System.Runtime.Serialization;
  39. using System.Runtime.Serialization.Formatters.Binary;
  40. using System.Security.Cryptography;
  41. using System.Text;
  42. using System.Text.RegularExpressions;
  43. using System.Xml;
  44. using System.Threading;
  45. using log4net;
  46. using Nini.Config;
  47. using Nwc.XmlRpc;
  48. using OpenMetaverse;
  49. using OpenMetaverse.StructuredData;
  50. using Amib.Threading;
  51. namespace OpenSim.Framework
  52. {
  53. /// <summary>
  54. /// The method used by Util.FireAndForget for asynchronously firing events
  55. /// </summary>
  56. /// <remarks>
  57. /// None is used to execute the method in the same thread that made the call. It should only be used by regression
  58. /// test code that relies on predictable event ordering.
  59. /// </remarks>
  60. public enum FireAndForgetMethod
  61. {
  62. None,
  63. UnsafeQueueUserWorkItem,
  64. QueueUserWorkItem,
  65. BeginInvoke,
  66. SmartThreadPool,
  67. Thread,
  68. }
  69. /// <summary>
  70. /// Miscellaneous utility functions
  71. /// </summary>
  72. public class Util
  73. {
  74. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  75. private static uint nextXferID = 5000;
  76. private static Random randomClass = new Random();
  77. // Get a list of invalid file characters (OS dependent)
  78. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  79. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  80. private static object XferLock = new object();
  81. /// <summary>Thread pool used for Util.FireAndForget if
  82. /// FireAndForgetMethod.SmartThreadPool is used</summary>
  83. private static SmartThreadPool m_ThreadPool;
  84. // Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC.
  85. private static readonly DateTime unixEpoch =
  86. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  87. private static readonly string rawUUIDPattern
  88. = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
  89. public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
  90. public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
  91. public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  92. public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
  93. /// <summary>
  94. /// Gets the name of the directory where the current running executable
  95. /// is located
  96. /// </summary>
  97. /// <returns>Filesystem path to the directory containing the current
  98. /// executable</returns>
  99. public static string ExecutingDirectory()
  100. {
  101. return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  102. }
  103. /// <summary>
  104. /// Linear interpolates B<->C using percent A
  105. /// </summary>
  106. /// <param name="a"></param>
  107. /// <param name="b"></param>
  108. /// <param name="c"></param>
  109. /// <returns></returns>
  110. public static double lerp(double a, double b, double c)
  111. {
  112. return (b*a) + (c*(1 - a));
  113. }
  114. /// <summary>
  115. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  116. /// Layout:
  117. /// A B
  118. /// C D
  119. /// A<->C = Y
  120. /// C<->D = X
  121. /// </summary>
  122. /// <param name="x"></param>
  123. /// <param name="y"></param>
  124. /// <param name="a"></param>
  125. /// <param name="b"></param>
  126. /// <param name="c"></param>
  127. /// <param name="d"></param>
  128. /// <returns></returns>
  129. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  130. {
  131. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  132. }
  133. public static Encoding UTF8 = Encoding.UTF8;
  134. /// <value>
  135. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  136. /// </value>
  137. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  138. #region Vector Equations
  139. /// <summary>
  140. /// Get the distance between two 3d vectors
  141. /// </summary>
  142. /// <param name="a">A 3d vector</param>
  143. /// <param name="b">A 3d vector</param>
  144. /// <returns>The distance between the two vectors</returns>
  145. public static double GetDistanceTo(Vector3 a, Vector3 b)
  146. {
  147. float dx = a.X - b.X;
  148. float dy = a.Y - b.Y;
  149. float dz = a.Z - b.Z;
  150. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  151. }
  152. /// <summary>
  153. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  154. /// </summary>
  155. /// <param name="a"></param>
  156. /// <param name="b"></param>
  157. /// <param name="amount"></param>
  158. /// <returns></returns>
  159. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  160. {
  161. float dx = a.X - b.X;
  162. float dy = a.Y - b.Y;
  163. float dz = a.Z - b.Z;
  164. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  165. }
  166. /// <summary>
  167. /// Get the magnitude of a 3d vector
  168. /// </summary>
  169. /// <param name="a">A 3d vector</param>
  170. /// <returns>The magnitude of the vector</returns>
  171. public static double GetMagnitude(Vector3 a)
  172. {
  173. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  174. }
  175. /// <summary>
  176. /// Get a normalized form of a 3d vector
  177. /// </summary>
  178. /// <param name="a">A 3d vector</param>
  179. /// <returns>A new vector which is normalized form of the vector</returns>
  180. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  181. public static Vector3 GetNormalizedVector(Vector3 a)
  182. {
  183. if (IsZeroVector(a))
  184. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  185. float Mag = (float) GetMagnitude(a);
  186. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  187. }
  188. /// <summary>
  189. /// Returns if a vector is a zero vector (has all zero components)
  190. /// </summary>
  191. /// <returns></returns>
  192. public static bool IsZeroVector(Vector3 v)
  193. {
  194. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  195. {
  196. return true;
  197. }
  198. return false;
  199. }
  200. # endregion
  201. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  202. {
  203. float s;
  204. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  205. if (tr >= 1.0)
  206. {
  207. s = (float) (0.5 / Math.Sqrt(tr));
  208. return new Quaternion(
  209. (left.Z - up.Y) * s,
  210. (up.X - fwd.Z) * s,
  211. (fwd.Y - left.X) * s,
  212. (float) 0.25 / s);
  213. }
  214. else
  215. {
  216. float max = (left.Y > up.Z) ? left.Y : up.Z;
  217. if (max < fwd.X)
  218. {
  219. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  220. float x = (float) (s * 0.5);
  221. s = (float) (0.5 / s);
  222. return new Quaternion(
  223. x,
  224. (fwd.Y + left.X) * s,
  225. (up.X + fwd.Z) * s,
  226. (left.Z - up.Y) * s);
  227. }
  228. else if (max == left.Y)
  229. {
  230. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  231. float y = (float) (s * 0.5);
  232. s = (float) (0.5 / s);
  233. return new Quaternion(
  234. (fwd.Y + left.X) * s,
  235. y,
  236. (left.Z + up.Y) * s,
  237. (up.X - fwd.Z) * s);
  238. }
  239. else
  240. {
  241. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  242. float z = (float) (s * 0.5);
  243. s = (float) (0.5 / s);
  244. return new Quaternion(
  245. (up.X + fwd.Z) * s,
  246. (left.Z + up.Y) * s,
  247. z,
  248. (fwd.Y - left.X) * s);
  249. }
  250. }
  251. }
  252. public static Random RandomClass
  253. {
  254. get { return randomClass; }
  255. }
  256. public static ulong UIntsToLong(uint X, uint Y)
  257. {
  258. return Utils.UIntsToLong(X, Y);
  259. }
  260. public static T Clamp<T>(T x, T min, T max)
  261. where T : IComparable<T>
  262. {
  263. return x.CompareTo(max) > 0 ? max :
  264. x.CompareTo(min) < 0 ? min :
  265. x;
  266. }
  267. public static uint GetNextXferID()
  268. {
  269. uint id = 0;
  270. lock (XferLock)
  271. {
  272. id = nextXferID;
  273. nextXferID++;
  274. }
  275. return id;
  276. }
  277. public static string GetFileName(string file)
  278. {
  279. // Return just the filename on UNIX platforms
  280. // TODO: this should be customisable with a prefix, but that's something to do later.
  281. if (Environment.OSVersion.Platform == PlatformID.Unix)
  282. {
  283. return file;
  284. }
  285. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  286. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  287. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  288. {
  289. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  290. {
  291. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  292. }
  293. return "%APPDATA%\\OpenSim\\" + file;
  294. }
  295. // Catch all - covers older windows versions
  296. // (but those probably wont work anyway)
  297. return file;
  298. }
  299. /// <summary>
  300. /// Debug utility function to convert OSD into formatted XML for debugging purposes.
  301. /// </summary>
  302. /// <param name="osd">
  303. /// A <see cref="OSD"/>
  304. /// </param>
  305. /// <returns>
  306. /// A <see cref="System.String"/>
  307. /// </returns>
  308. public static string GetFormattedXml(OSD osd)
  309. {
  310. return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
  311. }
  312. /// <summary>
  313. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  314. /// </summary>
  315. /// <remarks>
  316. /// Please don't delete me even if I appear currently unused!
  317. /// </remarks>
  318. /// <param name="rawXml"></param>
  319. /// <returns></returns>
  320. public static string GetFormattedXml(string rawXml)
  321. {
  322. XmlDocument xd = new XmlDocument();
  323. xd.LoadXml(rawXml);
  324. StringBuilder sb = new StringBuilder();
  325. StringWriter sw = new StringWriter(sb);
  326. XmlTextWriter xtw = new XmlTextWriter(sw);
  327. xtw.Formatting = Formatting.Indented;
  328. try
  329. {
  330. xd.WriteTo(xtw);
  331. }
  332. finally
  333. {
  334. xtw.Close();
  335. }
  336. return sb.ToString();
  337. }
  338. public static bool IsEnvironmentSupported(ref string reason)
  339. {
  340. // Must have .NET 2.0 (Generics / libsl)
  341. if (Environment.Version.Major < 2)
  342. {
  343. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  344. return false;
  345. }
  346. // Windows 95/98/ME are unsupported
  347. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  348. Environment.OSVersion.Platform != PlatformID.Win32NT)
  349. {
  350. reason = "Windows 95/98/ME will not run OpenSim";
  351. return false;
  352. }
  353. // Windows 2000 / Pre-SP2 XP
  354. if (Environment.OSVersion.Version.Major == 5 &&
  355. Environment.OSVersion.Version.Minor == 0)
  356. {
  357. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  358. return false;
  359. }
  360. return true;
  361. }
  362. public static int UnixTimeSinceEpoch()
  363. {
  364. return ToUnixTime(DateTime.UtcNow);
  365. }
  366. public static int ToUnixTime(DateTime stamp)
  367. {
  368. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  369. return (int) t.TotalSeconds;
  370. }
  371. public static DateTime ToDateTime(ulong seconds)
  372. {
  373. DateTime epoch = unixEpoch;
  374. return epoch.AddSeconds(seconds);
  375. }
  376. public static DateTime ToDateTime(int seconds)
  377. {
  378. DateTime epoch = unixEpoch;
  379. return epoch.AddSeconds(seconds);
  380. }
  381. /// <summary>
  382. /// Return an md5 hash of the given string
  383. /// </summary>
  384. /// <param name="data"></param>
  385. /// <returns></returns>
  386. public static string Md5Hash(string data)
  387. {
  388. byte[] dataMd5 = ComputeMD5Hash(data);
  389. StringBuilder sb = new StringBuilder();
  390. for (int i = 0; i < dataMd5.Length; i++)
  391. sb.AppendFormat("{0:x2}", dataMd5[i]);
  392. return sb.ToString();
  393. }
  394. private static byte[] ComputeMD5Hash(string data)
  395. {
  396. MD5 md5 = MD5.Create();
  397. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  398. }
  399. /// <summary>
  400. /// Return an SHA1 hash
  401. /// </summary>
  402. /// <param name="data"></param>
  403. /// <returns></returns>
  404. public static string SHA1Hash(string data)
  405. {
  406. return SHA1Hash(Encoding.Default.GetBytes(data));
  407. }
  408. /// <summary>
  409. /// Return an SHA1 hash
  410. /// </summary>
  411. /// <param name="data"></param>
  412. /// <returns></returns>
  413. public static string SHA1Hash(byte[] data)
  414. {
  415. byte[] hash = ComputeSHA1Hash(data);
  416. return BitConverter.ToString(hash).Replace("-", String.Empty);
  417. }
  418. private static byte[] ComputeSHA1Hash(byte[] src)
  419. {
  420. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  421. return SHA1.ComputeHash(src);
  422. }
  423. public static int fast_distance2d(int x, int y)
  424. {
  425. x = Math.Abs(x);
  426. y = Math.Abs(y);
  427. int min = Math.Min(x, y);
  428. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  429. }
  430. /// <summary>
  431. /// Are the co-ordinates of the new region visible from the old region?
  432. /// </summary>
  433. /// <param name="oldx">Old region x-coord</param>
  434. /// <param name="newx">New region x-coord</param>
  435. /// <param name="oldy">Old region y-coord</param>
  436. /// <param name="newy">New region y-coord</param>
  437. /// <returns></returns>
  438. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy)
  439. {
  440. int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize);
  441. int startX = (int)oldx - dd;
  442. int startY = (int)oldy - dd;
  443. int endX = (int)oldx + dd;
  444. int endY = (int)oldy + dd;
  445. return (newx < startX || endX < newx || newy < startY || endY < newy);
  446. }
  447. public static string FieldToString(byte[] bytes)
  448. {
  449. return FieldToString(bytes, String.Empty);
  450. }
  451. /// <summary>
  452. /// Convert a variable length field (byte array) to a string, with a
  453. /// field name prepended to each line of the output
  454. /// </summary>
  455. /// <remarks>If the byte array has unprintable characters in it, a
  456. /// hex dump will be put in the string instead</remarks>
  457. /// <param name="bytes">The byte array to convert to a string</param>
  458. /// <param name="fieldName">A field name to prepend to each line of output</param>
  459. /// <returns>An ASCII string or a string containing a hex dump, minus
  460. /// the null terminator</returns>
  461. public static string FieldToString(byte[] bytes, string fieldName)
  462. {
  463. // Check for a common case
  464. if (bytes.Length == 0) return String.Empty;
  465. StringBuilder output = new StringBuilder();
  466. bool printable = true;
  467. for (int i = 0; i < bytes.Length; ++i)
  468. {
  469. // Check if there are any unprintable characters in the array
  470. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  471. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  472. {
  473. printable = false;
  474. break;
  475. }
  476. }
  477. if (printable)
  478. {
  479. if (fieldName.Length > 0)
  480. {
  481. output.Append(fieldName);
  482. output.Append(": ");
  483. }
  484. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  485. }
  486. else
  487. {
  488. for (int i = 0; i < bytes.Length; i += 16)
  489. {
  490. if (i != 0)
  491. output.Append(Environment.NewLine);
  492. if (fieldName.Length > 0)
  493. {
  494. output.Append(fieldName);
  495. output.Append(": ");
  496. }
  497. for (int j = 0; j < 16; j++)
  498. {
  499. if ((i + j) < bytes.Length)
  500. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  501. else
  502. output.Append(" ");
  503. }
  504. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  505. {
  506. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  507. output.Append((char) bytes[i + j]);
  508. else
  509. output.Append(".");
  510. }
  511. }
  512. }
  513. return output.ToString();
  514. }
  515. /// <summary>
  516. /// Converts a URL to a IPAddress
  517. /// </summary>
  518. /// <param name="url">URL Standard Format</param>
  519. /// <returns>A resolved IP Address</returns>
  520. public static IPAddress GetHostFromURL(string url)
  521. {
  522. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  523. }
  524. /// <summary>
  525. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  526. /// </summary>
  527. /// <param name="dnsAddress">DNS Hostname</param>
  528. /// <returns>An IP address, or null</returns>
  529. public static IPAddress GetHostFromDNS(string dnsAddress)
  530. {
  531. // Is it already a valid IP? No need to look it up.
  532. IPAddress ipa;
  533. if (IPAddress.TryParse(dnsAddress, out ipa))
  534. return ipa;
  535. IPAddress[] hosts = null;
  536. // Not an IP, lookup required
  537. try
  538. {
  539. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  540. }
  541. catch (Exception e)
  542. {
  543. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  544. // Still going to throw the exception on for now, since this was what was happening in the first place
  545. throw e;
  546. }
  547. foreach (IPAddress host in hosts)
  548. {
  549. if (host.AddressFamily == AddressFamily.InterNetwork)
  550. {
  551. return host;
  552. }
  553. }
  554. if (hosts.Length > 0)
  555. return hosts[0];
  556. return null;
  557. }
  558. public static Uri GetURI(string protocol, string hostname, int port, string path)
  559. {
  560. return new UriBuilder(protocol, hostname, port, path).Uri;
  561. }
  562. /// <summary>
  563. /// Gets a list of all local system IP addresses
  564. /// </summary>
  565. /// <returns></returns>
  566. public static IPAddress[] GetLocalHosts()
  567. {
  568. return Dns.GetHostAddresses(Dns.GetHostName());
  569. }
  570. public static IPAddress GetLocalHost()
  571. {
  572. IPAddress[] iplist = GetLocalHosts();
  573. if (iplist.Length == 0) // No accessible external interfaces
  574. {
  575. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  576. IPAddress localhost = loopback[0];
  577. return localhost;
  578. }
  579. foreach (IPAddress host in iplist)
  580. {
  581. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  582. {
  583. return host;
  584. }
  585. }
  586. if (iplist.Length > 0)
  587. {
  588. foreach (IPAddress host in iplist)
  589. {
  590. if (host.AddressFamily == AddressFamily.InterNetwork)
  591. return host;
  592. }
  593. // Well all else failed...
  594. return iplist[0];
  595. }
  596. return null;
  597. }
  598. /// <summary>
  599. /// Removes all invalid path chars (OS dependent)
  600. /// </summary>
  601. /// <param name="path">path</param>
  602. /// <returns>safe path</returns>
  603. public static string safePath(string path)
  604. {
  605. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  606. }
  607. /// <summary>
  608. /// Removes all invalid filename chars (OS dependent)
  609. /// </summary>
  610. /// <param name="path">filename</param>
  611. /// <returns>safe filename</returns>
  612. public static string safeFileName(string filename)
  613. {
  614. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  615. ;
  616. }
  617. //
  618. // directory locations
  619. //
  620. public static string homeDir()
  621. {
  622. string temp;
  623. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  624. // temp = Path.Combine(personal,".OpenSim");
  625. temp = ".";
  626. return temp;
  627. }
  628. public static string assetsDir()
  629. {
  630. return Path.Combine(configDir(), "assets");
  631. }
  632. public static string inventoryDir()
  633. {
  634. return Path.Combine(configDir(), "inventory");
  635. }
  636. public static string configDir()
  637. {
  638. return ".";
  639. }
  640. public static string dataDir()
  641. {
  642. return ".";
  643. }
  644. public static string logDir()
  645. {
  646. return ".";
  647. }
  648. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  649. public static string GetUniqueFilename(string FileName)
  650. {
  651. int count = 0;
  652. string Name;
  653. if (File.Exists(FileName))
  654. {
  655. FileInfo f = new FileInfo(FileName);
  656. if (!String.IsNullOrEmpty(f.Extension))
  657. {
  658. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  659. }
  660. else
  661. {
  662. Name = f.FullName;
  663. }
  664. while (File.Exists(FileName))
  665. {
  666. count++;
  667. FileName = Name + count + f.Extension;
  668. }
  669. }
  670. return FileName;
  671. }
  672. // Nini (config) related Methods
  673. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  674. {
  675. if (!File.Exists(fileName))
  676. {
  677. //create new file
  678. }
  679. XmlConfigSource config = new XmlConfigSource(fileName);
  680. AddDataRowToConfig(config, row);
  681. config.Save();
  682. return config;
  683. }
  684. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  685. {
  686. config.Configs.Add((string) row[0]);
  687. for (int i = 0; i < row.Table.Columns.Count; i++)
  688. {
  689. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  690. }
  691. }
  692. public static float Clip(float x, float min, float max)
  693. {
  694. return Math.Min(Math.Max(x, min), max);
  695. }
  696. public static int Clip(int x, int min, int max)
  697. {
  698. return Math.Min(Math.Max(x, min), max);
  699. }
  700. /// <summary>
  701. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  702. /// </summary>
  703. /// <param name="UUID"></param>
  704. /// <returns></returns>
  705. public static String ToRawUuidString(UUID UUID)
  706. {
  707. return UUID.Guid.ToString("n");
  708. }
  709. public static string CleanString(string input)
  710. {
  711. if (input.Length == 0)
  712. return input;
  713. int clip = input.Length;
  714. // Test for ++ string terminator
  715. int pos = input.IndexOf("\0");
  716. if (pos != -1 && pos < clip)
  717. clip = pos;
  718. // Test for CR
  719. pos = input.IndexOf("\r");
  720. if (pos != -1 && pos < clip)
  721. clip = pos;
  722. // Test for LF
  723. pos = input.IndexOf("\n");
  724. if (pos != -1 && pos < clip)
  725. clip = pos;
  726. // Truncate string before first end-of-line character found
  727. return input.Substring(0, clip);
  728. }
  729. /// <summary>
  730. /// returns the contents of /etc/issue on Unix Systems
  731. /// Use this for where it's absolutely necessary to implement platform specific stuff
  732. /// </summary>
  733. /// <returns></returns>
  734. public static string ReadEtcIssue()
  735. {
  736. try
  737. {
  738. StreamReader sr = new StreamReader("/etc/issue.net");
  739. string issue = sr.ReadToEnd();
  740. sr.Close();
  741. return issue;
  742. }
  743. catch (Exception)
  744. {
  745. return "";
  746. }
  747. }
  748. public static void SerializeToFile(string filename, Object obj)
  749. {
  750. IFormatter formatter = new BinaryFormatter();
  751. Stream stream = null;
  752. try
  753. {
  754. stream = new FileStream(
  755. filename, FileMode.Create,
  756. FileAccess.Write, FileShare.None);
  757. formatter.Serialize(stream, obj);
  758. }
  759. catch (Exception e)
  760. {
  761. m_log.Error(e.ToString());
  762. }
  763. finally
  764. {
  765. if (stream != null)
  766. {
  767. stream.Close();
  768. }
  769. }
  770. }
  771. public static Object DeserializeFromFile(string filename)
  772. {
  773. IFormatter formatter = new BinaryFormatter();
  774. Stream stream = null;
  775. Object ret = null;
  776. try
  777. {
  778. stream = new FileStream(
  779. filename, FileMode.Open,
  780. FileAccess.Read, FileShare.None);
  781. ret = formatter.Deserialize(stream);
  782. }
  783. catch (Exception e)
  784. {
  785. m_log.Error(e.ToString());
  786. }
  787. finally
  788. {
  789. if (stream != null)
  790. {
  791. stream.Close();
  792. }
  793. }
  794. return ret;
  795. }
  796. public static string Compress(string text)
  797. {
  798. byte[] buffer = Util.UTF8.GetBytes(text);
  799. MemoryStream memory = new MemoryStream();
  800. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  801. {
  802. compressor.Write(buffer, 0, buffer.Length);
  803. }
  804. memory.Position = 0;
  805. byte[] compressed = new byte[memory.Length];
  806. memory.Read(compressed, 0, compressed.Length);
  807. byte[] compressedBuffer = new byte[compressed.Length + 4];
  808. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  809. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  810. return Convert.ToBase64String(compressedBuffer);
  811. }
  812. public static string Decompress(string compressedText)
  813. {
  814. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  815. using (MemoryStream memory = new MemoryStream())
  816. {
  817. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  818. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  819. byte[] buffer = new byte[msgLength];
  820. memory.Position = 0;
  821. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  822. {
  823. decompressor.Read(buffer, 0, buffer.Length);
  824. }
  825. return Util.UTF8.GetString(buffer);
  826. }
  827. }
  828. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  829. {
  830. return SendXmlRpcCommand(url, methodName, args);
  831. }
  832. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  833. {
  834. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  835. return client.Send(url, 6000);
  836. }
  837. /// <summary>
  838. /// Returns an error message that the user could not be found in the database
  839. /// </summary>
  840. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  841. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  842. {
  843. XmlRpcResponse response = new XmlRpcResponse();
  844. Hashtable responseData = new Hashtable();
  845. responseData["error_type"] = "unknown_user";
  846. responseData["error_desc"] = "The user requested is not in the database";
  847. response.Value = responseData;
  848. return response;
  849. }
  850. /// <summary>
  851. /// Converts a byte array in big endian order into an ulong.
  852. /// </summary>
  853. /// <param name="bytes">
  854. /// The array of bytes
  855. /// </param>
  856. /// <returns>
  857. /// The extracted ulong
  858. /// </returns>
  859. public static ulong BytesToUInt64Big(byte[] bytes)
  860. {
  861. if (bytes.Length < 8) return 0;
  862. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  863. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  864. }
  865. // used for RemoteParcelRequest (for "About Landmark")
  866. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  867. {
  868. byte[] bytes =
  869. {
  870. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  871. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  872. (byte)x, (byte)(x >> 8), 0, 0,
  873. (byte)y, (byte)(y >> 8), 0, 0 };
  874. return new UUID(bytes, 0);
  875. }
  876. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  877. {
  878. byte[] bytes =
  879. {
  880. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  881. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  882. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  883. (byte)y, (byte)(y >> 8), 0, 0 };
  884. return new UUID(bytes, 0);
  885. }
  886. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  887. {
  888. byte[] bytes = parcelID.GetBytes();
  889. regionHandle = Utils.BytesToUInt64(bytes);
  890. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  891. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  892. }
  893. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  894. {
  895. byte[] bytes = parcelID.GetBytes();
  896. regionHandle = Utils.BytesToUInt64(bytes);
  897. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  898. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  899. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  900. }
  901. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  902. {
  903. ulong regionHandle;
  904. uint rx, ry;
  905. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  906. Utils.LongToUInts(regionHandle, out rx, out ry);
  907. x += rx;
  908. y += ry;
  909. }
  910. /// <summary>
  911. /// Get operating system information if available. Returns only the first 45 characters of information
  912. /// </summary>
  913. /// <returns>
  914. /// Operating system information. Returns an empty string if none was available.
  915. /// </returns>
  916. public static string GetOperatingSystemInformation()
  917. {
  918. string os = String.Empty;
  919. if (Environment.OSVersion.Platform != PlatformID.Unix)
  920. {
  921. os = Environment.OSVersion.ToString();
  922. }
  923. else
  924. {
  925. os = ReadEtcIssue();
  926. }
  927. if (os.Length > 45)
  928. {
  929. os = os.Substring(0, 45);
  930. }
  931. return os;
  932. }
  933. public static string GetRuntimeInformation()
  934. {
  935. string ru = String.Empty;
  936. if (Environment.OSVersion.Platform == PlatformID.Unix)
  937. ru = "Unix/Mono";
  938. else
  939. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  940. ru = "OSX/Mono";
  941. else
  942. {
  943. if (Type.GetType("Mono.Runtime") != null)
  944. ru = "Win/Mono";
  945. else
  946. ru = "Win/.NET";
  947. }
  948. return ru;
  949. }
  950. /// <summary>
  951. /// Is the given string a UUID?
  952. /// </summary>
  953. /// <param name="s"></param>
  954. /// <returns></returns>
  955. public static bool isUUID(string s)
  956. {
  957. return UUIDPattern.IsMatch(s);
  958. }
  959. public static string GetDisplayConnectionString(string connectionString)
  960. {
  961. int passPosition = 0;
  962. int passEndPosition = 0;
  963. string displayConnectionString = null;
  964. // hide the password in the connection string
  965. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  966. passPosition = connectionString.IndexOf("=", passPosition);
  967. if (passPosition < connectionString.Length)
  968. passPosition += 1;
  969. passEndPosition = connectionString.IndexOf(";", passPosition);
  970. displayConnectionString = connectionString.Substring(0, passPosition);
  971. displayConnectionString += "***";
  972. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  973. return displayConnectionString;
  974. }
  975. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  976. {
  977. Type settingsType = settingsClass.GetType();
  978. FieldInfo[] fieldInfos = settingsType.GetFields();
  979. foreach (FieldInfo fieldInfo in fieldInfos)
  980. {
  981. if (!fieldInfo.IsStatic)
  982. {
  983. if (fieldInfo.FieldType == typeof(System.String))
  984. {
  985. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  986. }
  987. else if (fieldInfo.FieldType == typeof(System.Boolean))
  988. {
  989. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  990. }
  991. else if (fieldInfo.FieldType == typeof(System.Int32))
  992. {
  993. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  994. }
  995. else if (fieldInfo.FieldType == typeof(System.Single))
  996. {
  997. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  998. }
  999. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1000. {
  1001. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1002. }
  1003. }
  1004. }
  1005. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1006. foreach (PropertyInfo propInfo in propertyInfos)
  1007. {
  1008. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1009. {
  1010. if (propInfo.PropertyType == typeof(System.String))
  1011. {
  1012. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1013. }
  1014. else if (propInfo.PropertyType == typeof(System.Boolean))
  1015. {
  1016. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1017. }
  1018. else if (propInfo.PropertyType == typeof(System.Int32))
  1019. {
  1020. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1021. }
  1022. else if (propInfo.PropertyType == typeof(System.Single))
  1023. {
  1024. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1025. }
  1026. if (propInfo.PropertyType == typeof(System.UInt32))
  1027. {
  1028. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1029. }
  1030. }
  1031. }
  1032. return settingsClass;
  1033. }
  1034. public static string Base64ToString(string str)
  1035. {
  1036. UTF8Encoding encoder = new UTF8Encoding();
  1037. Decoder utf8Decode = encoder.GetDecoder();
  1038. byte[] todecode_byte = Convert.FromBase64String(str);
  1039. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1040. char[] decoded_char = new char[charCount];
  1041. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1042. string result = new String(decoded_char);
  1043. return result;
  1044. }
  1045. public static Guid GetHashGuid(string data, string salt)
  1046. {
  1047. byte[] hash = ComputeMD5Hash(data + salt);
  1048. //string s = BitConverter.ToString(hash);
  1049. Guid guid = new Guid(hash);
  1050. return guid;
  1051. }
  1052. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1053. {
  1054. byte retVal = 0;
  1055. switch (maturity)
  1056. {
  1057. case 0: //PG
  1058. retVal = 13;
  1059. break;
  1060. case 1: //Mature
  1061. retVal = 21;
  1062. break;
  1063. case 2: // Adult
  1064. retVal = 42;
  1065. break;
  1066. }
  1067. return retVal;
  1068. }
  1069. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1070. {
  1071. if (maturity <= 13)
  1072. return 0;
  1073. else if (maturity <= 21)
  1074. return 1;
  1075. else
  1076. return 2;
  1077. }
  1078. /// <summary>
  1079. /// Produces an OSDMap from its string representation on a stream
  1080. /// </summary>
  1081. /// <param name="data">The stream</param>
  1082. /// <param name="length">The size of the data on the stream</param>
  1083. /// <returns>The OSDMap or an exception</returns>
  1084. public static OSDMap GetOSDMap(Stream stream, int length)
  1085. {
  1086. byte[] data = new byte[length];
  1087. stream.Read(data, 0, length);
  1088. string strdata = Util.UTF8.GetString(data);
  1089. OSDMap args = null;
  1090. OSD buffer;
  1091. buffer = OSDParser.DeserializeJson(strdata);
  1092. if (buffer.Type == OSDType.Map)
  1093. {
  1094. args = (OSDMap)buffer;
  1095. return args;
  1096. }
  1097. return null;
  1098. }
  1099. public static OSDMap GetOSDMap(string data)
  1100. {
  1101. OSDMap args = null;
  1102. try
  1103. {
  1104. OSD buffer;
  1105. // We should pay attention to the content-type, but let's assume we know it's Json
  1106. buffer = OSDParser.DeserializeJson(data);
  1107. if (buffer.Type == OSDType.Map)
  1108. {
  1109. args = (OSDMap)buffer;
  1110. return args;
  1111. }
  1112. else
  1113. {
  1114. // uh?
  1115. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1116. return null;
  1117. }
  1118. }
  1119. catch (Exception ex)
  1120. {
  1121. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1122. return null;
  1123. }
  1124. }
  1125. public static string[] Glob(string path)
  1126. {
  1127. string vol=String.Empty;
  1128. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1129. {
  1130. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1131. if (vcomps.Length > 1)
  1132. {
  1133. path = vcomps[1];
  1134. vol = vcomps[0];
  1135. }
  1136. }
  1137. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1138. // Glob
  1139. path = vol;
  1140. if (vol != String.Empty)
  1141. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1142. else
  1143. path = new String(new char[] {Path.DirectorySeparatorChar});
  1144. List<string> paths = new List<string>();
  1145. List<string> found = new List<string>();
  1146. paths.Add(path);
  1147. int compIndex = -1;
  1148. foreach (string c in comps)
  1149. {
  1150. compIndex++;
  1151. List<string> addpaths = new List<string>();
  1152. foreach (string p in paths)
  1153. {
  1154. string[] dirs = Directory.GetDirectories(p, c);
  1155. if (dirs.Length != 0)
  1156. {
  1157. foreach (string dir in dirs)
  1158. addpaths.Add(Path.Combine(path, dir));
  1159. }
  1160. // Only add files if that is the last path component
  1161. if (compIndex == comps.Length - 1)
  1162. {
  1163. string[] files = Directory.GetFiles(p, c);
  1164. foreach (string f in files)
  1165. found.Add(f);
  1166. }
  1167. }
  1168. paths = addpaths;
  1169. }
  1170. return found.ToArray();
  1171. }
  1172. public static string ServerURI(string uri)
  1173. {
  1174. if (uri == string.Empty)
  1175. return string.Empty;
  1176. // Get rid of eventual slashes at the end
  1177. uri = uri.TrimEnd('/');
  1178. IPAddress ipaddr1 = null;
  1179. string port1 = "";
  1180. try
  1181. {
  1182. ipaddr1 = Util.GetHostFromURL(uri);
  1183. }
  1184. catch { }
  1185. try
  1186. {
  1187. port1 = uri.Split(new char[] { ':' })[2];
  1188. }
  1189. catch { }
  1190. // We tried our best to convert the domain names to IP addresses
  1191. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1192. }
  1193. /// <summary>
  1194. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1195. /// </summary>
  1196. /// <param name="str">
  1197. /// If null or empty, then an bytes[0] is returned.
  1198. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1199. /// </param>
  1200. /// <param name="args">
  1201. /// Arguments to substitute into the string via the {} mechanism.
  1202. /// </param>
  1203. /// <returns></returns>
  1204. public static byte[] StringToBytes256(string str, params object[] args)
  1205. {
  1206. return StringToBytes256(string.Format(str, args));
  1207. }
  1208. /// <summary>
  1209. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1210. /// </summary>
  1211. /// <param name="str">
  1212. /// If null or empty, then an bytes[0] is returned.
  1213. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1214. /// </param>
  1215. /// <returns></returns>
  1216. public static byte[] StringToBytes256(string str)
  1217. {
  1218. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1219. if (str.Length > 254) str = str.Remove(254);
  1220. if (!str.EndsWith("\0")) { str += "\0"; }
  1221. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1222. // might have gotten an oversized array even after the string trim
  1223. byte[] data = UTF8.GetBytes(str);
  1224. if (data.Length > 256)
  1225. {
  1226. Array.Resize<byte>(ref data, 256);
  1227. data[255] = 0;
  1228. }
  1229. return data;
  1230. }
  1231. /// <summary>
  1232. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1233. /// </summary>
  1234. /// <param name="str">
  1235. /// If null or empty, then an bytes[0] is returned.
  1236. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1237. /// </param>
  1238. /// <param name="args">
  1239. /// Arguments to substitute into the string via the {} mechanism.
  1240. /// </param>
  1241. /// <returns></returns>
  1242. public static byte[] StringToBytes1024(string str, params object[] args)
  1243. {
  1244. return StringToBytes1024(string.Format(str, args));
  1245. }
  1246. /// <summary>
  1247. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1248. /// </summary>
  1249. /// <param name="str">
  1250. /// If null or empty, then an bytes[0] is returned.
  1251. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1252. /// </param>
  1253. /// <returns></returns>
  1254. public static byte[] StringToBytes1024(string str)
  1255. {
  1256. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1257. if (str.Length > 1023) str = str.Remove(1023);
  1258. if (!str.EndsWith("\0")) { str += "\0"; }
  1259. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1260. // might have gotten an oversized array even after the string trim
  1261. byte[] data = UTF8.GetBytes(str);
  1262. if (data.Length > 1024)
  1263. {
  1264. Array.Resize<byte>(ref data, 1024);
  1265. data[1023] = 0;
  1266. }
  1267. return data;
  1268. }
  1269. #region FireAndForget Threading Pattern
  1270. /// <summary>
  1271. /// Created to work around a limitation in Mono with nested delegates
  1272. /// </summary>
  1273. private sealed class FireAndForgetWrapper
  1274. {
  1275. private static volatile FireAndForgetWrapper instance;
  1276. private static object syncRoot = new Object();
  1277. public static FireAndForgetWrapper Instance {
  1278. get {
  1279. if (instance == null)
  1280. {
  1281. lock (syncRoot)
  1282. {
  1283. if (instance == null)
  1284. {
  1285. instance = new FireAndForgetWrapper();
  1286. }
  1287. }
  1288. }
  1289. return instance;
  1290. }
  1291. }
  1292. public void FireAndForget(System.Threading.WaitCallback callback)
  1293. {
  1294. callback.BeginInvoke(null, EndFireAndForget, callback);
  1295. }
  1296. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1297. {
  1298. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1299. }
  1300. private static void EndFireAndForget(IAsyncResult ar)
  1301. {
  1302. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1303. try { callback.EndInvoke(ar); }
  1304. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1305. ar.AsyncWaitHandle.Close();
  1306. }
  1307. }
  1308. public static void FireAndForget(System.Threading.WaitCallback callback)
  1309. {
  1310. FireAndForget(callback, null);
  1311. }
  1312. public static void InitThreadPool(int maxThreads)
  1313. {
  1314. if (maxThreads < 2)
  1315. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1316. if (m_ThreadPool != null)
  1317. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1318. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1319. }
  1320. public static int FireAndForgetCount()
  1321. {
  1322. const int MAX_SYSTEM_THREADS = 200;
  1323. switch (FireAndForgetMethod)
  1324. {
  1325. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1326. case FireAndForgetMethod.QueueUserWorkItem:
  1327. case FireAndForgetMethod.BeginInvoke:
  1328. int workerThreads, iocpThreads;
  1329. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1330. return workerThreads;
  1331. case FireAndForgetMethod.SmartThreadPool:
  1332. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1333. case FireAndForgetMethod.Thread:
  1334. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1335. default:
  1336. throw new NotImplementedException();
  1337. }
  1338. }
  1339. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1340. {
  1341. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  1342. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  1343. // for decimals places but is read by a culture that treats commas as number seperators.
  1344. WaitCallback realCallback = delegate(object o)
  1345. {
  1346. Culture.SetCurrentCulture();
  1347. try
  1348. {
  1349. callback(o);
  1350. }
  1351. catch (Exception e)
  1352. {
  1353. m_log.ErrorFormat(
  1354. "[UTIL]: Continuing after async_call_method thread terminated with exception {0}{1}",
  1355. e.Message, e.StackTrace);
  1356. }
  1357. };
  1358. switch (FireAndForgetMethod)
  1359. {
  1360. case FireAndForgetMethod.None:
  1361. realCallback.Invoke(obj);
  1362. break;
  1363. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1364. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  1365. break;
  1366. case FireAndForgetMethod.QueueUserWorkItem:
  1367. ThreadPool.QueueUserWorkItem(realCallback, obj);
  1368. break;
  1369. case FireAndForgetMethod.BeginInvoke:
  1370. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  1371. wrapper.FireAndForget(realCallback, obj);
  1372. break;
  1373. case FireAndForgetMethod.SmartThreadPool:
  1374. if (m_ThreadPool == null)
  1375. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1376. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { realCallback, obj });
  1377. break;
  1378. case FireAndForgetMethod.Thread:
  1379. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  1380. thread.Start(obj);
  1381. break;
  1382. default:
  1383. throw new NotImplementedException();
  1384. }
  1385. }
  1386. private static object SmartThreadPoolCallback(object o)
  1387. {
  1388. object[] array = (object[])o;
  1389. WaitCallback callback = (WaitCallback)array[0];
  1390. object obj = array[1];
  1391. callback(obj);
  1392. return null;
  1393. }
  1394. #endregion FireAndForget Threading Pattern
  1395. /// <summary>
  1396. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1397. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1398. /// for the callers.
  1399. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1400. /// </summary>
  1401. /// <returns></returns>
  1402. public static Int32 EnvironmentTickCount()
  1403. {
  1404. return Environment.TickCount & EnvironmentTickCountMask;
  1405. }
  1406. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1407. /// <summary>
  1408. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1409. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1410. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1411. /// </summary>
  1412. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1413. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1414. {
  1415. Int32 diff = EnvironmentTickCount() - prevValue;
  1416. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1417. }
  1418. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1419. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1420. // A positive return value indicates A occured later than B
  1421. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1422. {
  1423. // A, B and TC are all between 0 and 0x3fffffff
  1424. int tc = EnvironmentTickCount();
  1425. if (tc - tcA >= 0)
  1426. tcA += EnvironmentTickCountMask + 1;
  1427. if (tc - tcB >= 0)
  1428. tcB += EnvironmentTickCountMask + 1;
  1429. return tcA - tcB;
  1430. }
  1431. /// <summary>
  1432. /// Prints the call stack at any given point. Useful for debugging.
  1433. /// </summary>
  1434. public static void PrintCallStack()
  1435. {
  1436. StackTrace stackTrace = new StackTrace(); // get call stack
  1437. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1438. // write call stack method names
  1439. foreach (StackFrame stackFrame in stackFrames)
  1440. {
  1441. m_log.Debug(stackFrame.GetMethod().DeclaringType + "." + stackFrame.GetMethod().Name); // write method name
  1442. }
  1443. }
  1444. /// <summary>
  1445. /// Gets the client IP address
  1446. /// </summary>
  1447. /// <param name="xff"></param>
  1448. /// <returns></returns>
  1449. public static IPEndPoint GetClientIPFromXFF(string xff)
  1450. {
  1451. if (xff == string.Empty)
  1452. return null;
  1453. string[] parts = xff.Split(new char[] { ',' });
  1454. if (parts.Length > 0)
  1455. {
  1456. try
  1457. {
  1458. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1459. }
  1460. catch (Exception e)
  1461. {
  1462. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1463. }
  1464. }
  1465. return null;
  1466. }
  1467. public static string GetCallerIP(Hashtable req)
  1468. {
  1469. if (req.ContainsKey("headers"))
  1470. {
  1471. try
  1472. {
  1473. Hashtable headers = (Hashtable)req["headers"];
  1474. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1475. return headers["remote_addr"].ToString();
  1476. }
  1477. catch (Exception e)
  1478. {
  1479. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1480. }
  1481. }
  1482. return string.Empty;
  1483. }
  1484. #region Xml Serialization Utilities
  1485. public static bool ReadBoolean(XmlTextReader reader)
  1486. {
  1487. reader.ReadStartElement();
  1488. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1489. reader.ReadEndElement();
  1490. return result;
  1491. }
  1492. public static UUID ReadUUID(XmlTextReader reader, string name)
  1493. {
  1494. UUID id;
  1495. string idStr;
  1496. reader.ReadStartElement(name);
  1497. if (reader.Name == "Guid")
  1498. idStr = reader.ReadElementString("Guid");
  1499. else if (reader.Name == "UUID")
  1500. idStr = reader.ReadElementString("UUID");
  1501. else // no leading tag
  1502. idStr = reader.ReadContentAsString();
  1503. UUID.TryParse(idStr, out id);
  1504. reader.ReadEndElement();
  1505. return id;
  1506. }
  1507. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1508. {
  1509. Vector3 vec;
  1510. reader.ReadStartElement(name);
  1511. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1512. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1513. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1514. reader.ReadEndElement();
  1515. return vec;
  1516. }
  1517. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1518. {
  1519. Quaternion quat = new Quaternion();
  1520. reader.ReadStartElement(name);
  1521. while (reader.NodeType != XmlNodeType.EndElement)
  1522. {
  1523. switch (reader.Name.ToLower())
  1524. {
  1525. case "x":
  1526. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1527. break;
  1528. case "y":
  1529. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1530. break;
  1531. case "z":
  1532. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1533. break;
  1534. case "w":
  1535. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1536. break;
  1537. }
  1538. }
  1539. reader.ReadEndElement();
  1540. return quat;
  1541. }
  1542. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1543. {
  1544. string value = reader.ReadElementContentAsString(name, String.Empty);
  1545. // !!!!! to deal with flags without commas
  1546. if (value.Contains(" ") && !value.Contains(","))
  1547. value = value.Replace(" ", ", ");
  1548. return (T)Enum.Parse(typeof(T), value); ;
  1549. }
  1550. #endregion
  1551. #region Universal User Identifiers
  1552. /// <summary>
  1553. /// </summary>
  1554. /// <param name="value">uuid[;endpoint[;name]]</param>
  1555. /// <param name="uuid"></param>
  1556. /// <param name="url"></param>
  1557. /// <param name="firstname"></param>
  1558. /// <param name="lastname"></param>
  1559. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1560. {
  1561. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1562. string[] parts = value.Split(';');
  1563. if (parts.Length >= 1)
  1564. if (!UUID.TryParse(parts[0], out uuid))
  1565. return false;
  1566. if (parts.Length >= 2)
  1567. url = parts[1];
  1568. if (parts.Length >= 3)
  1569. {
  1570. string[] name = parts[2].Split();
  1571. if (name.Length == 2)
  1572. {
  1573. firstname = name[0];
  1574. lastname = name[1];
  1575. }
  1576. }
  1577. if (parts.Length >= 4)
  1578. secret = parts[3];
  1579. return true;
  1580. }
  1581. /// <summary>
  1582. ///
  1583. /// </summary>
  1584. /// <param name="acircuit"></param>
  1585. /// <returns>uuid[;endpoint[;name]]</returns>
  1586. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1587. {
  1588. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1589. {
  1590. string agentsURI = acircuit.ServiceURLs["HomeURI"].ToString();
  1591. if (!agentsURI.EndsWith("/"))
  1592. agentsURI += "/";
  1593. // This is ugly, but there's no other way, given that the name is changed
  1594. // in the agent circuit data for foreigners
  1595. if (acircuit.lastname.Contains("@"))
  1596. {
  1597. string[] parts = acircuit.firstname.Split(new char[] { '.' });
  1598. if (parts.Length == 2)
  1599. return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1600. }
  1601. return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + acircuit.firstname + " " + acircuit.lastname;
  1602. }
  1603. else
  1604. return acircuit.AgentID.ToString();
  1605. }
  1606. #endregion
  1607. }
  1608. }