ScriptsHttpRequests.cs 25 KB

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