RestSessionService.cs 11 KB

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