RestSessionService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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.IO;
  29. using System.Net;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Xml;
  33. using System.Xml.Serialization;
  34. using log4net;
  35. namespace OpenSim.Framework.Servers.HttpServer
  36. {
  37. public class RestSessionObject<TRequest>
  38. {
  39. private string sid;
  40. private string aid;
  41. private TRequest request_body;
  42. public string SessionID
  43. {
  44. get { return sid; }
  45. set { sid = value; }
  46. }
  47. public string AvatarID
  48. {
  49. get { return aid; }
  50. set { aid = value; }
  51. }
  52. public TRequest Body
  53. {
  54. get { return request_body; }
  55. set { request_body = value; }
  56. }
  57. }
  58. public class SynchronousRestSessionObjectPoster<TRequest, TResponse>
  59. {
  60. public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
  61. {
  62. RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>();
  63. sobj.SessionID = sid;
  64. sobj.AvatarID = aid;
  65. sobj.Body = obj;
  66. Type type = typeof(RestSessionObject<TRequest>);
  67. WebRequest request = WebRequest.Create(requestUrl);
  68. request.Method = verb;
  69. request.ContentType = "text/xml";
  70. request.Timeout = 20000;
  71. MemoryStream buffer = new MemoryStream();
  72. XmlWriterSettings settings = new XmlWriterSettings();
  73. settings.Encoding = Encoding.UTF8;
  74. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  75. {
  76. XmlSerializer serializer = new XmlSerializer(type);
  77. serializer.Serialize(writer, sobj);
  78. writer.Flush();
  79. }
  80. int length = (int)buffer.Length;
  81. request.ContentLength = length;
  82. Stream requestStream = request.GetRequestStream();
  83. requestStream.Write(buffer.ToArray(), 0, length);
  84. buffer.Close();
  85. requestStream.Close();
  86. TResponse deserial = default(TResponse);
  87. using (WebResponse resp = request.GetResponse())
  88. {
  89. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  90. Stream respStream = null;
  91. try
  92. {
  93. respStream = resp.GetResponseStream();
  94. deserial = (TResponse)deserializer.Deserialize(respStream);
  95. }
  96. catch { }
  97. finally
  98. {
  99. if (respStream != null)
  100. respStream.Close();
  101. resp.Close();
  102. }
  103. }
  104. return deserial;
  105. }
  106. }
  107. public class RestSessionObjectPosterResponse<TRequest, TResponse>
  108. {
  109. public ReturnResponse<TResponse> ResponseCallback;
  110. public void BeginPostObject(string requestUrl, TRequest obj, string sid, string aid)
  111. {
  112. BeginPostObject("POST", requestUrl, obj, sid, aid);
  113. }
  114. public void BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
  115. {
  116. RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>();
  117. sobj.SessionID = sid;
  118. sobj.AvatarID = aid;
  119. sobj.Body = obj;
  120. Type type = typeof(RestSessionObject<TRequest>);
  121. WebRequest request = WebRequest.Create(requestUrl);
  122. request.Method = verb;
  123. request.ContentType = "text/xml";
  124. request.Timeout = 10000;
  125. MemoryStream buffer = new MemoryStream();
  126. XmlWriterSettings settings = new XmlWriterSettings();
  127. settings.Encoding = Encoding.UTF8;
  128. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  129. {
  130. XmlSerializer serializer = new XmlSerializer(type);
  131. serializer.Serialize(writer, sobj);
  132. writer.Flush();
  133. }
  134. buffer.Close();
  135. int length = (int)buffer.Length;
  136. request.ContentLength = length;
  137. Stream requestStream = request.GetRequestStream();
  138. requestStream.Write(buffer.ToArray(), 0, length);
  139. requestStream.Close();
  140. // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
  141. request.BeginGetResponse(AsyncCallback, request);
  142. }
  143. private void AsyncCallback(IAsyncResult result)
  144. {
  145. WebRequest request = (WebRequest)result.AsyncState;
  146. using (WebResponse resp = request.EndGetResponse(result))
  147. {
  148. TResponse deserial;
  149. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  150. Stream stream = resp.GetResponseStream();
  151. // This is currently a bad debug stanza since it gobbles us the response...
  152. // StreamReader reader = new StreamReader(stream);
  153. // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd());
  154. deserial = (TResponse)deserializer.Deserialize(stream);
  155. if (stream != null)
  156. stream.Close();
  157. if (deserial != null && ResponseCallback != null)
  158. {
  159. ResponseCallback(deserial);
  160. }
  161. }
  162. }
  163. }
  164. public delegate bool CheckIdentityMethod(string sid, string aid);
  165. public class RestDeserialiseSecureHandler<TRequest, TResponse> : BaseRequestHandler, IStreamHandler
  166. where TRequest : new()
  167. {
  168. private static readonly ILog m_log
  169. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  170. private RestDeserialiseMethod<TRequest, TResponse> m_method;
  171. private CheckIdentityMethod m_smethod;
  172. public RestDeserialiseSecureHandler(
  173. string httpMethod, string path,
  174. RestDeserialiseMethod<TRequest, TResponse> method, CheckIdentityMethod smethod)
  175. : base(httpMethod, path)
  176. {
  177. m_smethod = smethod;
  178. m_method = method;
  179. }
  180. public void Handle(string path, Stream request, Stream responseStream,
  181. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  182. {
  183. RestSessionObject<TRequest> deserial = default(RestSessionObject<TRequest>);
  184. bool fail = false;
  185. using (XmlTextReader xmlReader = new XmlTextReader(request))
  186. {
  187. try
  188. {
  189. XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>));
  190. deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader);
  191. }
  192. catch (Exception e)
  193. {
  194. m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
  195. fail = true;
  196. }
  197. }
  198. TResponse response = default(TResponse);
  199. if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID))
  200. {
  201. response = m_method(deserial.Body);
  202. }
  203. using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
  204. {
  205. XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
  206. serializer.Serialize(xmlWriter, response);
  207. }
  208. }
  209. }
  210. public delegate bool CheckTrustedSourceMethod(IPEndPoint peer);
  211. public class RestDeserialiseTrustedHandler<TRequest, TResponse> : BaseRequestHandler, IStreamHandler
  212. where TRequest : new()
  213. {
  214. private static readonly ILog m_log
  215. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  216. /// <summary>
  217. /// The operation to perform once trust has been established.
  218. /// </summary>
  219. private RestDeserialiseMethod<TRequest, TResponse> m_method;
  220. /// <summary>
  221. /// The method used to check whether a request is trusted.
  222. /// </summary>
  223. private CheckTrustedSourceMethod m_tmethod;
  224. public RestDeserialiseTrustedHandler(string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckTrustedSourceMethod tmethod)
  225. : base(httpMethod, path)
  226. {
  227. m_tmethod = tmethod;
  228. m_method = method;
  229. }
  230. public void Handle(string path, Stream request, Stream responseStream,
  231. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  232. {
  233. TRequest deserial = default(TRequest);
  234. bool fail = false;
  235. using (XmlTextReader xmlReader = new XmlTextReader(request))
  236. {
  237. try
  238. {
  239. XmlSerializer deserializer = new XmlSerializer(typeof(TRequest));
  240. deserial = (TRequest)deserializer.Deserialize(xmlReader);
  241. }
  242. catch (Exception e)
  243. {
  244. m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
  245. fail = true;
  246. }
  247. }
  248. TResponse response = default(TResponse);
  249. if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint))
  250. {
  251. response = m_method(deserial);
  252. }
  253. using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
  254. {
  255. XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
  256. serializer.Serialize(xmlWriter, response);
  257. }
  258. }
  259. }
  260. }