ScriptsHttpRequests.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. //Have we reached the end of the list of headers?
  199. //End is marked by a string with a single digit.
  200. //We already know we have at least one parameter
  201. //so it is safe to do this check at top of loop.
  202. if (Char.IsDigit(parms[i][0]))
  203. break;
  204. if (htc.HttpCustomHeaders == null)
  205. htc.HttpCustomHeaders = new List<string>();
  206. htc.HttpCustomHeaders.Add(parms[i]);
  207. htc.HttpCustomHeaders.Add(parms[i+1]);
  208. i += 2;
  209. }
  210. break;
  211. case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
  212. htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
  213. break;
  214. }
  215. }
  216. }
  217. htc.RequestModule = this;
  218. htc.LocalID = localID;
  219. htc.ItemID = itemID;
  220. htc.Url = url;
  221. htc.ReqID = reqID;
  222. htc.HttpTimeout = httpTimeout;
  223. htc.OutboundBody = body;
  224. htc.ResponseHeaders = headers;
  225. htc.proxyurl = m_proxyurl;
  226. htc.proxyexcepts = m_proxyexcepts;
  227. // Same number as default HttpWebRequest.MaximumAutomaticRedirections
  228. htc.MaxRedirects = 50;
  229. if (StartHttpRequest(htc))
  230. {
  231. status = HttpInitialRequestStatus.OK;
  232. return htc.ReqID;
  233. }
  234. else
  235. {
  236. status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
  237. return UUID.Zero;
  238. }
  239. }
  240. /// <summary>
  241. /// Would a caller to this module be allowed to make a request to the given URL?
  242. /// </summary>
  243. /// <returns></returns>
  244. public bool CheckAllowed(Uri url)
  245. {
  246. return m_outboundUrlFilter.CheckAllowed(url);
  247. }
  248. public bool StartHttpRequest(HttpRequestClass req)
  249. {
  250. if (!CheckAllowed(new Uri(req.Url)))
  251. return false;
  252. lock (HttpListLock)
  253. {
  254. m_pendingRequests.Add(req.ReqID, req);
  255. }
  256. req.Process();
  257. return true;
  258. }
  259. public void StopHttpRequest(uint m_localID, UUID m_itemID)
  260. {
  261. if (m_pendingRequests != null)
  262. {
  263. lock (HttpListLock)
  264. {
  265. HttpRequestClass tmpReq;
  266. if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
  267. {
  268. tmpReq.Stop();
  269. m_pendingRequests.Remove(m_itemID);
  270. }
  271. }
  272. }
  273. }
  274. /*
  275. * TODO
  276. * Not sure how important ordering is is here - the next first
  277. * one completed in the list is returned, based soley on its list
  278. * position, not the order in which the request was started or
  279. * finished. I thought about setting up a queue for this, but
  280. * it will need some refactoring and this works 'enough' right now
  281. */
  282. public IServiceRequest GetNextCompletedRequest()
  283. {
  284. lock (HttpListLock)
  285. {
  286. foreach (UUID luid in m_pendingRequests.Keys)
  287. {
  288. HttpRequestClass tmpReq;
  289. if (m_pendingRequests.TryGetValue(luid, out tmpReq))
  290. {
  291. if (tmpReq.Finished)
  292. {
  293. return tmpReq;
  294. }
  295. }
  296. }
  297. }
  298. return null;
  299. }
  300. public void RemoveCompletedRequest(UUID id)
  301. {
  302. lock (HttpListLock)
  303. {
  304. HttpRequestClass tmpReq;
  305. if (m_pendingRequests.TryGetValue(id, out tmpReq))
  306. {
  307. tmpReq.Stop();
  308. tmpReq = null;
  309. m_pendingRequests.Remove(id);
  310. }
  311. }
  312. }
  313. #endregion
  314. #region ISharedRegionModule Members
  315. public void Initialise(IConfigSource config)
  316. {
  317. m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
  318. m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
  319. HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384);
  320. m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
  321. int maxThreads = 15;
  322. IConfig httpConfig = config.Configs["HttpRequestModule"];
  323. if (httpConfig != null)
  324. {
  325. maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads);
  326. }
  327. m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
  328. // First instance sets this up for all sims
  329. if (ThreadPool == null)
  330. {
  331. STPStartInfo startInfo = new STPStartInfo();
  332. startInfo.IdleTimeout = 20000;
  333. startInfo.MaxWorkerThreads = maxThreads;
  334. startInfo.MinWorkerThreads = 1;
  335. startInfo.ThreadPriority = ThreadPriority.BelowNormal;
  336. startInfo.StartSuspended = true;
  337. startInfo.ThreadPoolName = "ScriptsHttpReq";
  338. ThreadPool = new SmartThreadPool(startInfo);
  339. ThreadPool.Start();
  340. }
  341. }
  342. public void AddRegion(Scene scene)
  343. {
  344. m_scene = scene;
  345. m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
  346. }
  347. public void RemoveRegion(Scene scene)
  348. {
  349. scene.UnregisterModuleInterface<IHttpRequestModule>(this);
  350. if (scene == m_scene)
  351. m_scene = null;
  352. }
  353. public void PostInitialise()
  354. {
  355. }
  356. public void RegionLoaded(Scene scene)
  357. {
  358. }
  359. public void Close()
  360. {
  361. }
  362. public string Name
  363. {
  364. get { return m_name; }
  365. }
  366. public Type ReplaceableInterface
  367. {
  368. get { return null; }
  369. }
  370. #endregion
  371. }
  372. public class HttpRequestClass : IServiceRequest
  373. {
  374. // Constants for parameters
  375. // public const int HTTP_BODY_MAXLENGTH = 2;
  376. // public const int HTTP_METHOD = 0;
  377. // public const int HTTP_MIMETYPE = 1;
  378. // public const int HTTP_VERIFY_CERT = 3;
  379. // public const int HTTP_VERBOSE_THROTTLE = 4;
  380. // public const int HTTP_CUSTOM_HEADER = 5;
  381. // public const int HTTP_PRAGMA_NO_CACHE = 6;
  382. /// <summary>
  383. /// Module that made this request.
  384. /// </summary>
  385. public HttpRequestModule RequestModule { get; set; }
  386. private bool _finished;
  387. public bool Finished
  388. {
  389. get { return _finished; }
  390. }
  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 IWorkItemResult WorkItem = null;
  399. //public bool HttpVerboseThrottle = true; // not implemented
  400. public List<string> HttpCustomHeaders = null;
  401. public bool HttpPragmaNoCache = true;
  402. // Request info
  403. private UUID _itemID;
  404. public UUID ItemID
  405. {
  406. get { return _itemID; }
  407. set { _itemID = value; }
  408. }
  409. private uint _localID;
  410. public uint LocalID
  411. {
  412. get { return _localID; }
  413. set { _localID = value; }
  414. }
  415. public DateTime Next;
  416. public string proxyurl;
  417. public string proxyexcepts;
  418. /// <summary>
  419. /// Number of HTTP redirects that this request has been through.
  420. /// </summary>
  421. public int Redirects { get; private set; }
  422. /// <summary>
  423. /// Maximum number of HTTP redirects allowed for this request.
  424. /// </summary>
  425. public int MaxRedirects { get; set; }
  426. public string OutboundBody;
  427. private UUID _reqID;
  428. public UUID ReqID
  429. {
  430. get { return _reqID; }
  431. set { _reqID = value; }
  432. }
  433. public HttpWebRequest Request;
  434. public string ResponseBody;
  435. public List<string> ResponseMetadata;
  436. public Dictionary<string, string> ResponseHeaders;
  437. public int Status;
  438. public string Url;
  439. public void Process()
  440. {
  441. _finished = false;
  442. lock (HttpRequestModule.ThreadPool)
  443. WorkItem = HttpRequestModule.ThreadPool.QueueWorkItem(new WorkItemCallback(StpSendWrapper), null);
  444. }
  445. private object StpSendWrapper(object o)
  446. {
  447. SendRequest();
  448. return null;
  449. }
  450. /*
  451. * TODO: More work on the response codes. Right now
  452. * returning 200 for success or 499 for exception
  453. */
  454. public void SendRequest()
  455. {
  456. HttpWebResponse response = null;
  457. Stream resStream = null;
  458. byte[] buf = new byte[HttpBodyMaxLenMAX + 16];
  459. string tempString = null;
  460. int count = 0;
  461. try
  462. {
  463. Request = (HttpWebRequest)WebRequest.Create(Url);
  464. Request.AllowAutoRedirect = false;
  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. Request.Timeout = HttpTimeout;
  515. try
  516. {
  517. // execute the request
  518. response = (HttpWebResponse) Request.GetResponse();
  519. }
  520. catch (WebException e)
  521. {
  522. if (e.Status != WebExceptionStatus.ProtocolError)
  523. {
  524. throw;
  525. }
  526. response = (HttpWebResponse)e.Response;
  527. }
  528. Status = (int)response.StatusCode;
  529. resStream = response.GetResponseStream();
  530. int totalBodyBytes = 0;
  531. int maxBytes = HttpBodyMaxLen;
  532. if(maxBytes > buf.Length)
  533. maxBytes = buf.Length;
  534. // we need to read all allowed or UFT8 conversion may fail
  535. do
  536. {
  537. // fill the buffer with data
  538. count = resStream.Read(buf, totalBodyBytes, maxBytes - totalBodyBytes);
  539. totalBodyBytes += count;
  540. if (totalBodyBytes >= maxBytes)
  541. break;
  542. } while (count > 0); // any more data to read?
  543. if(totalBodyBytes > 0)
  544. {
  545. tempString = Util.UTF8.GetString(buf, 0, totalBodyBytes);
  546. ResponseBody = tempString.Replace("\r", "");
  547. }
  548. else
  549. ResponseBody = "";
  550. }
  551. catch (WebException e)
  552. {
  553. if (e.Status == WebExceptionStatus.ProtocolError)
  554. {
  555. HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
  556. Status = (int)webRsp.StatusCode;
  557. try
  558. {
  559. using (Stream responseStream = webRsp.GetResponseStream())
  560. {
  561. using (StreamReader reader = new StreamReader(responseStream))
  562. ResponseBody = reader.ReadToEnd();
  563. }
  564. }
  565. catch
  566. {
  567. ResponseBody = webRsp.StatusDescription;
  568. }
  569. }
  570. else
  571. {
  572. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  573. ResponseBody = e.Message;
  574. }
  575. if (ResponseBody == null)
  576. ResponseBody = String.Empty;
  577. _finished = true;
  578. return;
  579. }
  580. catch (Exception e)
  581. {
  582. // Don't crash on anything else
  583. }
  584. finally
  585. {
  586. if (resStream != null)
  587. resStream.Close();
  588. if (response != null)
  589. response.Close();
  590. // We need to resubmit
  591. if (
  592. (Status == (int)HttpStatusCode.MovedPermanently
  593. || Status == (int)HttpStatusCode.Found
  594. || Status == (int)HttpStatusCode.SeeOther
  595. || Status == (int)HttpStatusCode.TemporaryRedirect))
  596. {
  597. if (Redirects >= MaxRedirects)
  598. {
  599. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  600. ResponseBody = "Number of redirects exceeded max redirects";
  601. _finished = true;
  602. }
  603. else
  604. {
  605. string location = response.Headers["Location"];
  606. if (location == null)
  607. {
  608. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  609. ResponseBody = "HTTP redirect code but no location header";
  610. _finished = true;
  611. }
  612. else if (!RequestModule.CheckAllowed(new Uri(location)))
  613. {
  614. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  615. ResponseBody = "URL from HTTP redirect blocked: " + location;
  616. _finished = true;
  617. }
  618. else
  619. {
  620. Status = 0;
  621. Url = response.Headers["Location"];
  622. Redirects++;
  623. ResponseBody = null;
  624. // m_log.DebugFormat("Redirecting to [{0}]", Url);
  625. Process();
  626. }
  627. }
  628. }
  629. else
  630. {
  631. _finished = true;
  632. }
  633. }
  634. if (ResponseBody == null)
  635. ResponseBody = String.Empty;
  636. _finished = true;
  637. }
  638. public void Stop()
  639. {
  640. try
  641. {
  642. if (!WorkItem.Cancel())
  643. {
  644. WorkItem.Cancel(true);
  645. }
  646. }
  647. catch (Exception)
  648. {
  649. }
  650. }
  651. }
  652. }