1
0

WebUtil.cs 58 KB

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