WebUtil.cs 60 KB

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