ScriptsHttpRequests.cs 27 KB

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