ScriptsHttpRequests.cs 15 KB

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