ScriptsHttpRequests.cs 28 KB

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