ScriptsHttpRequests.cs 28 KB

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