1
0

WebUtil.cs 68 KB

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