RestSessionService.cs 11 KB

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