1
0

RestSessionService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. using (MemoryStream buffer = new MemoryStream())
  72. {
  73. XmlWriterSettings settings = new XmlWriterSettings();
  74. settings.Encoding = Encoding.UTF8;
  75. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  76. {
  77. XmlSerializer serializer = new XmlSerializer(type);
  78. serializer.Serialize(writer, sobj);
  79. writer.Flush();
  80. }
  81. int length = (int)buffer.Length;
  82. request.ContentLength = length;
  83. using (Stream requestStream = request.GetRequestStream())
  84. requestStream.Write(buffer.ToArray(), 0, length);
  85. }
  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. using (MemoryStream buffer = new MemoryStream())
  115. {
  116. XmlWriterSettings settings = new XmlWriterSettings();
  117. settings.Encoding = Encoding.UTF8;
  118. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  119. {
  120. XmlSerializer serializer = new XmlSerializer(type);
  121. serializer.Serialize(writer, sobj);
  122. writer.Flush();
  123. }
  124. int length = (int)buffer.Length;
  125. request.ContentLength = length;
  126. using (Stream requestStream = request.GetRequestStream())
  127. requestStream.Write(buffer.ToArray(), 0, length);
  128. }
  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. xmlReader.DtdProcessing = DtdProcessing.Ignore;
  179. XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>));
  180. deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader);
  181. }
  182. catch (Exception e)
  183. {
  184. m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
  185. fail = true;
  186. }
  187. }
  188. TResponse response = default(TResponse);
  189. if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID))
  190. {
  191. response = m_method(deserial.Body);
  192. }
  193. using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
  194. {
  195. XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
  196. serializer.Serialize(xmlWriter, response);
  197. }
  198. }
  199. }
  200. public delegate bool CheckTrustedSourceMethod(IPEndPoint peer);
  201. public class RestDeserialiseTrustedHandler<TRequest, TResponse> : BaseOutputStreamHandler, IStreamHandler
  202. where TRequest : new()
  203. {
  204. private static readonly ILog m_log
  205. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  206. /// <summary>
  207. /// The operation to perform once trust has been established.
  208. /// </summary>
  209. private RestDeserialiseMethod<TRequest, TResponse> m_method;
  210. /// <summary>
  211. /// The method used to check whether a request is trusted.
  212. /// </summary>
  213. private CheckTrustedSourceMethod m_tmethod;
  214. public RestDeserialiseTrustedHandler(string httpMethod, string path, RestDeserialiseMethod<TRequest, TResponse> method, CheckTrustedSourceMethod tmethod)
  215. : base(httpMethod, path)
  216. {
  217. m_tmethod = tmethod;
  218. m_method = method;
  219. }
  220. protected override void ProcessRequest(string path, Stream request, Stream responseStream,
  221. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  222. {
  223. TRequest deserial = default(TRequest);
  224. bool fail = false;
  225. using (XmlTextReader xmlReader = new XmlTextReader(request))
  226. {
  227. try
  228. {
  229. xmlReader.DtdProcessing = DtdProcessing.Ignore;
  230. XmlSerializer deserializer = new XmlSerializer(typeof(TRequest));
  231. deserial = (TRequest)deserializer.Deserialize(xmlReader);
  232. }
  233. catch (Exception e)
  234. {
  235. m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
  236. fail = true;
  237. }
  238. }
  239. TResponse response = default(TResponse);
  240. if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint))
  241. {
  242. response = m_method(deserial);
  243. }
  244. using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
  245. {
  246. XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
  247. serializer.Serialize(xmlWriter, response);
  248. }
  249. }
  250. }
  251. }