ScriptsHttpRequests.cs 14 KB

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