WebUtil.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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.Collections.Specialized;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.IO.Compression;
  34. using System.Net;
  35. using System.Net.Security;
  36. using System.Reflection;
  37. using System.Text;
  38. using System.Web;
  39. using System.Xml;
  40. using System.Xml.Serialization;
  41. using log4net;
  42. using OpenMetaverse.StructuredData;
  43. namespace OpenSim.Framework
  44. {
  45. /// <summary>
  46. /// Miscellaneous static methods and extension methods related to the web
  47. /// </summary>
  48. public static class WebUtil
  49. {
  50. private static readonly ILog m_log =
  51. LogManager.GetLogger(
  52. MethodBase.GetCurrentMethod().DeclaringType);
  53. /// <summary>
  54. /// Request number for diagnostic purposes.
  55. /// </summary>
  56. public static int RequestNumber = 0;
  57. /// <summary>
  58. /// this is the header field used to communicate the local request id
  59. /// used for performance and debugging
  60. /// </summary>
  61. public const string OSHeaderRequestID = "opensim-request-id";
  62. /// <summary>
  63. /// Number of milliseconds a call can take before it is considered
  64. /// a "long" call for warning & debugging purposes
  65. /// </summary>
  66. public const int LongCallTime = 3000;
  67. /// <summary>
  68. /// The maximum length of any data logged because of a long request time.
  69. /// </summary>
  70. /// <remarks>
  71. /// This is to truncate any really large post data, such as an asset. In theory, the first section should
  72. /// give us useful information about the call (which agent it relates to if applicable, etc.).
  73. /// </remarks>
  74. public const int MaxRequestDiagLength = 100;
  75. /// <summary>
  76. /// Dictionary of end points
  77. /// </summary>
  78. private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>();
  79. private static object EndPointLock(string url)
  80. {
  81. System.Uri uri = new System.Uri(url);
  82. string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port);
  83. lock (m_endpointSerializer)
  84. {
  85. object eplock = null;
  86. if (! m_endpointSerializer.TryGetValue(endpoint,out eplock))
  87. {
  88. eplock = new object();
  89. m_endpointSerializer.Add(endpoint,eplock);
  90. // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint);
  91. }
  92. return eplock;
  93. }
  94. }
  95. #region JSONRequest
  96. /// <summary>
  97. /// PUT JSON-encoded data to a web service that returns LLSD or
  98. /// JSON data
  99. /// </summary>
  100. public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout)
  101. {
  102. return ServiceOSDRequest(url,data, "PUT", timeout, true);
  103. }
  104. public static OSDMap PutToService(string url, OSDMap data, int timeout)
  105. {
  106. return ServiceOSDRequest(url,data, "PUT", timeout, false);
  107. }
  108. public static OSDMap PostToService(string url, OSDMap data, int timeout)
  109. {
  110. return ServiceOSDRequest(url, data, "POST", timeout, false);
  111. }
  112. public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout)
  113. {
  114. return ServiceOSDRequest(url, data, "POST", timeout, true);
  115. }
  116. public static OSDMap GetFromService(string url, int timeout)
  117. {
  118. return ServiceOSDRequest(url, null, "GET", timeout, false);
  119. }
  120. public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed)
  121. {
  122. lock (EndPointLock(url))
  123. {
  124. return ServiceOSDRequestWorker(url,data,method,timeout,compressed);
  125. }
  126. }
  127. private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed)
  128. {
  129. int reqnum = RequestNumber++;
  130. // m_log.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);
  131. string errorMessage = "unknown error";
  132. int tickstart = Util.EnvironmentTickCount();
  133. int tickdata = 0;
  134. string strBuffer = null;
  135. try
  136. {
  137. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  138. request.Method = method;
  139. request.Timeout = timeout;
  140. request.KeepAlive = false;
  141. request.MaximumAutomaticRedirections = 10;
  142. request.ReadWriteTimeout = timeout / 4;
  143. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  144. // If there is some input, write it into the request
  145. if (data != null)
  146. {
  147. strBuffer = OSDParser.SerializeJsonString(data);
  148. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer);
  149. if (compressed)
  150. {
  151. request.ContentType = "application/x-gzip";
  152. using (MemoryStream ms = new MemoryStream())
  153. {
  154. using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress))
  155. {
  156. comp.Write(buffer, 0, buffer.Length);
  157. // We need to close the gzip stream before we write it anywhere
  158. // because apparently something important related to gzip compression
  159. // gets written on the strteam upon Dispose()
  160. }
  161. byte[] buf = ms.ToArray();
  162. request.ContentLength = buf.Length; //Count bytes to send
  163. using (Stream requestStream = request.GetRequestStream())
  164. requestStream.Write(buf, 0, (int)buf.Length);
  165. }
  166. }
  167. else
  168. {
  169. request.ContentType = "application/json";
  170. request.ContentLength = buffer.Length; //Count bytes to send
  171. using (Stream requestStream = request.GetRequestStream())
  172. requestStream.Write(buffer, 0, buffer.Length); //Send it
  173. }
  174. }
  175. // capture how much time was spent writing, this may seem silly
  176. // but with the number concurrent requests, this often blocks
  177. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  178. using (WebResponse response = request.GetResponse())
  179. {
  180. using (Stream responseStream = response.GetResponseStream())
  181. {
  182. string responseStr = null;
  183. responseStr = responseStream.GetStreamString();
  184. // m_log.DebugFormat("[WEB UTIL]: <{0}> response is <{1}>",reqnum,responseStr);
  185. return CanonicalizeResults(responseStr);
  186. }
  187. }
  188. }
  189. catch (WebException we)
  190. {
  191. errorMessage = we.Message;
  192. if (we.Status == WebExceptionStatus.ProtocolError)
  193. {
  194. HttpWebResponse webResponse = (HttpWebResponse)we.Response;
  195. errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
  196. }
  197. }
  198. catch (Exception ex)
  199. {
  200. errorMessage = ex.Message;
  201. }
  202. finally
  203. {
  204. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  205. if (tickdiff > LongCallTime)
  206. m_log.InfoFormat(
  207. "[OSD REQUEST]: Slow request to <{0}> {1} {2} took {3}ms, {4}ms writing, {5}",
  208. reqnum,
  209. method,
  210. url,
  211. tickdiff,
  212. tickdata,
  213. strBuffer != null
  214. ? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer)
  215. : "");
  216. }
  217. m_log.DebugFormat(
  218. "[WEB UTIL]: <{0}> osd request for {1}, method {2} FAILED: {3}", reqnum, url, method, errorMessage);
  219. return ErrorResponseMap(errorMessage);
  220. }
  221. /// <summary>
  222. /// Since there are no consistencies in the way web requests are
  223. /// formed, we need to do a little guessing about the result format.
  224. /// Keys:
  225. /// Success|success == the success fail of the request
  226. /// _RawResult == the raw string that came back
  227. /// _Result == the OSD unpacked string
  228. /// </summary>
  229. private static OSDMap CanonicalizeResults(string response)
  230. {
  231. OSDMap result = new OSDMap();
  232. // Default values
  233. result["Success"] = OSD.FromBoolean(true);
  234. result["success"] = OSD.FromBoolean(true);
  235. result["_RawResult"] = OSD.FromString(response);
  236. result["_Result"] = new OSDMap();
  237. if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase))
  238. return result;
  239. if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase))
  240. {
  241. result["Success"] = OSD.FromBoolean(false);
  242. result["success"] = OSD.FromBoolean(false);
  243. return result;
  244. }
  245. try
  246. {
  247. OSD responseOSD = OSDParser.Deserialize(response);
  248. if (responseOSD.Type == OSDType.Map)
  249. {
  250. result["_Result"] = (OSDMap)responseOSD;
  251. return result;
  252. }
  253. }
  254. catch
  255. {
  256. // don't need to treat this as an error... we're just guessing anyway
  257. // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message);
  258. }
  259. return result;
  260. }
  261. #endregion JSONRequest
  262. #region FormRequest
  263. /// <summary>
  264. /// POST URL-encoded form data to a web service that returns LLSD or
  265. /// JSON data
  266. /// </summary>
  267. public static OSDMap PostToService(string url, NameValueCollection data)
  268. {
  269. return ServiceFormRequest(url,data,10000);
  270. }
  271. public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
  272. {
  273. lock (EndPointLock(url))
  274. {
  275. return ServiceFormRequestWorker(url,data,timeout);
  276. }
  277. }
  278. private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout)
  279. {
  280. int reqnum = RequestNumber++;
  281. string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
  282. // m_log.DebugFormat("[WEB UTIL]: <{0}> start form request for {1}, method {2}",reqnum,url,method);
  283. string errorMessage = "unknown error";
  284. int tickstart = Util.EnvironmentTickCount();
  285. int tickdata = 0;
  286. string queryString = null;
  287. try
  288. {
  289. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  290. request.Method = "POST";
  291. request.Timeout = timeout;
  292. request.KeepAlive = false;
  293. request.MaximumAutomaticRedirections = 10;
  294. request.ReadWriteTimeout = timeout / 4;
  295. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  296. if (data != null)
  297. {
  298. queryString = BuildQueryString(data);
  299. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString);
  300. request.ContentLength = buffer.Length;
  301. request.ContentType = "application/x-www-form-urlencoded";
  302. using (Stream requestStream = request.GetRequestStream())
  303. requestStream.Write(buffer, 0, buffer.Length);
  304. }
  305. // capture how much time was spent writing, this may seem silly
  306. // but with the number concurrent requests, this often blocks
  307. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  308. using (WebResponse response = request.GetResponse())
  309. {
  310. using (Stream responseStream = response.GetResponseStream())
  311. {
  312. string responseStr = null;
  313. responseStr = responseStream.GetStreamString();
  314. OSD responseOSD = OSDParser.Deserialize(responseStr);
  315. if (responseOSD.Type == OSDType.Map)
  316. return (OSDMap)responseOSD;
  317. }
  318. }
  319. }
  320. catch (WebException we)
  321. {
  322. errorMessage = we.Message;
  323. if (we.Status == WebExceptionStatus.ProtocolError)
  324. {
  325. HttpWebResponse webResponse = (HttpWebResponse)we.Response;
  326. errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
  327. }
  328. }
  329. catch (Exception ex)
  330. {
  331. errorMessage = ex.Message;
  332. }
  333. finally
  334. {
  335. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  336. if (tickdiff > LongCallTime)
  337. m_log.InfoFormat(
  338. "[SERVICE FORM]: Slow request to <{0}> {1} {2} took {3}ms, {4}ms writing, {5}",
  339. reqnum,
  340. method,
  341. url,
  342. tickdiff,
  343. tickdata,
  344. queryString != null
  345. ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString
  346. : "");
  347. }
  348. m_log.WarnFormat("[SERVICE FORM]: <{0}> form request to {1} failed: {2}", reqnum, url, errorMessage);
  349. return ErrorResponseMap(errorMessage);
  350. }
  351. /// <summary>
  352. /// Create a response map for an error, trying to keep
  353. /// the result formats consistent
  354. /// </summary>
  355. private static OSDMap ErrorResponseMap(string msg)
  356. {
  357. OSDMap result = new OSDMap();
  358. result["Success"] = "False";
  359. result["Message"] = OSD.FromString("Service request failed: " + msg);
  360. return result;
  361. }
  362. #endregion FormRequest
  363. #region Uri
  364. /// <summary>
  365. /// Combines a Uri that can contain both a base Uri and relative path
  366. /// with a second relative path fragment
  367. /// </summary>
  368. /// <param name="uri">Starting (base) Uri</param>
  369. /// <param name="fragment">Relative path fragment to append to the end
  370. /// of the Uri</param>
  371. /// <returns>The combined Uri</returns>
  372. /// <remarks>This is similar to the Uri constructor that takes a base
  373. /// Uri and the relative path, except this method can append a relative
  374. /// path fragment on to an existing relative path</remarks>
  375. public static Uri Combine(this Uri uri, string fragment)
  376. {
  377. string fragment1 = uri.Fragment;
  378. string fragment2 = fragment;
  379. if (!fragment1.EndsWith("/"))
  380. fragment1 = fragment1 + '/';
  381. if (fragment2.StartsWith("/"))
  382. fragment2 = fragment2.Substring(1);
  383. return new Uri(uri, fragment1 + fragment2);
  384. }
  385. /// <summary>
  386. /// Combines a Uri that can contain both a base Uri and relative path
  387. /// with a second relative path fragment. If the fragment is absolute,
  388. /// it will be returned without modification
  389. /// </summary>
  390. /// <param name="uri">Starting (base) Uri</param>
  391. /// <param name="fragment">Relative path fragment to append to the end
  392. /// of the Uri, or an absolute Uri to return unmodified</param>
  393. /// <returns>The combined Uri</returns>
  394. public static Uri Combine(this Uri uri, Uri fragment)
  395. {
  396. if (fragment.IsAbsoluteUri)
  397. return fragment;
  398. string fragment1 = uri.Fragment;
  399. string fragment2 = fragment.ToString();
  400. if (!fragment1.EndsWith("/"))
  401. fragment1 = fragment1 + '/';
  402. if (fragment2.StartsWith("/"))
  403. fragment2 = fragment2.Substring(1);
  404. return new Uri(uri, fragment1 + fragment2);
  405. }
  406. /// <summary>
  407. /// Appends a query string to a Uri that may or may not have existing
  408. /// query parameters
  409. /// </summary>
  410. /// <param name="uri">Uri to append the query to</param>
  411. /// <param name="query">Query string to append. Can either start with ?
  412. /// or just containg key/value pairs</param>
  413. /// <returns>String representation of the Uri with the query string
  414. /// appended</returns>
  415. public static string AppendQuery(this Uri uri, string query)
  416. {
  417. if (String.IsNullOrEmpty(query))
  418. return uri.ToString();
  419. if (query[0] == '?' || query[0] == '&')
  420. query = query.Substring(1);
  421. string uriStr = uri.ToString();
  422. if (uriStr.Contains("?"))
  423. return uriStr + '&' + query;
  424. else
  425. return uriStr + '?' + query;
  426. }
  427. #endregion Uri
  428. #region NameValueCollection
  429. /// <summary>
  430. /// Convert a NameValueCollection into a query string. This is the
  431. /// inverse of HttpUtility.ParseQueryString()
  432. /// </summary>
  433. /// <param name="parameters">Collection of key/value pairs to convert</param>
  434. /// <returns>A query string with URL-escaped values</returns>
  435. public static string BuildQueryString(NameValueCollection parameters)
  436. {
  437. List<string> items = new List<string>(parameters.Count);
  438. foreach (string key in parameters.Keys)
  439. {
  440. string[] values = parameters.GetValues(key);
  441. if (values != null)
  442. {
  443. foreach (string value in values)
  444. items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
  445. }
  446. }
  447. return String.Join("&", items.ToArray());
  448. }
  449. /// <summary>
  450. ///
  451. /// </summary>
  452. /// <param name="collection"></param>
  453. /// <param name="key"></param>
  454. /// <returns></returns>
  455. public static string GetOne(this NameValueCollection collection, string key)
  456. {
  457. string[] values = collection.GetValues(key);
  458. if (values != null && values.Length > 0)
  459. return values[0];
  460. return null;
  461. }
  462. #endregion NameValueCollection
  463. #region Stream
  464. /// <summary>
  465. /// Copies the contents of one stream to another, starting at the
  466. /// current position of each stream
  467. /// </summary>
  468. /// <param name="copyFrom">The stream to copy from, at the position
  469. /// where copying should begin</param>
  470. /// <param name="copyTo">The stream to copy to, at the position where
  471. /// bytes should be written</param>
  472. /// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
  473. /// <returns>The total number of bytes copied</returns>
  474. /// <remarks>
  475. /// Copying begins at the streams' current positions. The positions are
  476. /// NOT reset after copying is complete.
  477. /// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'.
  478. /// This function could be replaced with that method once we move
  479. /// totally to .NET 4.0. For versions before, this routine exists.
  480. /// This routine used to be named 'CopyTo' but the int parameter has
  481. /// a different meaning so this method was renamed to avoid any confusion.
  482. /// </remarks>
  483. public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
  484. {
  485. byte[] buffer = new byte[4096];
  486. int readBytes;
  487. int totalCopiedBytes = 0;
  488. while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
  489. {
  490. int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
  491. copyTo.Write(buffer, 0, writeBytes);
  492. totalCopiedBytes += writeBytes;
  493. maximumBytesToCopy -= writeBytes;
  494. }
  495. return totalCopiedBytes;
  496. }
  497. /// <summary>
  498. /// Converts an entire stream to a string, regardless of current stream
  499. /// position
  500. /// </summary>
  501. /// <param name="stream">The stream to convert to a string</param>
  502. /// <returns></returns>
  503. /// <remarks>When this method is done, the stream position will be
  504. /// reset to its previous position before this method was called</remarks>
  505. public static string GetStreamString(this Stream stream)
  506. {
  507. string value = null;
  508. if (stream != null && stream.CanRead)
  509. {
  510. long rewindPos = -1;
  511. if (stream.CanSeek)
  512. {
  513. rewindPos = stream.Position;
  514. stream.Seek(0, SeekOrigin.Begin);
  515. }
  516. StreamReader reader = new StreamReader(stream);
  517. value = reader.ReadToEnd();
  518. if (rewindPos >= 0)
  519. stream.Seek(rewindPos, SeekOrigin.Begin);
  520. }
  521. return value;
  522. }
  523. #endregion Stream
  524. public class QBasedComparer : IComparer
  525. {
  526. public int Compare(Object x, Object y)
  527. {
  528. float qx = GetQ(x);
  529. float qy = GetQ(y);
  530. return qy.CompareTo(qx); // descending order
  531. }
  532. private float GetQ(Object o)
  533. {
  534. // Example: image/png;q=0.9
  535. float qvalue = 1F;
  536. if (o is String)
  537. {
  538. string mime = (string)o;
  539. string[] parts = mime.Split(';');
  540. if (parts.Length > 1)
  541. {
  542. string[] kvp = parts[1].Split('=');
  543. if (kvp.Length == 2 && kvp[0] == "q")
  544. float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue);
  545. }
  546. }
  547. return qvalue;
  548. }
  549. }
  550. /// <summary>
  551. /// Takes the value of an Accept header and returns the preferred types
  552. /// ordered by q value (if it exists).
  553. /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2
  554. /// Exmaple output: ["jp2", "png", "jpg"]
  555. /// NOTE: This doesn't handle the semantics of *'s...
  556. /// </summary>
  557. /// <param name="accept"></param>
  558. /// <returns></returns>
  559. public static string[] GetPreferredImageTypes(string accept)
  560. {
  561. if (accept == null || accept == string.Empty)
  562. return new string[0];
  563. string[] types = accept.Split(new char[] { ',' });
  564. if (types.Length > 0)
  565. {
  566. List<string> list = new List<string>(types);
  567. list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); });
  568. ArrayList tlist = new ArrayList(list);
  569. tlist.Sort(new QBasedComparer());
  570. string[] result = new string[tlist.Count];
  571. for (int i = 0; i < tlist.Count; i++)
  572. {
  573. string mime = (string)tlist[i];
  574. string[] parts = mime.Split(new char[] { ';' });
  575. string[] pair = parts[0].Split(new char[] { '/' });
  576. if (pair.Length == 2)
  577. result[i] = pair[1].ToLower();
  578. else // oops, we don't know what this is...
  579. result[i] = pair[0];
  580. }
  581. return result;
  582. }
  583. return new string[0];
  584. }
  585. }
  586. public static class AsynchronousRestObjectRequester
  587. {
  588. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  589. /// <summary>
  590. /// Perform an asynchronous REST request.
  591. /// </summary>
  592. /// <param name="verb">GET or POST</param>
  593. /// <param name="requestUrl"></param>
  594. /// <param name="obj"></param>
  595. /// <param name="action"></param>
  596. /// <returns></returns>
  597. ///
  598. /// <exception cref="System.Net.WebException">Thrown if we encounter a
  599. /// network issue while posting the request. You'll want to make
  600. /// sure you deal with this as they're not uncommon</exception>
  601. //
  602. public static void MakeRequest<TRequest, TResponse>(string verb,
  603. string requestUrl, TRequest obj, Action<TResponse> action)
  604. {
  605. int reqnum = WebUtil.RequestNumber++;
  606. // m_log.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);
  607. int tickstart = Util.EnvironmentTickCount();
  608. int tickdata = 0;
  609. // m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
  610. Type type = typeof(TRequest);
  611. WebRequest request = WebRequest.Create(requestUrl);
  612. WebResponse response = null;
  613. TResponse deserial = default(TResponse);
  614. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  615. request.Method = verb;
  616. MemoryStream buffer = null;
  617. if (verb == "POST")
  618. {
  619. request.ContentType = "text/xml";
  620. buffer = new MemoryStream();
  621. XmlWriterSettings settings = new XmlWriterSettings();
  622. settings.Encoding = Encoding.UTF8;
  623. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  624. {
  625. XmlSerializer serializer = new XmlSerializer(type);
  626. serializer.Serialize(writer, obj);
  627. writer.Flush();
  628. }
  629. int length = (int)buffer.Length;
  630. request.ContentLength = length;
  631. request.BeginGetRequestStream(delegate(IAsyncResult res)
  632. {
  633. Stream requestStream = request.EndGetRequestStream(res);
  634. requestStream.Write(buffer.ToArray(), 0, length);
  635. requestStream.Close();
  636. // capture how much time was spent writing
  637. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  638. request.BeginGetResponse(delegate(IAsyncResult ar)
  639. {
  640. response = request.EndGetResponse(ar);
  641. Stream respStream = null;
  642. try
  643. {
  644. respStream = response.GetResponseStream();
  645. deserial = (TResponse)deserializer.Deserialize(
  646. respStream);
  647. }
  648. catch (System.InvalidOperationException)
  649. {
  650. }
  651. finally
  652. {
  653. // Let's not close this
  654. //buffer.Close();
  655. respStream.Close();
  656. response.Close();
  657. }
  658. action(deserial);
  659. }, null);
  660. }, null);
  661. }
  662. else
  663. {
  664. request.BeginGetResponse(delegate(IAsyncResult res2)
  665. {
  666. try
  667. {
  668. // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
  669. // documented in MSDN
  670. response = request.EndGetResponse(res2);
  671. Stream respStream = null;
  672. try
  673. {
  674. respStream = response.GetResponseStream();
  675. deserial = (TResponse)deserializer.Deserialize(respStream);
  676. }
  677. catch (System.InvalidOperationException)
  678. {
  679. }
  680. finally
  681. {
  682. respStream.Close();
  683. response.Close();
  684. }
  685. }
  686. catch (WebException e)
  687. {
  688. if (e.Status == WebExceptionStatus.ProtocolError)
  689. {
  690. if (e.Response is HttpWebResponse)
  691. {
  692. HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
  693. if (httpResponse.StatusCode != HttpStatusCode.NotFound)
  694. {
  695. // We don't appear to be handling any other status codes, so log these feailures to that
  696. // people don't spend unnecessary hours hunting phantom bugs.
  697. m_log.DebugFormat(
  698. "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
  699. verb, requestUrl, httpResponse.StatusCode);
  700. }
  701. }
  702. }
  703. else
  704. {
  705. m_log.ErrorFormat(
  706. "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}",
  707. verb, requestUrl, e.Status, e.Message);
  708. }
  709. }
  710. catch (Exception e)
  711. {
  712. m_log.ErrorFormat(
  713. "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}",
  714. verb, requestUrl, e.Message, e.StackTrace);
  715. }
  716. // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
  717. try
  718. {
  719. action(deserial);
  720. }
  721. catch (Exception e)
  722. {
  723. m_log.ErrorFormat(
  724. "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}",
  725. verb, requestUrl, e.Message, e.StackTrace);
  726. }
  727. }, null);
  728. }
  729. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  730. if (tickdiff > WebUtil.LongCallTime)
  731. {
  732. string originalRequest = null;
  733. if (buffer != null)
  734. {
  735. originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
  736. if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
  737. originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
  738. }
  739. m_log.InfoFormat(
  740. "[ASYNC REQUEST]: Slow request to <{0}> {1} {2} took {3}ms, {4}ms writing, {5}",
  741. reqnum,
  742. verb,
  743. requestUrl,
  744. tickdiff,
  745. tickdata,
  746. originalRequest);
  747. }
  748. }
  749. }
  750. public static class SynchronousRestFormsRequester
  751. {
  752. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  753. /// <summary>
  754. /// Perform a synchronous REST request.
  755. /// </summary>
  756. /// <param name="verb"></param>
  757. /// <param name="requestUrl"></param>
  758. /// <param name="obj"> </param>
  759. /// <returns></returns>
  760. ///
  761. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  762. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  763. public static string MakeRequest(string verb, string requestUrl, string obj)
  764. {
  765. int reqnum = WebUtil.RequestNumber++;
  766. // m_log.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);
  767. int tickstart = Util.EnvironmentTickCount();
  768. int tickdata = 0;
  769. WebRequest request = WebRequest.Create(requestUrl);
  770. request.Method = verb;
  771. string respstring = String.Empty;
  772. using (MemoryStream buffer = new MemoryStream())
  773. {
  774. if ((verb == "POST") || (verb == "PUT"))
  775. {
  776. request.ContentType = "application/x-www-form-urlencoded";
  777. int length = 0;
  778. using (StreamWriter writer = new StreamWriter(buffer))
  779. {
  780. writer.Write(obj);
  781. writer.Flush();
  782. }
  783. length = (int)obj.Length;
  784. request.ContentLength = length;
  785. Stream requestStream = null;
  786. try
  787. {
  788. requestStream = request.GetRequestStream();
  789. requestStream.Write(buffer.ToArray(), 0, length);
  790. }
  791. catch (Exception e)
  792. {
  793. m_log.DebugFormat(
  794. "[FORMS]: exception occured {0} {1}: {2}{3}", verb, requestUrl, e.Message, e.StackTrace);
  795. }
  796. finally
  797. {
  798. if (requestStream != null)
  799. requestStream.Close();
  800. // capture how much time was spent writing
  801. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  802. }
  803. }
  804. try
  805. {
  806. using (WebResponse resp = request.GetResponse())
  807. {
  808. if (resp.ContentLength != 0)
  809. {
  810. Stream respStream = null;
  811. try
  812. {
  813. respStream = resp.GetResponseStream();
  814. using (StreamReader reader = new StreamReader(respStream))
  815. {
  816. respstring = reader.ReadToEnd();
  817. }
  818. }
  819. catch (Exception e)
  820. {
  821. m_log.DebugFormat(
  822. "[FORMS]: Exception occured on receiving {0} {1}: {2}{3}",
  823. verb, requestUrl, e.Message, e.StackTrace);
  824. }
  825. finally
  826. {
  827. if (respStream != null)
  828. respStream.Close();
  829. }
  830. }
  831. }
  832. }
  833. catch (System.InvalidOperationException)
  834. {
  835. // This is what happens when there is invalid XML
  836. m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving {0} {1}", verb, requestUrl);
  837. }
  838. }
  839. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  840. if (tickdiff > WebUtil.LongCallTime)
  841. m_log.InfoFormat(
  842. "[FORMS]: Slow request to <{0}> {1} {2} took {3}ms, {4}ms writing, {5}",
  843. reqnum,
  844. verb,
  845. requestUrl,
  846. tickdiff,
  847. tickdata,
  848. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  849. return respstring;
  850. }
  851. }
  852. public class SynchronousRestObjectRequester
  853. {
  854. private static readonly ILog m_log =
  855. LogManager.GetLogger(
  856. MethodBase.GetCurrentMethod().DeclaringType);
  857. /// <summary>
  858. /// Perform a synchronous REST request.
  859. /// </summary>
  860. /// <param name="verb"></param>
  861. /// <param name="requestUrl"></param>
  862. /// <param name="obj"> </param>
  863. /// <returns></returns>
  864. ///
  865. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  866. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  867. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
  868. {
  869. int reqnum = WebUtil.RequestNumber++;
  870. // m_log.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);
  871. int tickstart = Util.EnvironmentTickCount();
  872. int tickdata = 0;
  873. Type type = typeof(TRequest);
  874. TResponse deserial = default(TResponse);
  875. WebRequest request = WebRequest.Create(requestUrl);
  876. request.Method = verb;
  877. MemoryStream buffer = null;
  878. if ((verb == "POST") || (verb == "PUT"))
  879. {
  880. request.ContentType = "text/xml";
  881. buffer = new MemoryStream();
  882. XmlWriterSettings settings = new XmlWriterSettings();
  883. settings.Encoding = Encoding.UTF8;
  884. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  885. {
  886. XmlSerializer serializer = new XmlSerializer(type);
  887. serializer.Serialize(writer, obj);
  888. writer.Flush();
  889. }
  890. int length = (int)buffer.Length;
  891. request.ContentLength = length;
  892. Stream requestStream = null;
  893. try
  894. {
  895. requestStream = request.GetRequestStream();
  896. requestStream.Write(buffer.ToArray(), 0, length);
  897. }
  898. catch (Exception e)
  899. {
  900. m_log.DebugFormat(
  901. "[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}",
  902. verb, requestUrl, e.Message, e.StackTrace);
  903. return deserial;
  904. }
  905. finally
  906. {
  907. if (requestStream != null)
  908. requestStream.Close();
  909. // capture how much time was spent writing
  910. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  911. }
  912. }
  913. try
  914. {
  915. using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
  916. {
  917. if (resp.ContentLength != 0)
  918. {
  919. Stream respStream = resp.GetResponseStream();
  920. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  921. deserial = (TResponse)deserializer.Deserialize(respStream);
  922. respStream.Close();
  923. }
  924. else
  925. {
  926. m_log.DebugFormat(
  927. "[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}",
  928. verb, requestUrl);
  929. }
  930. }
  931. }
  932. catch (WebException e)
  933. {
  934. HttpWebResponse hwr = (HttpWebResponse)e.Response;
  935. if (hwr != null && hwr.StatusCode == HttpStatusCode.NotFound)
  936. return deserial;
  937. else
  938. m_log.ErrorFormat(
  939. "[SynchronousRestObjectRequester]: WebException for {0} {1} {2}: {3} {4}",
  940. verb, requestUrl, typeof(TResponse).ToString(), e.Message, e.StackTrace);
  941. }
  942. catch (System.InvalidOperationException)
  943. {
  944. // This is what happens when there is invalid XML
  945. m_log.DebugFormat(
  946. "[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}",
  947. verb, requestUrl, typeof(TResponse).ToString());
  948. }
  949. catch (Exception e)
  950. {
  951. m_log.DebugFormat(
  952. "[SynchronousRestObjectRequester]: Exception on response from {0} {1}: {2}{3}",
  953. verb, requestUrl, e.Message, e.StackTrace);
  954. }
  955. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  956. if (tickdiff > WebUtil.LongCallTime)
  957. {
  958. string originalRequest = null;
  959. if (buffer != null)
  960. {
  961. originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
  962. if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
  963. originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
  964. }
  965. m_log.InfoFormat(
  966. "[SynchronousRestObjectRequester]: Slow request to <{0}> {1} {2} took {3}ms, {4}ms writing, {5}",
  967. reqnum,
  968. verb,
  969. requestUrl,
  970. tickdiff,
  971. tickdata,
  972. originalRequest);
  973. }
  974. return deserial;
  975. }
  976. }
  977. }