WebUtil.cs 59 KB

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