ScriptsHttpRequests.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. }
  107. #region IHttpRequestModule Members
  108. public UUID MakeHttpRequest(string url, string parameters, string body)
  109. {
  110. return UUID.Zero;
  111. }
  112. public UUID StartHttpRequest(
  113. uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
  114. out HttpInitialRequestStatus status)
  115. {
  116. UUID reqID = UUID.Random();
  117. HttpRequestClass htc = new HttpRequestClass();
  118. // Partial implementation: support for parameter flags needed
  119. // see http://wiki.secondlife.com/wiki/LlHTTPRequest
  120. //
  121. // Parameters are expected in {key, value, ... , key, value}
  122. if (parameters != null)
  123. {
  124. string[] parms = parameters.ToArray();
  125. for (int i = 0; i < parms.Length; i += 2)
  126. {
  127. switch (Int32.Parse(parms[i]))
  128. {
  129. case (int)HttpRequestConstants.HTTP_METHOD:
  130. htc.HttpMethod = parms[i + 1];
  131. break;
  132. case (int)HttpRequestConstants.HTTP_MIMETYPE:
  133. htc.HttpMIMEType = parms[i + 1];
  134. break;
  135. case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
  136. int len;
  137. if(int.TryParse(parms[i + 1], out len))
  138. {
  139. if(len > HttpRequestClass.HttpBodyMaxLenMAX)
  140. len = HttpRequestClass.HttpBodyMaxLenMAX;
  141. else if(len < 64) //???
  142. len = 64;
  143. htc.HttpBodyMaxLen = len;
  144. }
  145. break;
  146. case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
  147. htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
  148. break;
  149. case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
  150. // TODO implement me
  151. break;
  152. case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
  153. //Parameters are in pairs and custom header takes
  154. //arguments in pairs so adjust for header marker.
  155. ++i;
  156. //Maximum of 8 headers are allowed based on the
  157. //Second Life documentation for llHTTPRequest.
  158. for (int count = 1; count <= 8; ++count)
  159. {
  160. //Not enough parameters remaining for a header?
  161. if (parms.Length - i < 2)
  162. break;
  163. if (htc.HttpCustomHeaders == null)
  164. htc.HttpCustomHeaders = new List<string>();
  165. htc.HttpCustomHeaders.Add(parms[i]);
  166. htc.HttpCustomHeaders.Add(parms[i+1]);
  167. int nexti = i + 2;
  168. if (nexti >= parms.Length || Char.IsDigit(parms[nexti][0]))
  169. break;
  170. i = nexti;
  171. }
  172. break;
  173. case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
  174. htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
  175. break;
  176. }
  177. }
  178. }
  179. htc.RequestModule = this;
  180. htc.LocalID = localID;
  181. htc.ItemID = itemID;
  182. htc.Url = url;
  183. htc.ReqID = reqID;
  184. htc.HttpTimeout = httpTimeout;
  185. htc.OutboundBody = body;
  186. htc.ResponseHeaders = headers;
  187. htc.proxyurl = m_proxyurl;
  188. htc.proxyexcepts = m_proxyexcepts;
  189. // Same number as default HttpWebRequest.MaximumAutomaticRedirections
  190. htc.MaxRedirects = 50;
  191. if (StartHttpRequest(htc))
  192. {
  193. status = HttpInitialRequestStatus.OK;
  194. return htc.ReqID;
  195. }
  196. else
  197. {
  198. status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
  199. return UUID.Zero;
  200. }
  201. }
  202. /// <summary>
  203. /// Would a caller to this module be allowed to make a request to the given URL?
  204. /// </summary>
  205. /// <returns></returns>
  206. public bool CheckAllowed(Uri url)
  207. {
  208. return m_outboundUrlFilter.CheckAllowed(url);
  209. }
  210. public bool StartHttpRequest(HttpRequestClass req)
  211. {
  212. if (!CheckAllowed(new Uri(req.Url)))
  213. return false;
  214. lock (HttpListLock)
  215. {
  216. m_pendingRequests.Add(req.ReqID, req);
  217. }
  218. req.Process();
  219. return true;
  220. }
  221. public void StopHttpRequest(uint m_localID, UUID m_itemID)
  222. {
  223. if (m_pendingRequests != null)
  224. {
  225. lock (HttpListLock)
  226. {
  227. HttpRequestClass tmpReq;
  228. if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
  229. {
  230. tmpReq.Stop();
  231. m_pendingRequests.Remove(m_itemID);
  232. }
  233. }
  234. }
  235. }
  236. /*
  237. * TODO
  238. * Not sure how important ordering is is here - the next first
  239. * one completed in the list is returned, based soley on its list
  240. * position, not the order in which the request was started or
  241. * finished. I thought about setting up a queue for this, but
  242. * it will need some refactoring and this works 'enough' right now
  243. */
  244. public IServiceRequest GetNextCompletedRequest()
  245. {
  246. lock (HttpListLock)
  247. {
  248. foreach (UUID luid in m_pendingRequests.Keys)
  249. {
  250. HttpRequestClass tmpReq;
  251. if (m_pendingRequests.TryGetValue(luid, out tmpReq))
  252. {
  253. if (tmpReq.Finished)
  254. {
  255. return tmpReq;
  256. }
  257. }
  258. }
  259. }
  260. return null;
  261. }
  262. public void RemoveCompletedRequest(UUID id)
  263. {
  264. lock (HttpListLock)
  265. {
  266. HttpRequestClass tmpReq;
  267. if (m_pendingRequests.TryGetValue(id, out tmpReq))
  268. {
  269. tmpReq.Stop();
  270. tmpReq = null;
  271. m_pendingRequests.Remove(id);
  272. }
  273. }
  274. }
  275. #endregion
  276. #region ISharedRegionModule Members
  277. public void Initialise(IConfigSource config)
  278. {
  279. m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
  280. m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
  281. HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384);
  282. m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
  283. int maxThreads = 15;
  284. IConfig httpConfig = config.Configs["HttpRequestModule"];
  285. if (httpConfig != null)
  286. {
  287. maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads);
  288. }
  289. m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
  290. // First instance sets this up for all sims
  291. if (ThreadPool == null)
  292. {
  293. STPStartInfo startInfo = new STPStartInfo();
  294. startInfo.IdleTimeout = 2000;
  295. startInfo.MaxWorkerThreads = maxThreads;
  296. startInfo.MinWorkerThreads = 0;
  297. startInfo.ThreadPriority = ThreadPriority.BelowNormal;
  298. startInfo.StartSuspended = true;
  299. startInfo.ThreadPoolName = "ScriptsHttpReq";
  300. ThreadPool = new SmartThreadPool(startInfo);
  301. ThreadPool.Start();
  302. }
  303. }
  304. public void AddRegion(Scene scene)
  305. {
  306. m_scene = scene;
  307. m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
  308. }
  309. public void RemoveRegion(Scene scene)
  310. {
  311. scene.UnregisterModuleInterface<IHttpRequestModule>(this);
  312. if (scene == m_scene)
  313. m_scene = null;
  314. }
  315. public void PostInitialise()
  316. {
  317. }
  318. public void RegionLoaded(Scene scene)
  319. {
  320. }
  321. public void Close()
  322. {
  323. ThreadPool.Shutdown();
  324. }
  325. public string Name
  326. {
  327. get { return m_name; }
  328. }
  329. public Type ReplaceableInterface
  330. {
  331. get { return null; }
  332. }
  333. #endregion
  334. }
  335. public class HttpRequestClass : IServiceRequest
  336. {
  337. // Constants for parameters
  338. // public const int HTTP_BODY_MAXLENGTH = 2;
  339. // public const int HTTP_METHOD = 0;
  340. // public const int HTTP_MIMETYPE = 1;
  341. // public const int HTTP_VERIFY_CERT = 3;
  342. // public const int HTTP_VERBOSE_THROTTLE = 4;
  343. // public const int HTTP_CUSTOM_HEADER = 5;
  344. // public const int HTTP_PRAGMA_NO_CACHE = 6;
  345. /// <summary>
  346. /// Module that made this request.
  347. /// </summary>
  348. public HttpRequestModule RequestModule { get; set; }
  349. private bool _finished;
  350. public bool Finished
  351. {
  352. get { return _finished; }
  353. }
  354. public static int HttpBodyMaxLenMAX = 16384;
  355. // Parameter members and default values
  356. public int HttpBodyMaxLen = 2048;
  357. public string HttpMethod = "GET";
  358. public string HttpMIMEType = "text/plain;charset=utf-8";
  359. public int HttpTimeout;
  360. public bool HttpVerifyCert = true;
  361. public IWorkItemResult WorkItem = null;
  362. //public bool HttpVerboseThrottle = true; // not implemented
  363. public List<string> HttpCustomHeaders = null;
  364. public bool HttpPragmaNoCache = true;
  365. // Request info
  366. private UUID _itemID;
  367. public UUID ItemID
  368. {
  369. get { return _itemID; }
  370. set { _itemID = value; }
  371. }
  372. private uint _localID;
  373. public uint LocalID
  374. {
  375. get { return _localID; }
  376. set { _localID = value; }
  377. }
  378. public DateTime Next;
  379. public string proxyurl;
  380. public string proxyexcepts;
  381. /// <summary>
  382. /// Number of HTTP redirects that this request has been through.
  383. /// </summary>
  384. public int Redirects { get; private set; }
  385. /// <summary>
  386. /// Maximum number of HTTP redirects allowed for this request.
  387. /// </summary>
  388. public int MaxRedirects { get; set; }
  389. public string OutboundBody;
  390. private UUID _reqID;
  391. public UUID ReqID
  392. {
  393. get { return _reqID; }
  394. set { _reqID = value; }
  395. }
  396. public HttpWebRequest Request;
  397. public string ResponseBody;
  398. public List<string> ResponseMetadata;
  399. public Dictionary<string, string> ResponseHeaders;
  400. public int Status;
  401. public string Url;
  402. public void Process()
  403. {
  404. _finished = false;
  405. lock (HttpRequestModule.ThreadPool)
  406. WorkItem = HttpRequestModule.ThreadPool.QueueWorkItem(new WorkItemCallback(StpSendWrapper), null);
  407. }
  408. private object StpSendWrapper(object o)
  409. {
  410. SendRequest();
  411. return null;
  412. }
  413. public static bool ValidateServerCertificate(
  414. object sender,
  415. X509Certificate certificate,
  416. X509Chain chain,
  417. SslPolicyErrors sslPolicyErrors)
  418. {
  419. // If this is a web request we need to check the headers first
  420. // We may want to ignore SSL
  421. if (sender is HttpWebRequest)
  422. {
  423. HttpWebRequest Request = (HttpWebRequest)sender;
  424. ServicePoint sp = Request.ServicePoint;
  425. // We don't case about encryption, get out of here
  426. if (Request.Headers.Get("NoVerifyCert") != null)
  427. {
  428. return true;
  429. }
  430. // If there was an upstream cert verification error, bail
  431. if ((((int)sslPolicyErrors) & ~4) != 0)
  432. return false;
  433. // Check for policy and execute it if defined
  434. #pragma warning disable 0618
  435. if (ServicePointManager.CertificatePolicy != null)
  436. {
  437. return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
  438. }
  439. #pragma warning restore 0618
  440. return true;
  441. }
  442. // If it's not HTTP, trust .NET to check it
  443. if ((((int)sslPolicyErrors) & ~4) != 0)
  444. return false;
  445. return true;
  446. }
  447. /*
  448. * TODO: More work on the response codes. Right now
  449. * returning 200 for success or 499 for exception
  450. */
  451. public void SendRequest()
  452. {
  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. //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. 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 = (int)OSHttpStatusCode.ClientErrorJoker;
  596. ResponseBody = "Number of redirects exceeded max redirects";
  597. _finished = true;
  598. }
  599. else
  600. {
  601. string location = response.Headers["Location"];
  602. if (location == null)
  603. {
  604. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  605. ResponseBody = "HTTP redirect code but no location header";
  606. _finished = true;
  607. }
  608. else if (!RequestModule.CheckAllowed(new Uri(location)))
  609. {
  610. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  611. ResponseBody = "URL from HTTP redirect blocked: " + location;
  612. _finished = true;
  613. }
  614. else
  615. {
  616. Status = 0;
  617. Url = response.Headers["Location"];
  618. Redirects++;
  619. ResponseBody = null;
  620. // m_log.DebugFormat("Redirecting to [{0}]", Url);
  621. Process();
  622. }
  623. }
  624. }
  625. else
  626. {
  627. _finished = true;
  628. if (ResponseBody == null)
  629. ResponseBody = String.Empty;
  630. }
  631. }
  632. }
  633. public void Stop()
  634. {
  635. try
  636. {
  637. if (!WorkItem.Cancel())
  638. {
  639. WorkItem.Cancel(true);
  640. }
  641. }
  642. catch (Exception)
  643. {
  644. }
  645. }
  646. }
  647. }