ScriptsHttpRequests.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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.Linq;
  31. using System.Net;
  32. using System.Net.Mail;
  33. using System.Net.Security;
  34. using System.Reflection;
  35. using System.Text;
  36. using System.Threading;
  37. using System.Security.Cryptography.X509Certificates;
  38. using log4net;
  39. using Nini.Config;
  40. using OpenMetaverse;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Framework.Servers.HttpServer;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. using Mono.Addins;
  47. /*****************************************************
  48. *
  49. * ScriptsHttpRequests
  50. *
  51. * Implements the llHttpRequest and http_response
  52. * callback.
  53. *
  54. * Some stuff was already in LSLLongCmdHandler, and then
  55. * there was this file with a stub class in it. So,
  56. * I am moving some of the objects and functions out of
  57. * LSLLongCmdHandler, such as the HttpRequestClass, the
  58. * start and stop methods, and setting up pending and
  59. * completed queues. These are processed in the
  60. * LSLLongCmdHandler polling loop. Similiar to the
  61. * XMLRPCModule, since that seems to work.
  62. *
  63. * //TODO
  64. *
  65. * This probably needs some throttling mechanism but
  66. * it's wide open right now. This applies to both
  67. * number of requests and data volume.
  68. *
  69. * Linden puts all kinds of header fields in the requests.
  70. * Not doing any of that:
  71. * User-Agent
  72. * X-SecondLife-Shard
  73. * X-SecondLife-Object-Name
  74. * X-SecondLife-Object-Key
  75. * X-SecondLife-Region
  76. * X-SecondLife-Local-Position
  77. * X-SecondLife-Local-Velocity
  78. * X-SecondLife-Local-Rotation
  79. * X-SecondLife-Owner-Name
  80. * X-SecondLife-Owner-Key
  81. *
  82. * HTTPS support
  83. *
  84. * Configurable timeout?
  85. * Configurable max response size?
  86. * Configurable
  87. *
  88. * **************************************************/
  89. namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
  90. {
  91. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
  92. public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
  93. {
  94. private object HttpListLock = new object();
  95. private int httpTimeout = 30000;
  96. private string m_name = "HttpScriptRequests";
  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 HttpRequestModule()
  104. {
  105. ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate;
  106. }
  107. public static bool ValidateServerCertificate(
  108. object sender,
  109. X509Certificate certificate,
  110. X509Chain chain,
  111. SslPolicyErrors sslPolicyErrors)
  112. {
  113. // If this is a web request we need to check the headers first
  114. // We may want to ignore SSL
  115. if (sender is HttpWebRequest)
  116. {
  117. HttpWebRequest Request = (HttpWebRequest)sender;
  118. ServicePoint sp = Request.ServicePoint;
  119. // We don't case about encryption, get out of here
  120. if (Request.Headers.Get("NoVerifyCert") != null)
  121. {
  122. return true;
  123. }
  124. // If there was an upstream cert verification error, bail
  125. if ((((int)sslPolicyErrors) & ~4) != 0)
  126. return false;
  127. // Check for policy and execute it if defined
  128. if (ServicePointManager.CertificatePolicy != null)
  129. {
  130. return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
  131. }
  132. return true;
  133. }
  134. // If it's not HTTP, trust .NET to check it
  135. if ((((int)sslPolicyErrors) & ~4) != 0)
  136. return false;
  137. return true;
  138. }
  139. #region IHttpRequestModule Members
  140. public UUID MakeHttpRequest(string url, string parameters, string body)
  141. {
  142. return UUID.Zero;
  143. }
  144. public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body)
  145. {
  146. UUID reqID = UUID.Random();
  147. HttpRequestClass htc = new HttpRequestClass();
  148. // Partial implementation: support for parameter flags needed
  149. // see http://wiki.secondlife.com/wiki/LlHTTPRequest
  150. //
  151. // Parameters are expected in {key, value, ... , key, value}
  152. if (parameters != null)
  153. {
  154. string[] parms = parameters.ToArray();
  155. for (int i = 0; i < parms.Length; i += 2)
  156. {
  157. switch (Int32.Parse(parms[i]))
  158. {
  159. case (int)HttpRequestConstants.HTTP_METHOD:
  160. htc.HttpMethod = parms[i + 1];
  161. break;
  162. case (int)HttpRequestConstants.HTTP_MIMETYPE:
  163. htc.HttpMIMEType = parms[i + 1];
  164. break;
  165. case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
  166. // TODO implement me
  167. break;
  168. case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
  169. htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
  170. break;
  171. case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
  172. // TODO implement me
  173. break;
  174. case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
  175. //Parameters are in pairs and custom header takes
  176. //arguments in pairs so adjust for header marker.
  177. ++i;
  178. //Maximum of 8 headers are allowed based on the
  179. //Second Life documentation for llHTTPRequest.
  180. for (int count = 1; count <= 8; ++count)
  181. {
  182. //Not enough parameters remaining for a header?
  183. if (parms.Length - i < 2)
  184. break;
  185. //Have we reached the end of the list of headers?
  186. //End is marked by a string with a single digit.
  187. //We already know we have at least one parameter
  188. //so it is safe to do this check at top of loop.
  189. if (Char.IsDigit(parms[i][0]))
  190. break;
  191. if (htc.HttpCustomHeaders == null)
  192. htc.HttpCustomHeaders = new List<string>();
  193. htc.HttpCustomHeaders.Add(parms[i]);
  194. htc.HttpCustomHeaders.Add(parms[i+1]);
  195. i += 2;
  196. }
  197. break;
  198. case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
  199. htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
  200. break;
  201. }
  202. }
  203. }
  204. htc.LocalID = localID;
  205. htc.ItemID = itemID;
  206. htc.Url = url;
  207. htc.ReqID = reqID;
  208. htc.HttpTimeout = httpTimeout;
  209. htc.OutboundBody = body;
  210. htc.ResponseHeaders = headers;
  211. htc.proxyurl = m_proxyurl;
  212. htc.proxyexcepts = m_proxyexcepts;
  213. lock (HttpListLock)
  214. {
  215. m_pendingRequests.Add(reqID, htc);
  216. }
  217. htc.Process();
  218. return reqID;
  219. }
  220. public void StopHttpRequestsForScript(UUID id)
  221. {
  222. if (m_pendingRequests != null)
  223. {
  224. List<UUID> keysToRemove = null;
  225. lock (HttpListLock)
  226. {
  227. foreach (HttpRequestClass req in m_pendingRequests.Values)
  228. {
  229. if (req.ItemID == id)
  230. {
  231. req.Stop();
  232. if (keysToRemove == null)
  233. keysToRemove = new List<UUID>();
  234. keysToRemove.Add(req.ReqID);
  235. }
  236. }
  237. if (keysToRemove != null)
  238. keysToRemove.ForEach(keyToRemove => m_pendingRequests.Remove(keyToRemove));
  239. }
  240. }
  241. }
  242. /*
  243. * TODO
  244. * Not sure how important ordering is is here - the next first
  245. * one completed in the list is returned, based soley on its list
  246. * position, not the order in which the request was started or
  247. * finished. I thought about setting up a queue for this, but
  248. * it will need some refactoring and this works 'enough' right now
  249. */
  250. public IServiceRequest GetNextCompletedRequest()
  251. {
  252. lock (HttpListLock)
  253. {
  254. foreach (HttpRequestClass req in m_pendingRequests.Values)
  255. {
  256. if (req.Finished)
  257. return req;
  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. m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
  282. }
  283. public void AddRegion(Scene scene)
  284. {
  285. m_scene = scene;
  286. m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
  287. }
  288. public void RemoveRegion(Scene scene)
  289. {
  290. scene.UnregisterModuleInterface<IHttpRequestModule>(this);
  291. if (scene == m_scene)
  292. m_scene = null;
  293. }
  294. public void PostInitialise()
  295. {
  296. }
  297. public void RegionLoaded(Scene scene)
  298. {
  299. }
  300. public void Close()
  301. {
  302. }
  303. public string Name
  304. {
  305. get { return m_name; }
  306. }
  307. public Type ReplaceableInterface
  308. {
  309. get { return null; }
  310. }
  311. #endregion
  312. }
  313. public class HttpRequestClass: IServiceRequest
  314. {
  315. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  316. // Constants for parameters
  317. // public const int HTTP_BODY_MAXLENGTH = 2;
  318. // public const int HTTP_METHOD = 0;
  319. // public const int HTTP_MIMETYPE = 1;
  320. // public const int HTTP_VERIFY_CERT = 3;
  321. // public const int HTTP_VERBOSE_THROTTLE = 4;
  322. // public const int HTTP_CUSTOM_HEADER = 5;
  323. // public const int HTTP_PRAGMA_NO_CACHE = 6;
  324. private bool _finished;
  325. public bool Finished
  326. {
  327. get { return _finished; }
  328. }
  329. // public int HttpBodyMaxLen = 2048; // not implemented
  330. // Parameter members and default values
  331. public string HttpMethod = "GET";
  332. public string HttpMIMEType = "text/plain;charset=utf-8";
  333. public int HttpTimeout;
  334. public bool HttpVerifyCert = true;
  335. //public bool HttpVerboseThrottle = true; // not implemented
  336. public List<string> HttpCustomHeaders = null;
  337. public bool HttpPragmaNoCache = true;
  338. // Request info
  339. private UUID _itemID;
  340. public UUID ItemID
  341. {
  342. get { return _itemID; }
  343. set { _itemID = value; }
  344. }
  345. private uint _localID;
  346. public uint LocalID
  347. {
  348. get { return _localID; }
  349. set { _localID = value; }
  350. }
  351. public DateTime Next;
  352. public string proxyurl;
  353. public string proxyexcepts;
  354. public string OutboundBody;
  355. private UUID _reqID;
  356. public UUID ReqID
  357. {
  358. get { return _reqID; }
  359. set { _reqID = value; }
  360. }
  361. public WebRequest Request;
  362. public string ResponseBody;
  363. public List<string> ResponseMetadata;
  364. public Dictionary<string, string> ResponseHeaders;
  365. public int Status;
  366. public string Url;
  367. public void Process()
  368. {
  369. SendRequest();
  370. }
  371. public void SendRequest()
  372. {
  373. try
  374. {
  375. Request = WebRequest.Create(Url);
  376. Request.Method = HttpMethod;
  377. Request.ContentType = HttpMIMEType;
  378. if (!HttpVerifyCert)
  379. {
  380. // We could hijack Connection Group Name to identify
  381. // a desired security exception. But at the moment we'll use a dummy header instead.
  382. // Request.ConnectionGroupName = "NoVerify";
  383. Request.Headers.Add("NoVerifyCert", "true");
  384. }
  385. // else
  386. // {
  387. // Request.ConnectionGroupName="Verify";
  388. // }
  389. if (!HttpPragmaNoCache)
  390. {
  391. Request.Headers.Add("Pragma", "no-cache");
  392. }
  393. if (HttpCustomHeaders != null)
  394. {
  395. for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
  396. Request.Headers.Add(HttpCustomHeaders[i],
  397. HttpCustomHeaders[i+1]);
  398. }
  399. if (!string.IsNullOrEmpty(proxyurl))
  400. {
  401. if (!string.IsNullOrEmpty(proxyexcepts))
  402. {
  403. string[] elist = proxyexcepts.Split(';');
  404. Request.Proxy = new WebProxy(proxyurl, true, elist);
  405. }
  406. else
  407. {
  408. Request.Proxy = new WebProxy(proxyurl, true);
  409. }
  410. }
  411. if (ResponseHeaders != null)
  412. {
  413. foreach (KeyValuePair<string, string> entry in ResponseHeaders)
  414. if (entry.Key.ToLower().Equals("user-agent") && Request is HttpWebRequest)
  415. ((HttpWebRequest)Request).UserAgent = entry.Value;
  416. else
  417. Request.Headers[entry.Key] = entry.Value;
  418. }
  419. // Encode outbound data
  420. if (!string.IsNullOrEmpty(OutboundBody))
  421. {
  422. byte[] data = Util.UTF8.GetBytes(OutboundBody);
  423. Request.ContentLength = data.Length;
  424. Stream bstream = Request.GetRequestStream();
  425. bstream.Write(data, 0, data.Length);
  426. bstream.Close();
  427. }
  428. try
  429. {
  430. IAsyncResult result = (IAsyncResult)Request.BeginGetResponse(ResponseCallback, null);
  431. ThreadPool.RegisterWaitForSingleObject(
  432. result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), null, HttpTimeout, true);
  433. }
  434. catch (WebException e)
  435. {
  436. if (e.Status != WebExceptionStatus.ProtocolError)
  437. {
  438. throw;
  439. }
  440. HttpWebResponse response = (HttpWebResponse)e.Response;
  441. Status = (int)response.StatusCode;
  442. ResponseBody = response.StatusDescription;
  443. _finished = true;
  444. }
  445. }
  446. catch (Exception e)
  447. {
  448. // m_log.Debug(
  449. // string.Format("[SCRIPTS HTTP REQUESTS]: Exception on request to {0} for {1} ", Url, ItemID), e);
  450. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  451. ResponseBody = e.Message;
  452. _finished = true;
  453. }
  454. }
  455. private void ResponseCallback(IAsyncResult ar)
  456. {
  457. HttpWebResponse response = null;
  458. try
  459. {
  460. try
  461. {
  462. response = (HttpWebResponse)Request.EndGetResponse(ar);
  463. }
  464. catch (WebException e)
  465. {
  466. if (e.Status != WebExceptionStatus.ProtocolError)
  467. {
  468. throw;
  469. }
  470. response = (HttpWebResponse)e.Response;
  471. }
  472. Status = (int)response.StatusCode;
  473. using (Stream stream = response.GetResponseStream())
  474. {
  475. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  476. ResponseBody = reader.ReadToEnd();
  477. }
  478. }
  479. catch (Exception e)
  480. {
  481. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  482. ResponseBody = e.Message;
  483. // m_log.Debug(
  484. // string.Format("[SCRIPTS HTTP REQUESTS]: Exception on response to {0} for {1} ", Url, ItemID), e);
  485. }
  486. finally
  487. {
  488. if (response != null)
  489. response.Close();
  490. _finished = true;
  491. }
  492. }
  493. private void TimeoutCallback(object state, bool timedOut)
  494. {
  495. if (timedOut)
  496. Request.Abort();
  497. }
  498. public void Stop()
  499. {
  500. // m_log.DebugFormat("[SCRIPTS HTTP REQUESTS]: Stopping request to {0} for {1} ", Url, ItemID);
  501. if (Request != null)
  502. Request.Abort();
  503. }
  504. }
  505. }