WebUtil.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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.Security.Cryptography.X509Certificates;
  37. using System.Reflection;
  38. using System.Text;
  39. using System.Web;
  40. using System.Xml;
  41. using System.Xml.Serialization;
  42. using System.Xml.Linq;
  43. using log4net;
  44. using Nwc.XmlRpc;
  45. using OpenMetaverse.StructuredData;
  46. using OpenSim.Framework.ServiceAuth;
  47. using XMLResponseHelper = OpenSim.Framework.SynchronousRestObjectRequester.XMLResponseHelper;
  48. namespace OpenSim.Framework
  49. {
  50. /// <summary>
  51. /// Miscellaneous static methods and extension methods related to the web
  52. /// </summary>
  53. public static class WebUtil
  54. {
  55. private static readonly ILog m_log =
  56. LogManager.GetLogger(
  57. MethodBase.GetCurrentMethod().DeclaringType);
  58. /// <summary>
  59. /// Control the printing of certain debug messages.
  60. /// </summary>
  61. /// <remarks>
  62. /// If DebugLevel >= 3 then short notices about outgoing HTTP requests are logged.
  63. /// </remarks>
  64. public static int DebugLevel { get; set; }
  65. /// <summary>
  66. /// Request number for diagnostic purposes.
  67. /// </summary>
  68. public static int RequestNumber { get; set; }
  69. /// <summary>
  70. /// this is the header field used to communicate the local request id
  71. /// used for performance and debugging
  72. /// </summary>
  73. public const string OSHeaderRequestID = "opensim-request-id";
  74. /// <summary>
  75. /// Number of milliseconds a call can take before it is considered
  76. /// a "long" call for warning & debugging purposes
  77. /// </summary>
  78. public const int LongCallTime = 3000;
  79. /// <summary>
  80. /// The maximum length of any data logged because of a long request time.
  81. /// </summary>
  82. /// <remarks>
  83. /// This is to truncate any really large post data, such as an asset. In theory, the first section should
  84. /// give us useful information about the call (which agent it relates to if applicable, etc.).
  85. /// This is also used to truncate messages when using DebugLevel 5.
  86. /// </remarks>
  87. public const int MaxRequestDiagLength = 200;
  88. public static bool ValidateServerCertificateNoChecks(
  89. object sender,
  90. X509Certificate certificate,
  91. X509Chain chain,
  92. SslPolicyErrors sslPolicyErrors)
  93. {
  94. sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
  95. sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
  96. if (sslPolicyErrors == SslPolicyErrors.None)
  97. return true;
  98. return false;
  99. }
  100. #region JSONRequest
  101. /// <summary>
  102. /// PUT JSON-encoded data to a web service that returns LLSD or
  103. /// JSON data
  104. /// </summary>
  105. public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout)
  106. {
  107. return ServiceOSDRequest(url,data, "PUT", timeout, true, false);
  108. }
  109. public static OSDMap PutToService(string url, OSDMap data, int timeout)
  110. {
  111. return ServiceOSDRequest(url,data, "PUT", timeout, false, false);
  112. }
  113. public static OSDMap PostToService(string url, OSDMap data, int timeout, bool rpc)
  114. {
  115. return ServiceOSDRequest(url, data, "POST", timeout, false, rpc);
  116. }
  117. public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout)
  118. {
  119. return ServiceOSDRequest(url, data, "POST", timeout, true, false);
  120. }
  121. public static OSDMap GetFromService(string url, int timeout)
  122. {
  123. return ServiceOSDRequest(url, null, "GET", timeout, false, false);
  124. }
  125. public static void LogOutgoingDetail(Stream outputStream)
  126. {
  127. LogOutgoingDetail("", outputStream);
  128. }
  129. public static void LogOutgoingDetail(string context, Stream outputStream)
  130. {
  131. using (Stream stream = Util.Copy(outputStream))
  132. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  133. {
  134. string output;
  135. if (DebugLevel == 5)
  136. {
  137. char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed
  138. int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1);
  139. output = new string(chars, 0, len);
  140. }
  141. else
  142. {
  143. output = reader.ReadToEnd();
  144. }
  145. LogOutgoingDetail(context, output);
  146. }
  147. }
  148. public static void LogOutgoingDetail(string type, int reqnum, string output)
  149. {
  150. LogOutgoingDetail(string.Format("{0} {1}: ", type, reqnum), output);
  151. }
  152. public static void LogOutgoingDetail(string context, string output)
  153. {
  154. if (DebugLevel == 5)
  155. {
  156. if (output.Length > MaxRequestDiagLength)
  157. output = output.Substring(0, MaxRequestDiagLength) + "...";
  158. }
  159. m_log.DebugFormat("[LOGHTTP]: {0}{1}", context, Util.BinaryToASCII(output));
  160. }
  161. public static void LogResponseDetail(int reqnum, Stream inputStream)
  162. {
  163. LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), inputStream);
  164. }
  165. public static void LogResponseDetail(int reqnum, string input)
  166. {
  167. LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input);
  168. }
  169. public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc, bool keepalive = false)
  170. {
  171. int reqnum = RequestNumber++;
  172. if (DebugLevel >= 3)
  173. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} JSON-RPC {1} to {2}",
  174. reqnum, method, url);
  175. string errorMessage = "unknown error";
  176. int tickstart = Util.EnvironmentTickCount();
  177. int tickdata = 0;
  178. int tickcompressdata = 0;
  179. int tickJsondata = 0;
  180. int compsize = 0;
  181. string strBuffer = null;
  182. try
  183. {
  184. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  185. request.Method = method;
  186. request.Timeout = timeout;
  187. request.KeepAlive = keepalive;
  188. request.MaximumAutomaticRedirections = 10;
  189. request.ReadWriteTimeout = timeout / 2;
  190. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  191. // If there is some input, write it into the request
  192. if (data != null)
  193. {
  194. strBuffer = OSDParser.SerializeJsonString(data);
  195. tickJsondata = Util.EnvironmentTickCountSubtract(tickstart);
  196. if (DebugLevel >= 5)
  197. LogOutgoingDetail("SEND", reqnum, strBuffer);
  198. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer);
  199. request.ContentType = rpc ? "application/json-rpc" : "application/json";
  200. if (compressed)
  201. {
  202. request.Headers["X-Content-Encoding"] = "gzip"; // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding
  203. using (MemoryStream ms = new MemoryStream())
  204. {
  205. using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true))
  206. {
  207. comp.Write(buffer, 0, buffer.Length);
  208. // We need to close the gzip stream before we write it anywhere
  209. // because apparently something important related to gzip compression
  210. // gets written on the stream upon Dispose()
  211. }
  212. byte[] buf = ms.ToArray();
  213. tickcompressdata = Util.EnvironmentTickCountSubtract(tickstart);
  214. request.ContentLength = buf.Length; //Count bytes to send
  215. compsize = buf.Length;
  216. using (Stream requestStream = request.GetRequestStream())
  217. requestStream.Write(buf, 0, (int)buf.Length);
  218. }
  219. }
  220. else
  221. {
  222. compsize = buffer.Length;
  223. request.ContentLength = buffer.Length; //Count bytes to send
  224. using (Stream requestStream = request.GetRequestStream())
  225. requestStream.Write(buffer, 0, buffer.Length); //Send it
  226. }
  227. }
  228. // capture how much time was spent writing, this may seem silly
  229. // but with the number concurrent requests, this often blocks
  230. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  231. using (WebResponse response = request.GetResponse())
  232. {
  233. using (Stream responseStream = response.GetResponseStream())
  234. {
  235. using (StreamReader reader = new StreamReader(responseStream))
  236. {
  237. string responseStr = reader.ReadToEnd();
  238. if (WebUtil.DebugLevel >= 5)
  239. WebUtil.LogResponseDetail(reqnum, responseStr);
  240. return CanonicalizeResults(responseStr);
  241. }
  242. }
  243. }
  244. }
  245. catch (WebException we)
  246. {
  247. errorMessage = we.Message;
  248. if (we.Status == WebExceptionStatus.ProtocolError)
  249. {
  250. using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
  251. errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription);
  252. }
  253. }
  254. catch (Exception ex)
  255. {
  256. errorMessage = ex.Message;
  257. m_log.Debug("[WEB UTIL]: Exception making request: " + ex.ToString());
  258. }
  259. finally
  260. {
  261. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  262. if (tickdiff > LongCallTime)
  263. {
  264. m_log.InfoFormat(
  265. "[WEB UTIL]: Slow ServiceOSD request {0} {1} {2} took {3}ms, {4}ms writing({5} at Json; {6} at comp), {7} bytes ({8} uncomp): {9}",
  266. reqnum,
  267. method,
  268. url,
  269. tickdiff,
  270. tickdata,
  271. tickJsondata,
  272. tickcompressdata,
  273. compsize,
  274. strBuffer != null ? strBuffer.Length : 0,
  275. strBuffer != null
  276. ? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer)
  277. : "");
  278. }
  279. else if (DebugLevel >= 4)
  280. {
  281. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  282. reqnum, tickdiff, tickdata);
  283. }
  284. }
  285. m_log.DebugFormat(
  286. "[LOGHTTP]: JSON-RPC request {0} {1} to {2} FAILED: {3}", reqnum, method, url, errorMessage);
  287. return ErrorResponseMap(errorMessage);
  288. }
  289. /// <summary>
  290. /// Since there are no consistencies in the way web requests are
  291. /// formed, we need to do a little guessing about the result format.
  292. /// Keys:
  293. /// Success|success == the success fail of the request
  294. /// _RawResult == the raw string that came back
  295. /// _Result == the OSD unpacked string
  296. /// </summary>
  297. private static OSDMap CanonicalizeResults(string response)
  298. {
  299. OSDMap result = new OSDMap();
  300. // Default values
  301. result["Success"] = OSD.FromBoolean(true);
  302. result["success"] = OSD.FromBoolean(true);
  303. result["_RawResult"] = OSD.FromString(response);
  304. result["_Result"] = new OSDMap();
  305. if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase))
  306. return result;
  307. if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase))
  308. {
  309. result["Success"] = OSD.FromBoolean(false);
  310. result["success"] = OSD.FromBoolean(false);
  311. return result;
  312. }
  313. try
  314. {
  315. OSD responseOSD = OSDParser.Deserialize(response);
  316. if (responseOSD.Type == OSDType.Map)
  317. {
  318. result["_Result"] = (OSDMap)responseOSD;
  319. return result;
  320. }
  321. }
  322. catch
  323. {
  324. // don't need to treat this as an error... we're just guessing anyway
  325. // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message);
  326. }
  327. return result;
  328. }
  329. #endregion JSONRequest
  330. #region FormRequest
  331. /// <summary>
  332. /// POST URL-encoded form data to a web service that returns LLSD or
  333. /// JSON data
  334. /// </summary>
  335. public static OSDMap PostToService(string url, NameValueCollection data)
  336. {
  337. return ServiceFormRequest(url,data, 30000);
  338. }
  339. public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
  340. {
  341. int reqnum = RequestNumber++;
  342. string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
  343. if (DebugLevel >= 3)
  344. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} ServiceForm '{1}' to {2}",
  345. reqnum, method, url);
  346. string errorMessage = "unknown error";
  347. int tickstart = Util.EnvironmentTickCount();
  348. int tickdata = 0;
  349. string queryString = null;
  350. try
  351. {
  352. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  353. request.Method = "POST";
  354. request.Timeout = timeout;
  355. request.KeepAlive = false;
  356. request.MaximumAutomaticRedirections = 10;
  357. request.ReadWriteTimeout = timeout / 2;
  358. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  359. if (data != null)
  360. {
  361. queryString = BuildQueryString(data);
  362. if (DebugLevel >= 5)
  363. LogOutgoingDetail("SEND", reqnum, queryString);
  364. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString);
  365. request.ContentLength = buffer.Length;
  366. request.ContentType = "application/x-www-form-urlencoded";
  367. using (Stream requestStream = request.GetRequestStream())
  368. requestStream.Write(buffer, 0, buffer.Length);
  369. }
  370. // capture how much time was spent writing, this may seem silly
  371. // but with the number concurrent requests, this often blocks
  372. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  373. using (WebResponse response = request.GetResponse())
  374. {
  375. using (Stream responseStream = response.GetResponseStream())
  376. {
  377. using (StreamReader reader = new StreamReader(responseStream))
  378. {
  379. string responseStr = reader.ReadToEnd();
  380. if (WebUtil.DebugLevel >= 5)
  381. WebUtil.LogResponseDetail(reqnum, responseStr);
  382. OSD responseOSD = OSDParser.Deserialize(responseStr);
  383. if (responseOSD.Type == OSDType.Map)
  384. return (OSDMap)responseOSD;
  385. }
  386. }
  387. }
  388. }
  389. catch (WebException we)
  390. {
  391. errorMessage = we.Message;
  392. if (we.Status == WebExceptionStatus.ProtocolError)
  393. {
  394. using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
  395. errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
  396. }
  397. }
  398. catch (Exception ex)
  399. {
  400. errorMessage = ex.Message;
  401. }
  402. finally
  403. {
  404. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  405. if (tickdiff > LongCallTime)
  406. {
  407. m_log.InfoFormat(
  408. "[LOGHTTP]: Slow ServiceForm request {0} '{1}' to {2} took {3}ms, {4}ms writing, {5}",
  409. reqnum, method, url, tickdiff, tickdata,
  410. queryString != null
  411. ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString
  412. : "");
  413. }
  414. else if (DebugLevel >= 4)
  415. {
  416. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  417. reqnum, tickdiff, tickdata);
  418. }
  419. }
  420. m_log.WarnFormat("[LOGHTTP]: ServiceForm request {0} '{1}' to {2} failed: {3}", reqnum, method, url, errorMessage);
  421. return ErrorResponseMap(errorMessage);
  422. }
  423. /// <summary>
  424. /// Create a response map for an error, trying to keep
  425. /// the result formats consistent
  426. /// </summary>
  427. private static OSDMap ErrorResponseMap(string msg)
  428. {
  429. OSDMap result = new OSDMap();
  430. result["Success"] = "False";
  431. result["Message"] = OSD.FromString("Service request failed: " + msg);
  432. return result;
  433. }
  434. #endregion FormRequest
  435. #region Uri
  436. /// <summary>
  437. /// Combines a Uri that can contain both a base Uri and relative path
  438. /// with a second relative path fragment
  439. /// </summary>
  440. /// <param name="uri">Starting (base) Uri</param>
  441. /// <param name="fragment">Relative path fragment to append to the end
  442. /// of the Uri</param>
  443. /// <returns>The combined Uri</returns>
  444. /// <remarks>This is similar to the Uri constructor that takes a base
  445. /// Uri and the relative path, except this method can append a relative
  446. /// path fragment on to an existing relative path</remarks>
  447. public static Uri Combine(this Uri uri, string fragment)
  448. {
  449. string fragment1 = uri.Fragment;
  450. string fragment2 = fragment;
  451. if (!fragment1.EndsWith("/"))
  452. fragment1 = fragment1 + '/';
  453. if (fragment2.StartsWith("/"))
  454. fragment2 = fragment2.Substring(1);
  455. return new Uri(uri, fragment1 + fragment2);
  456. }
  457. /// <summary>
  458. /// Combines a Uri that can contain both a base Uri and relative path
  459. /// with a second relative path fragment. If the fragment is absolute,
  460. /// it will be returned without modification
  461. /// </summary>
  462. /// <param name="uri">Starting (base) Uri</param>
  463. /// <param name="fragment">Relative path fragment to append to the end
  464. /// of the Uri, or an absolute Uri to return unmodified</param>
  465. /// <returns>The combined Uri</returns>
  466. public static Uri Combine(this Uri uri, Uri fragment)
  467. {
  468. if (fragment.IsAbsoluteUri)
  469. return fragment;
  470. string fragment1 = uri.Fragment;
  471. string fragment2 = fragment.ToString();
  472. if (!fragment1.EndsWith("/"))
  473. fragment1 = fragment1 + '/';
  474. if (fragment2.StartsWith("/"))
  475. fragment2 = fragment2.Substring(1);
  476. return new Uri(uri, fragment1 + fragment2);
  477. }
  478. /// <summary>
  479. /// Appends a query string to a Uri that may or may not have existing
  480. /// query parameters
  481. /// </summary>
  482. /// <param name="uri">Uri to append the query to</param>
  483. /// <param name="query">Query string to append. Can either start with ?
  484. /// or just containg key/value pairs</param>
  485. /// <returns>String representation of the Uri with the query string
  486. /// appended</returns>
  487. public static string AppendQuery(this Uri uri, string query)
  488. {
  489. if (String.IsNullOrEmpty(query))
  490. return uri.ToString();
  491. if (query[0] == '?' || query[0] == '&')
  492. query = query.Substring(1);
  493. string uriStr = uri.ToString();
  494. if (uriStr.Contains("?"))
  495. return uriStr + '&' + query;
  496. else
  497. return uriStr + '?' + query;
  498. }
  499. #endregion Uri
  500. #region NameValueCollection
  501. /// <summary>
  502. /// Convert a NameValueCollection into a query string. This is the
  503. /// inverse of HttpUtility.ParseQueryString()
  504. /// </summary>
  505. /// <param name="parameters">Collection of key/value pairs to convert</param>
  506. /// <returns>A query string with URL-escaped values</returns>
  507. public static string BuildQueryString(NameValueCollection parameters)
  508. {
  509. List<string> items = new List<string>(parameters.Count);
  510. foreach (string key in parameters.Keys)
  511. {
  512. string[] values = parameters.GetValues(key);
  513. if (values != null)
  514. {
  515. foreach (string value in values)
  516. items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
  517. }
  518. }
  519. return String.Join("&", items.ToArray());
  520. }
  521. /// <summary>
  522. ///
  523. /// </summary>
  524. /// <param name="collection"></param>
  525. /// <param name="key"></param>
  526. /// <returns></returns>
  527. public static string GetOne(this NameValueCollection collection, string key)
  528. {
  529. string[] values = collection.GetValues(key);
  530. if (values != null && values.Length > 0)
  531. return values[0];
  532. return null;
  533. }
  534. #endregion NameValueCollection
  535. #region Stream
  536. /// <summary>
  537. /// Copies the contents of one stream to another, starting at the
  538. /// current position of each stream
  539. /// </summary>
  540. /// <param name="copyFrom">The stream to copy from, at the position
  541. /// where copying should begin</param>
  542. /// <param name="copyTo">The stream to copy to, at the position where
  543. /// bytes should be written</param>
  544. /// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
  545. /// <returns>The total number of bytes copied</returns>
  546. /// <remarks>
  547. /// Copying begins at the streams' current positions. The positions are
  548. /// NOT reset after copying is complete.
  549. /// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'.
  550. /// This function could be replaced with that method once we move
  551. /// totally to .NET 4.0. For versions before, this routine exists.
  552. /// This routine used to be named 'CopyTo' but the int parameter has
  553. /// a different meaning so this method was renamed to avoid any confusion.
  554. /// </remarks>
  555. public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
  556. {
  557. byte[] buffer = new byte[4096];
  558. int readBytes;
  559. int totalCopiedBytes = 0;
  560. while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
  561. {
  562. int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
  563. copyTo.Write(buffer, 0, writeBytes);
  564. totalCopiedBytes += writeBytes;
  565. maximumBytesToCopy -= writeBytes;
  566. }
  567. return totalCopiedBytes;
  568. }
  569. #endregion Stream
  570. public class QBasedComparer : IComparer
  571. {
  572. public int Compare(Object x, Object y)
  573. {
  574. float qx = GetQ(x);
  575. float qy = GetQ(y);
  576. return qy.CompareTo(qx); // descending order
  577. }
  578. private float GetQ(Object o)
  579. {
  580. // Example: image/png;q=0.9
  581. float qvalue = 1F;
  582. if (o is String)
  583. {
  584. string mime = (string)o;
  585. string[] parts = mime.Split(';');
  586. if (parts.Length > 1)
  587. {
  588. string[] kvp = parts[1].Split('=');
  589. if (kvp.Length == 2 && kvp[0] == "q")
  590. float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue);
  591. }
  592. }
  593. return qvalue;
  594. }
  595. }
  596. /// <summary>
  597. /// Takes the value of an Accept header and returns the preferred types
  598. /// ordered by q value (if it exists).
  599. /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2
  600. /// Exmaple output: ["jp2", "png", "jpg"]
  601. /// NOTE: This doesn't handle the semantics of *'s...
  602. /// </summary>
  603. /// <param name="accept"></param>
  604. /// <returns></returns>
  605. public static string[] GetPreferredImageTypes(string accept)
  606. {
  607. if (string.IsNullOrEmpty(accept))
  608. return new string[0];
  609. string[] types = accept.Split(new char[] { ',' });
  610. if (types.Length > 0)
  611. {
  612. List<string> list = new List<string>(types);
  613. list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); });
  614. ArrayList tlist = new ArrayList(list);
  615. tlist.Sort(new QBasedComparer());
  616. string[] result = new string[tlist.Count];
  617. for (int i = 0; i < tlist.Count; i++)
  618. {
  619. string mime = (string)tlist[i];
  620. string[] parts = mime.Split(new char[] { ';' });
  621. string[] pair = parts[0].Split(new char[] { '/' });
  622. if (pair.Length == 2)
  623. result[i] = pair[1].ToLower();
  624. else // oops, we don't know what this is...
  625. result[i] = pair[0];
  626. }
  627. return result;
  628. }
  629. return new string[0];
  630. }
  631. }
  632. public static class AsynchronousRestObjectRequester
  633. {
  634. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  635. /// <summary>
  636. /// Perform an asynchronous REST request.
  637. /// </summary>
  638. /// <param name="verb">GET or POST</param>
  639. /// <param name="requestUrl"></param>
  640. /// <param name="obj"></param>
  641. /// <param name="action"></param>
  642. /// <returns></returns>
  643. ///
  644. /// <exception cref="System.Net.WebException">Thrown if we encounter a
  645. /// network issue while posting the request. You'll want to make
  646. /// sure you deal with this as they're not uncommon</exception>
  647. //
  648. public static void MakeRequest<TRequest, TResponse>(string verb,
  649. string requestUrl, TRequest obj, Action<TResponse> action)
  650. {
  651. MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, 0);
  652. }
  653. public static void MakeRequest<TRequest, TResponse>(string verb,
  654. string requestUrl, TRequest obj, Action<TResponse> action,
  655. int maxConnections)
  656. {
  657. MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, maxConnections, null);
  658. }
  659. /// <summary>
  660. /// Perform a synchronous REST request.
  661. /// </summary>
  662. /// <param name="verb"></param>
  663. /// <param name="requestUrl"></param>
  664. /// <param name="obj"></param>
  665. /// <param name="pTimeout">
  666. /// Request timeout in seconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
  667. /// </param>
  668. /// <param name="maxConnections"></param>
  669. /// <returns>
  670. /// The response. If there was an internal exception or the request timed out,
  671. /// then the default(TResponse) is returned.
  672. /// </returns>
  673. public static void MakeRequest<TRequest, TResponse>(string verb,
  674. string requestUrl, TRequest obj, Action<TResponse> action,
  675. int maxConnections, IServiceAuth auth)
  676. {
  677. int reqnum = WebUtil.RequestNumber++;
  678. if (WebUtil.DebugLevel >= 3)
  679. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} AsynchronousRequestObject {1} to {2}",
  680. reqnum, verb, requestUrl);
  681. int tickstart = Util.EnvironmentTickCount();
  682. int tickdata = 0;
  683. int tickdiff = 0;
  684. Type type = typeof(TRequest);
  685. WebRequest request = WebRequest.Create(requestUrl);
  686. HttpWebRequest ht = (HttpWebRequest)request;
  687. if (auth != null)
  688. auth.AddAuthorization(ht.Headers);
  689. if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections)
  690. ht.ServicePoint.ConnectionLimit = maxConnections;
  691. TResponse deserial = default(TResponse);
  692. request.Method = verb;
  693. MemoryStream buffer = null;
  694. try
  695. {
  696. if (verb == "POST")
  697. {
  698. request.ContentType = "text/xml";
  699. buffer = new MemoryStream();
  700. XmlWriterSettings settings = new XmlWriterSettings();
  701. settings.Encoding = Encoding.UTF8;
  702. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  703. {
  704. XmlSerializer serializer = new XmlSerializer(type);
  705. serializer.Serialize(writer, obj);
  706. writer.Flush();
  707. }
  708. int length = (int)buffer.Length;
  709. request.ContentLength = length;
  710. byte[] data = buffer.ToArray();
  711. if (WebUtil.DebugLevel >= 5)
  712. WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
  713. request.BeginGetRequestStream(delegate(IAsyncResult res)
  714. {
  715. using (Stream requestStream = request.EndGetRequestStream(res))
  716. requestStream.Write(data, 0, length);
  717. // capture how much time was spent writing
  718. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  719. request.BeginGetResponse(delegate(IAsyncResult ar)
  720. {
  721. using (WebResponse response = request.EndGetResponse(ar))
  722. {
  723. try
  724. {
  725. using (Stream respStream = response.GetResponseStream())
  726. {
  727. deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>(
  728. reqnum, respStream, response.ContentLength);
  729. }
  730. }
  731. catch (System.InvalidOperationException)
  732. {
  733. }
  734. }
  735. action(deserial);
  736. }, null);
  737. }, null);
  738. }
  739. else
  740. {
  741. request.BeginGetResponse(delegate(IAsyncResult res2)
  742. {
  743. try
  744. {
  745. // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
  746. // documented in MSDN
  747. using (WebResponse response = request.EndGetResponse(res2))
  748. {
  749. try
  750. {
  751. using (Stream respStream = response.GetResponseStream())
  752. {
  753. deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>(
  754. reqnum, respStream, response.ContentLength);
  755. }
  756. }
  757. catch (System.InvalidOperationException)
  758. {
  759. }
  760. }
  761. }
  762. catch (WebException e)
  763. {
  764. if (e.Status == WebExceptionStatus.ProtocolError)
  765. {
  766. if (e.Response is HttpWebResponse)
  767. {
  768. using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response)
  769. {
  770. if (httpResponse.StatusCode != HttpStatusCode.NotFound)
  771. {
  772. // We don't appear to be handling any other status codes, so log these feailures to that
  773. // people don't spend unnecessary hours hunting phantom bugs.
  774. m_log.DebugFormat(
  775. "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
  776. verb, requestUrl, httpResponse.StatusCode);
  777. }
  778. }
  779. }
  780. }
  781. else
  782. {
  783. m_log.ErrorFormat(
  784. "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}",
  785. verb, requestUrl, e.Status, e.Message);
  786. }
  787. }
  788. catch (Exception e)
  789. {
  790. m_log.ErrorFormat(
  791. "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}",
  792. verb, requestUrl, e.Message, e.StackTrace);
  793. }
  794. // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
  795. try
  796. {
  797. action(deserial);
  798. }
  799. catch (Exception e)
  800. {
  801. m_log.ErrorFormat(
  802. "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}",
  803. verb, requestUrl, e.Message, e.StackTrace);
  804. }
  805. }, null);
  806. }
  807. tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  808. if (tickdiff > WebUtil.LongCallTime)
  809. {
  810. string originalRequest = null;
  811. if (buffer != null)
  812. {
  813. originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
  814. if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
  815. originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
  816. }
  817. m_log.InfoFormat(
  818. "[LOGHTTP]: Slow AsynchronousRequestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}",
  819. reqnum, verb, requestUrl, tickdiff, tickdata,
  820. originalRequest);
  821. }
  822. else if (WebUtil.DebugLevel >= 4)
  823. {
  824. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  825. reqnum, tickdiff, tickdata);
  826. }
  827. }
  828. finally
  829. {
  830. if (buffer != null)
  831. buffer.Dispose();
  832. }
  833. }
  834. }
  835. public static class SynchronousRestFormsRequester
  836. {
  837. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  838. /// <summary>
  839. /// Perform a synchronous REST request.
  840. /// </summary>
  841. /// <param name="verb"></param>
  842. /// <param name="requestUrl"></param>
  843. /// <param name="obj"> </param>
  844. /// <param name="timeoutsecs"> </param>
  845. /// <returns></returns>
  846. ///
  847. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  848. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  849. public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs = -1,
  850. IServiceAuth auth = null, bool keepalive = true)
  851. {
  852. int reqnum = WebUtil.RequestNumber++;
  853. if (WebUtil.DebugLevel >= 3)
  854. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms {1} to {2}",
  855. reqnum, verb, requestUrl);
  856. int tickstart = Util.EnvironmentTickCount();
  857. int tickdata = 0;
  858. WebRequest request = WebRequest.Create(requestUrl);
  859. request.Method = verb;
  860. if (timeoutsecs > 0)
  861. request.Timeout = timeoutsecs * 1000;
  862. if(!keepalive && request is HttpWebRequest)
  863. ((HttpWebRequest)request).KeepAlive = false;
  864. if (auth != null)
  865. auth.AddAuthorization(request.Headers);
  866. string respstring = String.Empty;
  867. int tickset = Util.EnvironmentTickCountSubtract(tickstart);
  868. using (MemoryStream buffer = new MemoryStream())
  869. {
  870. if ((verb == "POST") || (verb == "PUT"))
  871. {
  872. request.ContentType = "application/x-www-form-urlencoded";
  873. int length = 0;
  874. using (StreamWriter writer = new StreamWriter(buffer))
  875. {
  876. writer.Write(obj);
  877. writer.Flush();
  878. }
  879. length = (int)obj.Length;
  880. request.ContentLength = length;
  881. byte[] data = buffer.ToArray();
  882. if (WebUtil.DebugLevel >= 5)
  883. WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
  884. try
  885. {
  886. using(Stream requestStream = request.GetRequestStream())
  887. requestStream.Write(data,0,length);
  888. }
  889. catch (Exception e)
  890. {
  891. m_log.InfoFormat("[FORMS]: Error sending request to {0}: {1}. Request: {2}", requestUrl, e.Message,
  892. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  893. throw e;
  894. }
  895. finally
  896. {
  897. // capture how much time was spent writing
  898. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  899. }
  900. }
  901. try
  902. {
  903. using (WebResponse resp = request.GetResponse())
  904. {
  905. if (resp.ContentLength != 0)
  906. {
  907. using (Stream respStream = resp.GetResponseStream())
  908. using (StreamReader reader = new StreamReader(respStream))
  909. respstring = reader.ReadToEnd();
  910. }
  911. }
  912. }
  913. catch (Exception e)
  914. {
  915. m_log.InfoFormat("[FORMS]: Error receiving response from {0}: {1}. Request: {2}", requestUrl, e.Message,
  916. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  917. throw e;
  918. }
  919. }
  920. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  921. if (tickdiff > WebUtil.LongCallTime)
  922. {
  923. m_log.InfoFormat(
  924. "[FORMS]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
  925. reqnum,
  926. verb,
  927. requestUrl,
  928. tickdiff,
  929. tickset,
  930. tickdata,
  931. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  932. }
  933. else if (WebUtil.DebugLevel >= 4)
  934. {
  935. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  936. reqnum, tickdiff, tickdata);
  937. }
  938. if (WebUtil.DebugLevel >= 5)
  939. WebUtil.LogResponseDetail(reqnum, respstring);
  940. return respstring;
  941. }
  942. public static string MakeRequest(string verb, string requestUrl, string obj, IServiceAuth auth)
  943. {
  944. return MakeRequest(verb, requestUrl, obj, -1, auth);
  945. }
  946. }
  947. public class SynchronousRestObjectRequester
  948. {
  949. private static readonly ILog m_log =
  950. LogManager.GetLogger(
  951. MethodBase.GetCurrentMethod().DeclaringType);
  952. /// <summary>
  953. /// Perform a synchronous REST request.
  954. /// </summary>
  955. /// <param name="verb"></param>
  956. /// <param name="requestUrl"></param>
  957. /// <param name="obj"></param>
  958. /// <returns>
  959. /// The response. If there was an internal exception, then the default(TResponse) is returned.
  960. /// </returns>
  961. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
  962. {
  963. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0);
  964. }
  965. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, IServiceAuth auth)
  966. {
  967. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0, auth);
  968. }
  969. /// <summary>
  970. /// Perform a synchronous REST request.
  971. /// </summary>
  972. /// <param name="verb"></param>
  973. /// <param name="requestUrl"></param>
  974. /// <param name="obj"></param>
  975. /// <param name="pTimeout">
  976. /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
  977. /// </param>
  978. /// <returns>
  979. /// The response. If there was an internal exception or the request timed out,
  980. /// then the default(TResponse) is returned.
  981. /// </returns>
  982. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout)
  983. {
  984. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0);
  985. }
  986. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, IServiceAuth auth)
  987. {
  988. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0, auth);
  989. }
  990. /// Perform a synchronous REST request.
  991. /// </summary>
  992. /// <param name="verb"></param>
  993. /// <param name="requestUrl"></param>
  994. /// <param name="obj"></param>
  995. /// <param name="pTimeout">
  996. /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
  997. /// </param>
  998. /// <param name="maxConnections"></param>
  999. /// <returns>
  1000. /// The response. If there was an internal exception or the request timed out,
  1001. /// then the default(TResponse) is returned.
  1002. /// </returns>
  1003. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections)
  1004. {
  1005. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, maxConnections, null);
  1006. }
  1007. /// <summary>
  1008. /// Perform a synchronous REST request.
  1009. /// </summary>
  1010. /// <param name="verb"></param>
  1011. /// <param name="requestUrl"></param>
  1012. /// <param name="obj"></param>
  1013. /// <param name="pTimeout">
  1014. /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds)
  1015. /// </param>
  1016. /// <param name="maxConnections"></param>
  1017. /// <returns>
  1018. /// The response. If there was an internal exception or the request timed out,
  1019. /// then the default(TResponse) is returned.
  1020. /// </returns>
  1021. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections, IServiceAuth auth)
  1022. {
  1023. int reqnum = WebUtil.RequestNumber++;
  1024. if (WebUtil.DebugLevel >= 3)
  1025. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestObject {1} to {2}",
  1026. reqnum, verb, requestUrl);
  1027. int tickstart = Util.EnvironmentTickCount();
  1028. int tickdata = 0;
  1029. Type type = typeof(TRequest);
  1030. TResponse deserial = default(TResponse);
  1031. WebRequest request = WebRequest.Create(requestUrl);
  1032. HttpWebRequest ht = (HttpWebRequest)request;
  1033. if (auth != null)
  1034. auth.AddAuthorization(ht.Headers);
  1035. if (pTimeout != 0)
  1036. request.Timeout = pTimeout;
  1037. if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections)
  1038. ht.ServicePoint.ConnectionLimit = maxConnections;
  1039. request.Method = verb;
  1040. MemoryStream buffer = null;
  1041. try
  1042. {
  1043. if ((verb == "POST") || (verb == "PUT"))
  1044. {
  1045. request.ContentType = "text/xml";
  1046. buffer = new MemoryStream();
  1047. XmlWriterSettings settings = new XmlWriterSettings();
  1048. settings.Encoding = Encoding.UTF8;
  1049. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  1050. {
  1051. XmlSerializer serializer = new XmlSerializer(type);
  1052. serializer.Serialize(writer, obj);
  1053. writer.Flush();
  1054. }
  1055. int length = (int)buffer.Length;
  1056. request.ContentLength = length;
  1057. byte[] data = buffer.ToArray();
  1058. if (WebUtil.DebugLevel >= 5)
  1059. WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data));
  1060. try
  1061. {
  1062. using (Stream requestStream = request.GetRequestStream())
  1063. requestStream.Write(data, 0, length);
  1064. }
  1065. catch (Exception e)
  1066. {
  1067. m_log.DebugFormat(
  1068. "[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}",
  1069. verb, requestUrl, e.Message, e.StackTrace);
  1070. return deserial;
  1071. }
  1072. finally
  1073. {
  1074. // capture how much time was spent writing
  1075. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  1076. }
  1077. }
  1078. try
  1079. {
  1080. using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
  1081. {
  1082. if (resp.ContentLength != 0)
  1083. {
  1084. using (Stream respStream = resp.GetResponseStream())
  1085. {
  1086. deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>(
  1087. reqnum, respStream, resp.ContentLength);
  1088. }
  1089. }
  1090. else
  1091. {
  1092. m_log.DebugFormat(
  1093. "[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}",
  1094. verb, requestUrl);
  1095. }
  1096. }
  1097. }
  1098. catch (WebException e)
  1099. {
  1100. using (HttpWebResponse hwr = (HttpWebResponse)e.Response)
  1101. {
  1102. if (hwr != null)
  1103. {
  1104. if (hwr.StatusCode == HttpStatusCode.NotFound)
  1105. return deserial;
  1106. if (hwr.StatusCode == HttpStatusCode.Unauthorized)
  1107. {
  1108. m_log.ErrorFormat("[SynchronousRestObjectRequester]: Web request {0} requires authentication",
  1109. requestUrl);
  1110. }
  1111. else
  1112. {
  1113. m_log.WarnFormat("[SynchronousRestObjectRequester]: Web request {0} returned error: {1}",
  1114. requestUrl, hwr.StatusCode);
  1115. }
  1116. }
  1117. else
  1118. m_log.ErrorFormat(
  1119. "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} {3}",
  1120. verb, requestUrl, typeof(TResponse).ToString(), e.Message);
  1121. return deserial;
  1122. }
  1123. }
  1124. catch (System.InvalidOperationException)
  1125. {
  1126. // This is what happens when there is invalid XML
  1127. m_log.DebugFormat(
  1128. "[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}",
  1129. verb, requestUrl, typeof(TResponse).ToString());
  1130. }
  1131. catch (Exception e)
  1132. {
  1133. m_log.Debug(string.Format(
  1134. "[SynchronousRestObjectRequester]: Exception on response from {0} {1} ",
  1135. verb, requestUrl), e);
  1136. }
  1137. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  1138. if (tickdiff > WebUtil.LongCallTime)
  1139. {
  1140. string originalRequest = null;
  1141. if (buffer != null)
  1142. {
  1143. originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
  1144. if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
  1145. originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
  1146. }
  1147. m_log.InfoFormat(
  1148. "[LOGHTTP]: Slow SynchronousRestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}",
  1149. reqnum, verb, requestUrl, tickdiff, tickdata,
  1150. originalRequest);
  1151. }
  1152. else if (WebUtil.DebugLevel >= 4)
  1153. {
  1154. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  1155. reqnum, tickdiff, tickdata);
  1156. }
  1157. }
  1158. finally
  1159. {
  1160. if (buffer != null)
  1161. buffer.Dispose();
  1162. }
  1163. return deserial;
  1164. }
  1165. public static class XMLResponseHelper
  1166. {
  1167. public static TResponse LogAndDeserialize<TRequest, TResponse>(int reqnum, Stream respStream, long contentLength)
  1168. {
  1169. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  1170. if (WebUtil.DebugLevel >= 5)
  1171. {
  1172. const int blockLength = 4096;
  1173. byte[] dataBuffer = new byte[blockLength];
  1174. int curcount;
  1175. using (MemoryStream ms = new MemoryStream(4 * blockLength))
  1176. {
  1177. if(contentLength == -1)
  1178. {
  1179. while (true)
  1180. {
  1181. curcount = respStream.Read(dataBuffer, 0, blockLength);
  1182. if (curcount <= 0)
  1183. break;
  1184. ms.Write(dataBuffer, 0, curcount);
  1185. }
  1186. }
  1187. else
  1188. {
  1189. int remaining = (int)contentLength;
  1190. while (remaining > 0)
  1191. {
  1192. curcount = respStream.Read(dataBuffer, 0, remaining);
  1193. if (curcount <= 0)
  1194. throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
  1195. ms.Write(dataBuffer, 0, curcount);
  1196. remaining -= curcount;
  1197. }
  1198. }
  1199. dataBuffer = ms.ToArray();
  1200. WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(dataBuffer));
  1201. ms.Position = 0;
  1202. return (TResponse)deserializer.Deserialize(ms);
  1203. }
  1204. }
  1205. else
  1206. {
  1207. return (TResponse)deserializer.Deserialize(respStream);
  1208. }
  1209. }
  1210. }
  1211. }
  1212. public static class XMLRPCRequester
  1213. {
  1214. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1215. public static Hashtable SendRequest(Hashtable ReqParams, string method, string url)
  1216. {
  1217. int reqnum = WebUtil.RequestNumber++;
  1218. if (WebUtil.DebugLevel >= 3)
  1219. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} XML-RPC '{1}' to {2}",
  1220. reqnum, method, url);
  1221. int tickstart = Util.EnvironmentTickCount();
  1222. string responseStr = null;
  1223. try
  1224. {
  1225. ArrayList SendParams = new ArrayList();
  1226. SendParams.Add(ReqParams);
  1227. XmlRpcRequest Req = new XmlRpcRequest(method, SendParams);
  1228. if (WebUtil.DebugLevel >= 5)
  1229. {
  1230. string str = Req.ToString();
  1231. str = XElement.Parse(str).ToString(SaveOptions.DisableFormatting);
  1232. WebUtil.LogOutgoingDetail("SEND", reqnum, str);
  1233. }
  1234. XmlRpcResponse Resp = Req.Send(url, 30000);
  1235. try
  1236. {
  1237. responseStr = Resp.ToString();
  1238. responseStr = XElement.Parse(responseStr).ToString(SaveOptions.DisableFormatting);
  1239. if (WebUtil.DebugLevel >= 5)
  1240. WebUtil.LogResponseDetail(reqnum, responseStr);
  1241. }
  1242. catch (Exception e)
  1243. {
  1244. m_log.Error("Error parsing XML-RPC response", e);
  1245. }
  1246. if (Resp.IsFault)
  1247. {
  1248. m_log.DebugFormat(
  1249. "[LOGHTTP]: XML-RPC request {0} '{1}' to {2} FAILED: FaultCode={3}, FaultMessage={4}",
  1250. reqnum, method, url, Resp.FaultCode, Resp.FaultString);
  1251. return null;
  1252. }
  1253. Hashtable RespData = (Hashtable)Resp.Value;
  1254. return RespData;
  1255. }
  1256. finally
  1257. {
  1258. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  1259. if (tickdiff > WebUtil.LongCallTime)
  1260. {
  1261. m_log.InfoFormat(
  1262. "[LOGHTTP]: Slow XML-RPC request {0} '{1}' to {2} took {3}ms, {4}",
  1263. reqnum, method, url, tickdiff,
  1264. responseStr != null
  1265. ? (responseStr.Length > WebUtil.MaxRequestDiagLength ? responseStr.Remove(WebUtil.MaxRequestDiagLength) : responseStr)
  1266. : "");
  1267. }
  1268. else if (WebUtil.DebugLevel >= 4)
  1269. {
  1270. m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff);
  1271. }
  1272. }
  1273. }
  1274. }
  1275. }