ScriptsHttpRequests.cs 12 KB

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