ScriptsHttpRequests.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. /*****************************************************
  44. *
  45. * ScriptsHttpRequests
  46. *
  47. * Implements the llHttpRequest and http_response
  48. * callback.
  49. *
  50. * Some stuff was already in LSLLongCmdHandler, and then
  51. * there was this file with a stub class in it. So,
  52. * I am moving some of the objects and functions out of
  53. * LSLLongCmdHandler, such as the HttpRequestClass, the
  54. * start and stop methods, and setting up pending and
  55. * completed queues. These are processed in the
  56. * LSLLongCmdHandler polling loop. Similiar to the
  57. * XMLRPCModule, since that seems to work.
  58. *
  59. * //TODO
  60. *
  61. * This probably needs some throttling mechanism but
  62. * it's wide open right now. This applies to both
  63. * number of requests and data volume.
  64. *
  65. * Linden puts all kinds of header fields in the requests.
  66. * Not doing any of that:
  67. * User-Agent
  68. * X-SecondLife-Shard
  69. * X-SecondLife-Object-Name
  70. * X-SecondLife-Object-Key
  71. * X-SecondLife-Region
  72. * X-SecondLife-Local-Position
  73. * X-SecondLife-Local-Velocity
  74. * X-SecondLife-Local-Rotation
  75. * X-SecondLife-Owner-Name
  76. * X-SecondLife-Owner-Key
  77. *
  78. * HTTPS support
  79. *
  80. * Configurable timeout?
  81. * Configurable max response size?
  82. * Configurable
  83. *
  84. * **************************************************/
  85. namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
  86. {
  87. public class HttpRequestModule : IRegionModule, IHttpRequestModule
  88. {
  89. private object HttpListLock = new object();
  90. private int httpTimeout = 30000;
  91. private string m_name = "HttpScriptRequests";
  92. private string m_proxyurl = "";
  93. private string m_proxyexcepts = "";
  94. // <request id, HttpRequestClass>
  95. private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
  96. private Scene m_scene;
  97. // private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
  98. public HttpRequestModule()
  99. {
  100. ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate;
  101. }
  102. public static bool ValidateServerCertificate(
  103. object sender,
  104. X509Certificate certificate,
  105. X509Chain chain,
  106. SslPolicyErrors sslPolicyErrors)
  107. {
  108. // If this is a web request we need to check the headers first
  109. // We may want to ignore SSL
  110. if (sender is HttpWebRequest)
  111. {
  112. HttpWebRequest Request = (HttpWebRequest)sender;
  113. ServicePoint sp = Request.ServicePoint;
  114. // We don't case about encryption, get out of here
  115. if (Request.Headers.Get("NoVerifyCert") != null)
  116. {
  117. return true;
  118. }
  119. // If there was an upstream cert verification error, bail
  120. if ((((int)sslPolicyErrors) & ~4) != 0)
  121. return false;
  122. // Check for policy and execute it if defined
  123. if (ServicePointManager.CertificatePolicy != null)
  124. {
  125. return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
  126. }
  127. return true;
  128. }
  129. // If it's not HTTP, trust .NET to check it
  130. if ((((int)sslPolicyErrors) & ~4) != 0)
  131. return false;
  132. return true;
  133. }
  134. #region IHttpRequestModule Members
  135. public UUID MakeHttpRequest(string url, string parameters, string body)
  136. {
  137. return UUID.Zero;
  138. }
  139. public UUID StartHttpRequest(uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body)
  140. {
  141. UUID reqID = UUID.Random();
  142. HttpRequestClass htc = new HttpRequestClass();
  143. // Partial implementation: support for parameter flags needed
  144. // see http://wiki.secondlife.com/wiki/LlHTTPRequest
  145. //
  146. // Parameters are expected in {key, value, ... , key, value}
  147. if (parameters != null)
  148. {
  149. string[] parms = parameters.ToArray();
  150. for (int i = 0; i < parms.Length; i += 2)
  151. {
  152. switch (Int32.Parse(parms[i]))
  153. {
  154. case (int)HttpRequestConstants.HTTP_METHOD:
  155. htc.HttpMethod = parms[i + 1];
  156. break;
  157. case (int)HttpRequestConstants.HTTP_MIMETYPE:
  158. htc.HttpMIMEType = parms[i + 1];
  159. break;
  160. case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
  161. // TODO implement me
  162. break;
  163. case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
  164. htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
  165. break;
  166. }
  167. }
  168. }
  169. htc.LocalID = localID;
  170. htc.ItemID = itemID;
  171. htc.Url = url;
  172. htc.ReqID = reqID;
  173. htc.HttpTimeout = httpTimeout;
  174. htc.OutboundBody = body;
  175. htc.ResponseHeaders = headers;
  176. htc.proxyurl = m_proxyurl;
  177. htc.proxyexcepts = m_proxyexcepts;
  178. lock (HttpListLock)
  179. {
  180. m_pendingRequests.Add(reqID, htc);
  181. }
  182. htc.Process();
  183. return reqID;
  184. }
  185. public void StopHttpRequest(uint m_localID, UUID m_itemID)
  186. {
  187. if (m_pendingRequests != null)
  188. {
  189. lock (HttpListLock)
  190. {
  191. HttpRequestClass tmpReq;
  192. if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
  193. {
  194. tmpReq.Stop();
  195. m_pendingRequests.Remove(m_itemID);
  196. }
  197. }
  198. }
  199. }
  200. /*
  201. * TODO
  202. * Not sure how important ordering is is here - the next first
  203. * one completed in the list is returned, based soley on its list
  204. * position, not the order in which the request was started or
  205. * finished. I thought about setting up a queue for this, but
  206. * it will need some refactoring and this works 'enough' right now
  207. */
  208. public IServiceRequest GetNextCompletedRequest()
  209. {
  210. lock (HttpListLock)
  211. {
  212. foreach (UUID luid in m_pendingRequests.Keys)
  213. {
  214. HttpRequestClass tmpReq;
  215. if (m_pendingRequests.TryGetValue(luid, out tmpReq))
  216. {
  217. if (tmpReq.Finished)
  218. {
  219. return tmpReq;
  220. }
  221. }
  222. }
  223. }
  224. return null;
  225. }
  226. public void RemoveCompletedRequest(UUID id)
  227. {
  228. lock (HttpListLock)
  229. {
  230. HttpRequestClass tmpReq;
  231. if (m_pendingRequests.TryGetValue(id, out tmpReq))
  232. {
  233. tmpReq.Stop();
  234. tmpReq = null;
  235. m_pendingRequests.Remove(id);
  236. }
  237. }
  238. }
  239. #endregion
  240. #region IRegionModule Members
  241. public void Initialise(Scene scene, IConfigSource config)
  242. {
  243. m_scene = scene;
  244. m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
  245. m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
  246. m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
  247. m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
  248. }
  249. public void PostInitialise()
  250. {
  251. }
  252. public void Close()
  253. {
  254. }
  255. public string Name
  256. {
  257. get { return m_name; }
  258. }
  259. public bool IsSharedModule
  260. {
  261. get { return true; }
  262. }
  263. #endregion
  264. }
  265. public class HttpRequestClass: IServiceRequest
  266. {
  267. // Constants for parameters
  268. // public const int HTTP_BODY_MAXLENGTH = 2;
  269. // public const int HTTP_METHOD = 0;
  270. // public const int HTTP_MIMETYPE = 1;
  271. // public const int HTTP_VERIFY_CERT = 3;
  272. private bool _finished;
  273. public bool Finished
  274. {
  275. get { return _finished; }
  276. }
  277. // public int HttpBodyMaxLen = 2048; // not implemented
  278. // Parameter members and default values
  279. public string HttpMethod = "GET";
  280. public string HttpMIMEType = "text/plain;charset=utf-8";
  281. public int HttpTimeout;
  282. public bool HttpVerifyCert = true;
  283. private Thread httpThread;
  284. // Request info
  285. private UUID _itemID;
  286. public UUID ItemID
  287. {
  288. get { return _itemID; }
  289. set { _itemID = value; }
  290. }
  291. private uint _localID;
  292. public uint LocalID
  293. {
  294. get { return _localID; }
  295. set { _localID = value; }
  296. }
  297. public DateTime Next;
  298. public string proxyurl;
  299. public string proxyexcepts;
  300. public string OutboundBody;
  301. private UUID _reqID;
  302. public UUID ReqID
  303. {
  304. get { return _reqID; }
  305. set { _reqID = value; }
  306. }
  307. public HttpWebRequest Request;
  308. public string ResponseBody;
  309. public List<string> ResponseMetadata;
  310. public Dictionary<string, string> ResponseHeaders;
  311. public int Status;
  312. public string Url;
  313. public void Process()
  314. {
  315. httpThread = new Thread(SendRequest);
  316. httpThread.Name = "HttpRequestThread";
  317. httpThread.Priority = ThreadPriority.BelowNormal;
  318. httpThread.IsBackground = true;
  319. _finished = false;
  320. httpThread.Start();
  321. }
  322. /*
  323. * TODO: More work on the response codes. Right now
  324. * returning 200 for success or 499 for exception
  325. */
  326. public void SendRequest()
  327. {
  328. HttpWebResponse response = null;
  329. StringBuilder sb = new StringBuilder();
  330. byte[] buf = new byte[8192];
  331. string tempString = null;
  332. int count = 0;
  333. try
  334. {
  335. Request = (HttpWebRequest) WebRequest.Create(Url);
  336. Request.Method = HttpMethod;
  337. Request.ContentType = HttpMIMEType;
  338. if(!HttpVerifyCert)
  339. {
  340. // We could hijack Connection Group Name to identify
  341. // a desired security exception. But at the moment we'll use a dummy header instead.
  342. // Request.ConnectionGroupName = "NoVerify";
  343. Request.Headers.Add("NoVerifyCert", "true");
  344. }
  345. // else
  346. // {
  347. // Request.ConnectionGroupName="Verify";
  348. // }
  349. if (proxyurl != null && proxyurl.Length > 0)
  350. {
  351. if (proxyexcepts != null && proxyexcepts.Length > 0)
  352. {
  353. string[] elist = proxyexcepts.Split(';');
  354. Request.Proxy = new WebProxy(proxyurl, true, elist);
  355. }
  356. else
  357. {
  358. Request.Proxy = new WebProxy(proxyurl, true);
  359. }
  360. }
  361. foreach (KeyValuePair<string, string> entry in ResponseHeaders)
  362. if (entry.Key.ToLower().Equals("user-agent"))
  363. Request.UserAgent = entry.Value;
  364. else
  365. Request.Headers[entry.Key] = entry.Value;
  366. // Encode outbound data
  367. if (OutboundBody.Length > 0)
  368. {
  369. byte[] data = Util.UTF8.GetBytes(OutboundBody);
  370. Request.ContentLength = data.Length;
  371. Stream bstream = Request.GetRequestStream();
  372. bstream.Write(data, 0, data.Length);
  373. bstream.Close();
  374. }
  375. Request.Timeout = HttpTimeout;
  376. try
  377. {
  378. // execute the request
  379. response = (HttpWebResponse) Request.GetResponse();
  380. }
  381. catch (WebException e)
  382. {
  383. if (e.Status != WebExceptionStatus.ProtocolError)
  384. {
  385. throw;
  386. }
  387. response = (HttpWebResponse)e.Response;
  388. }
  389. Status = (int)response.StatusCode;
  390. Stream resStream = response.GetResponseStream();
  391. do
  392. {
  393. // fill the buffer with data
  394. count = resStream.Read(buf, 0, buf.Length);
  395. // make sure we read some data
  396. if (count != 0)
  397. {
  398. // translate from bytes to ASCII text
  399. tempString = Util.UTF8.GetString(buf, 0, count);
  400. // continue building the string
  401. sb.Append(tempString);
  402. }
  403. } while (count > 0); // any more data to read?
  404. ResponseBody = sb.ToString();
  405. }
  406. catch (Exception e)
  407. {
  408. Status = (int)OSHttpStatusCode.ClientErrorJoker;
  409. ResponseBody = e.Message;
  410. _finished = true;
  411. return;
  412. }
  413. finally
  414. {
  415. if (response != null)
  416. response.Close();
  417. }
  418. _finished = true;
  419. }
  420. public void Stop()
  421. {
  422. try
  423. {
  424. httpThread.Abort();
  425. }
  426. catch (Exception)
  427. {
  428. }
  429. }
  430. }
  431. }