RestSessionService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. using (Stream respStream = resp.GetResponseStream())
  91. deserial = (TResponse)deserializer.Deserialize(respStream);
  92. }
  93. return deserial;
  94. }
  95. }
  96. public class RestSessionObjectPosterResponse<TRequest, TResponse>
  97. {
  98. public ReturnResponse<TResponse> ResponseCallback;
  99. public void BeginPostObject(string requestUrl, TRequest obj, string sid, string aid)
  100. {
  101. BeginPostObject("POST", requestUrl, obj, sid, aid);
  102. }
  103. public void BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
  104. {
  105. RestSessionObject<TRequest> sobj = new RestSessionObject<TRequest>();
  106. sobj.SessionID = sid;
  107. sobj.AvatarID = aid;
  108. sobj.Body = obj;
  109. Type type = typeof(RestSessionObject<TRequest>);
  110. WebRequest request = WebRequest.Create(requestUrl);
  111. request.Method = verb;
  112. request.ContentType = "text/xml";
  113. request.Timeout = 10000;
  114. MemoryStream buffer = new MemoryStream();
  115. XmlWriterSettings settings = new XmlWriterSettings();
  116. settings.Encoding = Encoding.UTF8;
  117. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  118. {
  119. XmlSerializer serializer = new XmlSerializer(type);
  120. serializer.Serialize(writer, sobj);
  121. writer.Flush();
  122. }
  123. buffer.Close();
  124. int length = (int)buffer.Length;
  125. request.ContentLength = length;
  126. Stream requestStream = request.GetRequestStream();
  127. requestStream.Write(buffer.ToArray(), 0, length);
  128. requestStream.Close();
  129. // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
  130. request.BeginGetResponse(AsyncCallback, request);
  131. }
  132. private void AsyncCallback(IAsyncResult result)
  133. {
  134. WebRequest request = (WebRequest)result.AsyncState;
  135. using (WebResponse resp = request.EndGetResponse(result))
  136. {
  137. TResponse deserial;
  138. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  139. Stream stream = resp.GetResponseStream();
  140. // This is currently a bad debug stanza since it gobbles us the response...
  141. // StreamReader reader = new StreamReader(stream);
  142. // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd());
  143. deserial = (TResponse)deserializer.Deserialize(stream);
  144. if (stream != null)
  145. stream.Close();
  146. if (deserial != null && ResponseCallback != null)
  147. {
  148. ResponseCallback(deserial);
  149. }
  150. }
  151. }
  152. }
  153. public delegate bool CheckIdentityMethod(string sid, string aid);
  154. public class RestDeserialiseSecureHandler<TRequest, TResponse> : BaseOutputStreamHandler, IStreamHandler
  155. where TRequest : new()
  156. {
  157. private static readonly ILog m_log
  158. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  159. private RestDeserialiseMethod<TRequest, TResponse> m_method;
  160. private CheckIdentityMethod m_smethod;
  161. public RestDeserialiseSecureHandler(
  162. string httpMethod, string path,
  163. RestDeserialiseMethod<TRequest, TResponse> method, CheckIdentityMethod smethod)
  164. : base(httpMethod, path)
  165. {
  166. m_smethod = smethod;
  167. m_method = method;
  168. }
  169. protected override void ProcessRequest(string path, Stream request, Stream responseStream,
  170. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  171. {
  172. RestSessionObject<TRequest> deserial = default(RestSessionObject<TRequest>);
  173. bool fail = false;
  174. using (XmlTextReader xmlReader = new XmlTextReader(request))
  175. {
  176. try
  177. {
  178. XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>));
  179. deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader);
  180. }
  181. catch (Exception e)
  182. {
  183. m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
  184. fail = true;
  185. }
  186. }
  187. TResponse response = default(TResponse);
  188. if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID))
  189. {
  190. response = m_method(deserial.Body);
  191. }
  192. using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
  193. {
  194. XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
  195. serializer.Serialize(xmlWriter, response);
  196. }
  197. }
  198. }
  199. public delegate bool CheckTrustedSourceMethod(IPEndPoint peer);
  200. public class RestDeserialiseTrustedHandler<TRequest, TResponse> : BaseOutputStreamHandler, IStreamHandler
  201. where TRequest : new()
  202. {
  203. private static readonly ILog m_log
  204. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  205. /// <summary>
  206. /// The operation to perform once trust has been established.
  207. /// </summary>
  208. private RestDeserialiseMethod<TRequest, TResponse> m_method;
  209. /// <summary>
  210. /// The method used to check whether a request is trusted.
  211. /// </summary>
  212. private CheckTrustedSourceMethod m_tmethod;
  213. public RestDeserialiseTrustedHandler(string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckTrustedSourceMethod tmethod)
  214. : base(httpMethod, path)
  215. {
  216. m_tmethod = tmethod;
  217. m_method = method;
  218. }
  219. protected override void ProcessRequest(string path, Stream request, Stream responseStream,
  220. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  221. {
  222. TRequest deserial = default(TRequest);
  223. bool fail = false;
  224. using (XmlTextReader xmlReader = new XmlTextReader(request))
  225. {
  226. try
  227. {
  228. XmlSerializer deserializer = new XmlSerializer(typeof(TRequest));
  229. deserial = (TRequest)deserializer.Deserialize(xmlReader);
  230. }
  231. catch (Exception e)
  232. {
  233. m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
  234. fail = true;
  235. }
  236. }
  237. TResponse response = default(TResponse);
  238. if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint))
  239. {
  240. response = m_method(deserial);
  241. }
  242. using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
  243. {
  244. XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
  245. serializer.Serialize(xmlWriter, response);
  246. }
  247. }
  248. }
  249. }