ScriptsHttpRequests.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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.Generic;
  29. using System.Collections.Concurrent;
  30. using System.IO;
  31. using System.Net;
  32. using System.Net.Security;
  33. using System.Security.Cryptography.X509Certificates;
  34. using System.Threading;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Monitoring;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using Mono.Addins;
  42. /*****************************************************
  43. *
  44. * ScriptsHttpRequests
  45. *
  46. * Implements the llHttpRequest and http_response
  47. * callback.
  48. *
  49. * This is a non shared module with shared static parts
  50. * **************************************************/
  51. namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
  52. {
  53. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
  54. public class HttpRequestModule : INonSharedRegionModule, IHttpRequestModule
  55. {
  56. private struct ThrottleData
  57. {
  58. public double lastTime;
  59. public float control;
  60. }
  61. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  62. private static readonly object m_mainLock = new object();
  63. private static int m_numberScenes;
  64. private static int m_httpTimeout = 30000;
  65. private static readonly string m_name = "HttpScriptRequests";
  66. private static OutboundUrlFilter m_outboundUrlFilter;
  67. private static string m_proxyurl = "";
  68. private static string m_proxyexcepts = "";
  69. private static float m_primPerSec = 1.0f;
  70. private static float m_primBurst = 3.0f;
  71. private static float m_primOwnerPerSec = 25.0f;
  72. private static float m_primOwnerBurst = 5.0f;
  73. public static JobEngine m_jobEngine = null;
  74. private static Dictionary<UUID, HttpRequestClass> m_pendingRequests;
  75. //this are per region/module
  76. private readonly ConcurrentQueue<HttpRequestClass> m_CompletedRequests = new ConcurrentQueue<HttpRequestClass>();
  77. private readonly ConcurrentDictionary<uint, ThrottleData> m_RequestsThrottle = new ConcurrentDictionary<uint, ThrottleData>();
  78. private readonly ConcurrentDictionary<UUID, ThrottleData> m_OwnerRequestsThrottle = new ConcurrentDictionary<UUID, ThrottleData>();
  79. public HttpRequestModule()
  80. {
  81. }
  82. #region INonSharedRegionModule Members
  83. public void Initialise(IConfigSource config)
  84. {
  85. lock (m_mainLock)
  86. {
  87. // shared items
  88. if (m_jobEngine == null)
  89. {
  90. m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
  91. m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
  92. HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384);
  93. m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
  94. int maxThreads = 8;
  95. IConfig httpConfig = config.Configs["ScriptsHttpRequestModule"];
  96. if (httpConfig != null)
  97. {
  98. maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads);
  99. m_primBurst = httpConfig.GetFloat("PrimRequestsBurst", m_primBurst);
  100. m_primPerSec = httpConfig.GetFloat("PrimRequestsPerSec", m_primPerSec);
  101. m_primOwnerBurst = httpConfig.GetFloat("PrimOwnerRequestsBurst", m_primOwnerBurst);
  102. m_primOwnerPerSec = httpConfig.GetFloat("PrimOwnerRequestsPerSec", m_primOwnerPerSec);
  103. m_httpTimeout = httpConfig.GetInt("RequestsTimeOut", m_httpTimeout);
  104. if (m_httpTimeout > 60000)
  105. m_httpTimeout = 60000;
  106. else if (m_httpTimeout < 200)
  107. m_httpTimeout = 200;
  108. }
  109. m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
  110. m_jobEngine = new JobEngine("ScriptsHttpReq", "ScriptsHttpReq", 2000, maxThreads);
  111. m_jobEngine.Start();
  112. }
  113. }
  114. }
  115. public void AddRegion(Scene scene)
  116. {
  117. scene.RegisterModuleInterface<IHttpRequestModule>(this);
  118. Interlocked.Increment(ref m_numberScenes);
  119. }
  120. public void RemoveRegion(Scene scene)
  121. {
  122. scene.UnregisterModuleInterface<IHttpRequestModule>(this);
  123. }
  124. public void PostInitialise()
  125. {
  126. }
  127. public void RegionLoaded(Scene scene)
  128. {
  129. }
  130. public void Close()
  131. {
  132. int n = Interlocked.Decrement(ref m_numberScenes);
  133. if (n == 0)
  134. {
  135. lock(m_mainLock)
  136. {
  137. if (m_jobEngine != null)
  138. {
  139. m_jobEngine.Stop();
  140. m_jobEngine = null;
  141. }
  142. }
  143. }
  144. }
  145. public string Name
  146. {
  147. get { return m_name; }
  148. }
  149. public Type ReplaceableInterface
  150. {
  151. get { return null; }
  152. }
  153. #endregion
  154. #region IHttpRequestModule Members
  155. public UUID MakeHttpRequest(string url, string parameters, string body)
  156. {
  157. return UUID.Zero;
  158. }
  159. public bool CheckThrottle(uint localID, UUID ownerID)
  160. {
  161. double now = Util.GetTimeStamp();
  162. bool ret;
  163. if (m_RequestsThrottle.TryGetValue(localID, out ThrottleData th))
  164. {
  165. double delta = now - th.lastTime;
  166. th.lastTime = now;
  167. float add = (float)(m_primPerSec * delta);
  168. th.control += add;
  169. if (th.control > m_primBurst)
  170. {
  171. th.control = m_primBurst - 1;
  172. ret = true;
  173. }
  174. else
  175. {
  176. ret = th.control > 0;
  177. if (ret)
  178. th.control--;
  179. }
  180. }
  181. else
  182. {
  183. th = new ThrottleData()
  184. {
  185. lastTime = now,
  186. control = m_primBurst - 1,
  187. };
  188. ret = true;
  189. }
  190. m_RequestsThrottle[localID] = th;
  191. if(!ret)
  192. return false;
  193. if (m_OwnerRequestsThrottle.TryGetValue(ownerID, out th))
  194. {
  195. double delta = now - th.lastTime;
  196. th.lastTime = now;
  197. float add = (float)(m_primOwnerPerSec * delta);
  198. th.control += add;
  199. if (th.control > m_primOwnerBurst)
  200. th.control = m_primOwnerBurst - 1;
  201. else
  202. {
  203. ret = th.control > 0;
  204. if (ret)
  205. th.control--;
  206. }
  207. }
  208. else
  209. {
  210. th = new ThrottleData()
  211. {
  212. lastTime = now,
  213. control = m_primBurst - 1
  214. };
  215. }
  216. m_OwnerRequestsThrottle[ownerID] = th;
  217. return ret;
  218. }
  219. public UUID StartHttpRequest(
  220. uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
  221. out HttpInitialRequestStatus status)
  222. {
  223. if (!CheckAllowed(new Uri(url)))
  224. {
  225. status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
  226. return UUID.Zero;
  227. }
  228. UUID reqID = UUID.Random();
  229. HttpRequestClass htc = new HttpRequestClass();
  230. // Partial implementation: support for parameter flags needed
  231. // see http://wiki.secondlife.com/wiki/LlHTTPRequest
  232. //
  233. // Parameters are expected in {key, value, ... , key, value}
  234. if (parameters != null)
  235. {
  236. string[] parms = parameters.ToArray();
  237. for (int i = 0; i < parms.Length; i += 2)
  238. {
  239. switch (Int32.Parse(parms[i]))
  240. {
  241. case (int)HttpRequestConstants.HTTP_METHOD:
  242. htc.HttpMethod = parms[i + 1];
  243. break;
  244. case (int)HttpRequestConstants.HTTP_MIMETYPE:
  245. htc.HttpMIMEType = parms[i + 1];
  246. break;
  247. case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
  248. int len;
  249. if(int.TryParse(parms[i + 1], out len))
  250. {
  251. if(len > HttpRequestClass.HttpBodyMaxLenMAX)
  252. len = HttpRequestClass.HttpBodyMaxLenMAX;
  253. else if(len < 64) //???
  254. len = 64;
  255. htc.HttpBodyMaxLen = len;
  256. }
  257. break;
  258. case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
  259. htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
  260. break;
  261. case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
  262. // TODO implement me
  263. break;
  264. case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
  265. //Parameters are in pairs and custom header takes
  266. //arguments in pairs so adjust for header marker.
  267. ++i;
  268. //Maximum of 8 headers are allowed based on the
  269. //Second Life documentation for llHTTPRequest.
  270. for (int count = 1; count <= 8; ++count)
  271. {
  272. //Not enough parameters remaining for a header?
  273. if (parms.Length - i < 2)
  274. break;
  275. if (htc.HttpCustomHeaders == null)
  276. htc.HttpCustomHeaders = new List<string>();
  277. htc.HttpCustomHeaders.Add(parms[i]);
  278. htc.HttpCustomHeaders.Add(parms[i+1]);
  279. int nexti = i + 2;
  280. if (nexti >= parms.Length || Char.IsDigit(parms[nexti][0]))
  281. break;
  282. i = nexti;
  283. }
  284. break;
  285. case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
  286. htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
  287. break;
  288. }
  289. }
  290. }
  291. htc.RequestModule = this;
  292. htc.LocalID = localID;
  293. htc.ItemID = itemID;
  294. htc.Url = url;
  295. htc.ReqID = reqID;
  296. htc.HttpTimeout = m_httpTimeout;
  297. htc.OutboundBody = body;
  298. htc.ResponseHeaders = headers;
  299. htc.proxyurl = m_proxyurl;
  300. htc.proxyexcepts = m_proxyexcepts;
  301. // Same number as default HttpWebRequest.MaximumAutomaticRedirections
  302. htc.MaxRedirects = 50;
  303. lock (m_mainLock)
  304. m_pendingRequests.Add(reqID, htc);
  305. htc.Process();
  306. status = HttpInitialRequestStatus.OK;
  307. return reqID;
  308. }
  309. /// <summary>
  310. /// Would a caller to this module be allowed to make a request to the given URL?
  311. /// </summary>
  312. /// <returns></returns>
  313. public bool CheckAllowed(Uri url)
  314. {
  315. return m_outboundUrlFilter.CheckAllowed(url);
  316. }
  317. public void StopHttpRequest(uint localID, UUID m_itemID)
  318. {
  319. List<UUID> toremove = new List<UUID>();
  320. lock (m_mainLock)
  321. {
  322. foreach (HttpRequestClass tmpReq in m_pendingRequests.Values)
  323. {
  324. if(tmpReq.ItemID == m_itemID)
  325. {
  326. tmpReq.Stop();
  327. toremove.Add(tmpReq.ReqID);
  328. }
  329. }
  330. foreach(UUID id in toremove)
  331. m_pendingRequests.Remove(id);
  332. }
  333. if (m_RequestsThrottle.TryGetValue(localID, out ThrottleData th))
  334. {
  335. if (th.control + m_primOwnerPerSec * (Util.GetTimeStamp() - th.lastTime) >= m_primBurst)
  336. m_RequestsThrottle.TryRemove(localID, out ThrottleData dummy);
  337. }
  338. }
  339. /*
  340. * TODO
  341. * Not sure how important ordering is is here - the next first
  342. * one completed in the list is returned, based soley on its list
  343. * position, not the order in which the request was started or
  344. * finished. I thought about setting up a queue for this, but
  345. * it will need some refactoring and this works 'enough' right now
  346. */
  347. public void GotCompletedRequest(HttpRequestClass req)
  348. {
  349. lock (m_mainLock)
  350. {
  351. m_pendingRequests.Remove(req.ReqID);
  352. if (!req.Removed)
  353. m_CompletedRequests.Enqueue(req);
  354. }
  355. }
  356. public IServiceRequest GetNextCompletedRequest()
  357. {
  358. if(m_CompletedRequests.TryDequeue(out HttpRequestClass req))
  359. return req;
  360. return null;
  361. }
  362. public void RemoveCompletedRequest(UUID reqId)
  363. {
  364. lock (m_mainLock)
  365. {
  366. if (m_pendingRequests.TryGetValue(reqId, out HttpRequestClass tmpReq))
  367. {
  368. tmpReq.Stop();
  369. m_pendingRequests.Remove(reqId);
  370. }
  371. }
  372. }
  373. #endregion
  374. }
  375. public class HttpRequestClass : IServiceRequest
  376. {
  377. // Constants for parameters
  378. // public const int HTTP_BODY_MAXLENGTH = 2;
  379. // public const int HTTP_METHOD = 0;
  380. // public const int HTTP_MIMETYPE = 1;
  381. // public const int HTTP_VERIFY_CERT = 3;
  382. // public const int HTTP_VERBOSE_THROTTLE = 4;
  383. // public const int HTTP_CUSTOM_HEADER = 5;
  384. // public const int HTTP_PRAGMA_NO_CACHE = 6;
  385. /// <summary>
  386. /// Module that made this request.
  387. /// </summary>
  388. public HttpRequestModule RequestModule { get; set; }
  389. public bool Finished { get; private set;}
  390. public bool Removed;
  391. public static int HttpBodyMaxLenMAX = 16384;
  392. // Parameter members and default values
  393. public int HttpBodyMaxLen = 2048;
  394. public string HttpMethod = "GET";
  395. public string HttpMIMEType = "text/plain;charset=utf-8";
  396. public int HttpTimeout;
  397. public bool HttpVerifyCert = true;
  398. //public bool HttpVerboseThrottle = true; // not implemented
  399. public List<string> HttpCustomHeaders = null;
  400. public bool HttpPragmaNoCache = true;
  401. // Request info
  402. public UUID ReqID { get; set; }
  403. public UUID ItemID { get; set;}
  404. public uint LocalID { get; set;}
  405. public string proxyurl;
  406. public string proxyexcepts;
  407. /// <summary>
  408. /// Number of HTTP redirects that this request has been through.
  409. /// </summary>
  410. public int Redirects { get; private set; }
  411. /// <summary>
  412. /// Maximum number of HTTP redirects allowed for this request.
  413. /// </summary>
  414. public int MaxRedirects { get; set; }
  415. public string OutboundBody;
  416. public string ResponseBody;
  417. public List<string> ResponseMetadata;
  418. public Dictionary<string, string> ResponseHeaders;
  419. public int Status;
  420. public string Url;
  421. public void Process()
  422. {
  423. HttpRequestModule.m_jobEngine?.QueueJob("", SendRequest);
  424. }
  425. public static bool ValidateServerCertificate(
  426. object sender,
  427. X509Certificate certificate,
  428. X509Chain chain,
  429. SslPolicyErrors sslPolicyErrors)
  430. {
  431. // If this is a web request we need to check the headers first
  432. // We may want to ignore SSL
  433. if (sender is HttpWebRequest)
  434. {
  435. HttpWebRequest Request = sender as HttpWebRequest;
  436. // We don't case about encryption, get out of here
  437. if (Request.Headers.Get("NoVerifyCert") != null)
  438. return true;
  439. }
  440. if ((((int)sslPolicyErrors) & ~4) != 0)
  441. return false;
  442. return true;
  443. }
  444. /*
  445. * TODO: More work on the response codes. Right now
  446. * returning 200 for success or 499 for exception
  447. */
  448. public void SendRequest()
  449. {
  450. if(Removed)
  451. return;
  452. HttpWebRequest Request;
  453. HttpWebResponse response = null;
  454. Stream resStream = null;
  455. try
  456. {
  457. Request = (HttpWebRequest)WebRequest.Create(Url);
  458. Request.ServerCertificateValidationCallback = ValidateServerCertificate;
  459. Request.AllowAutoRedirect = false;
  460. Request.KeepAlive = false;
  461. Request.Timeout = HttpTimeout;
  462. //This works around some buggy HTTP Servers like Lighttpd
  463. Request.ServicePoint.Expect100Continue = false;
  464. Request.Method = HttpMethod;
  465. Request.ContentType = HttpMIMEType;
  466. if (!HttpVerifyCert)
  467. {
  468. // We could hijack Connection Group Name to identify
  469. // a desired security exception. But at the moment we'll use a dummy header instead.
  470. Request.Headers.Add("NoVerifyCert", "true");
  471. }
  472. // else
  473. // {
  474. // Request.ConnectionGroupName="Verify";
  475. // }
  476. if (!HttpPragmaNoCache)
  477. {
  478. Request.Headers.Add("Pragma", "no-cache");
  479. }
  480. if (HttpCustomHeaders != null)
  481. {
  482. for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
  483. Request.Headers.Add(HttpCustomHeaders[i],
  484. HttpCustomHeaders[i+1]);
  485. }
  486. if (!string.IsNullOrEmpty(proxyurl))
  487. {
  488. if (!string.IsNullOrEmpty(proxyexcepts))
  489. {
  490. string[] elist = proxyexcepts.Split(';');
  491. Request.Proxy = new WebProxy(proxyurl, true, elist);
  492. }
  493. else
  494. {
  495. Request.Proxy = new WebProxy(proxyurl, true);
  496. }
  497. }
  498. foreach (KeyValuePair<string, string> entry in ResponseHeaders)
  499. if (entry.Key.ToLower().Equals("user-agent"))
  500. Request.UserAgent = entry.Value;
  501. else
  502. Request.Headers[entry.Key] = entry.Value;
  503. if (Removed)
  504. return;
  505. // Encode outbound data
  506. if (!string.IsNullOrEmpty(OutboundBody))
  507. {
  508. byte[] data = Util.UTF8.GetBytes(OutboundBody);
  509. Request.ContentLength = data.Length;
  510. using (Stream bstream = Request.GetRequestStream())
  511. bstream.Write(data, 0, data.Length);
  512. data = null;
  513. }
  514. if (Removed)
  515. return;
  516. try
  517. {
  518. // execute the request
  519. response = (HttpWebResponse) Request.GetResponse();
  520. }
  521. catch (WebException e)
  522. {
  523. if (e.Status != WebExceptionStatus.ProtocolError)
  524. {
  525. throw;
  526. }
  527. response = (HttpWebResponse)e.Response;
  528. }
  529. if (Removed)
  530. return;
  531. Status = (int)response.StatusCode;
  532. byte[] buf = new byte[HttpBodyMaxLenMAX + 16];
  533. int count = 0;
  534. resStream = response.GetResponseStream();
  535. int totalBodyBytes = 0;
  536. int maxBytes = HttpBodyMaxLen;
  537. if(maxBytes > buf.Length)
  538. maxBytes = buf.Length;
  539. // we need to read all allowed or UFT8 conversion may fail
  540. do
  541. {
  542. // fill the buffer with data
  543. count = resStream.Read(buf, totalBodyBytes, maxBytes - totalBodyBytes);
  544. totalBodyBytes += count;
  545. if (totalBodyBytes >= maxBytes)
  546. break;
  547. } while (count > 0); // any more data to read?
  548. if(totalBodyBytes > 0)
  549. {
  550. string tempString = Util.UTF8.GetString(buf, 0, totalBodyBytes);
  551. ResponseBody = tempString.Replace("\r", "");
  552. }
  553. else
  554. ResponseBody = "";
  555. }
  556. catch (WebException e)
  557. {
  558. if (e.Status == WebExceptionStatus.ProtocolError)
  559. {
  560. HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
  561. Status = (int)webRsp.StatusCode;
  562. try
  563. {
  564. using (Stream responseStream = webRsp.GetResponseStream())
  565. {
  566. using (StreamReader reader = new StreamReader(responseStream))
  567. ResponseBody = reader.ReadToEnd();
  568. }
  569. }
  570. catch
  571. {
  572. ResponseBody = webRsp.StatusDescription;
  573. }
  574. }
  575. else
  576. {
  577. Status = 499; //ClientErrorJoker;
  578. ResponseBody = e.Message;
  579. }
  580. }
  581. // catch (Exception e)
  582. catch
  583. {
  584. // Don't crash on anything else
  585. }
  586. finally
  587. {
  588. if (resStream != null)
  589. resStream.Close();
  590. if (response != null)
  591. response.Close();
  592. if(!Removed)
  593. {
  594. // We need to resubmit ?
  595. if (Status == (int)HttpStatusCode.MovedPermanently ||
  596. Status == (int)HttpStatusCode.Found ||
  597. Status == (int)HttpStatusCode.SeeOther ||
  598. Status == (int)HttpStatusCode.TemporaryRedirect)
  599. {
  600. if (Redirects >= MaxRedirects)
  601. {
  602. Status = 499;//.ClientErrorJoker;
  603. ResponseBody = "Number of redirects exceeded max redirects";
  604. RequestModule.GotCompletedRequest(this);
  605. }
  606. else
  607. {
  608. string location = response.Headers["Location"];
  609. if (location == null)
  610. {
  611. Status = 499;//ClientErrorJoker;
  612. ResponseBody = "HTTP redirect code but no location header";
  613. RequestModule.GotCompletedRequest(this);
  614. }
  615. else if (!RequestModule.CheckAllowed(new Uri(location)))
  616. {
  617. Status = 499;//ClientErrorJoker;
  618. ResponseBody = "URL from HTTP redirect blocked: " + location;
  619. RequestModule.GotCompletedRequest(this);
  620. }
  621. else
  622. {
  623. Status = 0;
  624. Url = location;
  625. Redirects++;
  626. ResponseBody = null;
  627. //m_log.DebugFormat("Redirecting to [{0}]", Url);
  628. Process();
  629. }
  630. }
  631. }
  632. else
  633. {
  634. if (ResponseBody == null)
  635. ResponseBody = string.Empty;
  636. RequestModule.GotCompletedRequest(this);
  637. }
  638. }
  639. }
  640. }
  641. public void Stop()
  642. {
  643. Removed = true;
  644. }
  645. }
  646. }