WebUtil.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.Collections.Generic;
  29. using System.Collections.Specialized;
  30. using System.IO;
  31. using System.Net;
  32. using System.Net.Security;
  33. using System.Reflection;
  34. using System.Text;
  35. using System.Web;
  36. using log4net;
  37. using OpenSim.Framework.Servers.HttpServer;
  38. using OpenMetaverse.StructuredData;
  39. namespace OpenSim.Framework
  40. {
  41. /// <summary>
  42. /// Miscellaneous static methods and extension methods related to the web
  43. /// </summary>
  44. public static class WebUtil
  45. {
  46. private static readonly ILog m_log =
  47. LogManager.GetLogger(
  48. MethodBase.GetCurrentMethod().DeclaringType);
  49. /// <summary>
  50. /// Send LLSD to an HTTP client in application/llsd+json form
  51. /// </summary>
  52. /// <param name="response">HTTP response to send the data in</param>
  53. /// <param name="body">LLSD to send to the client</param>
  54. public static void SendJSONResponse(OSHttpResponse response, OSDMap body)
  55. {
  56. byte[] responseData = Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(body));
  57. response.ContentEncoding = Encoding.UTF8;
  58. response.ContentLength = responseData.Length;
  59. response.ContentType = "application/llsd+json";
  60. response.Body.Write(responseData, 0, responseData.Length);
  61. }
  62. /// <summary>
  63. /// Send LLSD to an HTTP client in application/llsd+xml form
  64. /// </summary>
  65. /// <param name="response">HTTP response to send the data in</param>
  66. /// <param name="body">LLSD to send to the client</param>
  67. public static void SendXMLResponse(OSHttpResponse response, OSDMap body)
  68. {
  69. byte[] responseData = OSDParser.SerializeLLSDXmlBytes(body);
  70. response.ContentEncoding = Encoding.UTF8;
  71. response.ContentLength = responseData.Length;
  72. response.ContentType = "application/llsd+xml";
  73. response.Body.Write(responseData, 0, responseData.Length);
  74. }
  75. /// <summary>
  76. /// Make a GET or GET-like request to a web service that returns LLSD
  77. /// or JSON data
  78. /// </summary>
  79. public static OSDMap ServiceRequest(string url, string httpVerb)
  80. {
  81. string errorMessage;
  82. try
  83. {
  84. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  85. request.Method = httpVerb;
  86. using (WebResponse response = request.GetResponse())
  87. {
  88. using (Stream responseStream = response.GetResponseStream())
  89. {
  90. try
  91. {
  92. string responseStr = responseStream.GetStreamString();
  93. OSD responseOSD = OSDParser.Deserialize(responseStr);
  94. if (responseOSD.Type == OSDType.Map)
  95. return (OSDMap)responseOSD;
  96. else
  97. errorMessage = "Response format was invalid.";
  98. }
  99. catch
  100. {
  101. errorMessage = "Failed to parse the response.";
  102. }
  103. }
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. m_log.Warn(httpVerb + " on URL " + url + " failed: " + ex.Message);
  109. errorMessage = ex.Message;
  110. }
  111. return new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } };
  112. }
  113. /// <summary>
  114. /// POST URL-encoded form data to a web service that returns LLSD or
  115. /// JSON data
  116. /// </summary>
  117. public static OSDMap PostToService(string url, NameValueCollection data)
  118. {
  119. string errorMessage;
  120. try
  121. {
  122. string queryString = BuildQueryString(data);
  123. byte[] requestData = System.Text.Encoding.UTF8.GetBytes(queryString);
  124. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  125. request.Method = "POST";
  126. request.ContentLength = requestData.Length;
  127. request.ContentType = "application/x-www-form-urlencoded";
  128. Stream requestStream = request.GetRequestStream();
  129. requestStream.Write(requestData, 0, requestData.Length);
  130. requestStream.Close();
  131. using (WebResponse response = request.GetResponse())
  132. {
  133. using (Stream responseStream = response.GetResponseStream())
  134. {
  135. string responseStr = null;
  136. try
  137. {
  138. responseStr = responseStream.GetStreamString();
  139. OSD responseOSD = OSDParser.Deserialize(responseStr);
  140. if (responseOSD.Type == OSDType.Map)
  141. return (OSDMap)responseOSD;
  142. else
  143. errorMessage = "Response format was invalid.";
  144. }
  145. catch (Exception ex)
  146. {
  147. if (!String.IsNullOrEmpty(responseStr))
  148. errorMessage = "Failed to parse the response:\n" + responseStr;
  149. else
  150. errorMessage = "Failed to retrieve the response: " + ex.Message;
  151. }
  152. }
  153. }
  154. }
  155. catch (Exception ex)
  156. {
  157. m_log.Warn("POST to URL " + url + " failed: " + ex);
  158. errorMessage = ex.Message;
  159. }
  160. return new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } };
  161. }
  162. #region Uri
  163. /// <summary>
  164. /// Combines a Uri that can contain both a base Uri and relative path
  165. /// with a second relative path fragment
  166. /// </summary>
  167. /// <param name="uri">Starting (base) Uri</param>
  168. /// <param name="fragment">Relative path fragment to append to the end
  169. /// of the Uri</param>
  170. /// <returns>The combined Uri</returns>
  171. /// <remarks>This is similar to the Uri constructor that takes a base
  172. /// Uri and the relative path, except this method can append a relative
  173. /// path fragment on to an existing relative path</remarks>
  174. public static Uri Combine(this Uri uri, string fragment)
  175. {
  176. string fragment1 = uri.Fragment;
  177. string fragment2 = fragment;
  178. if (!fragment1.EndsWith("/"))
  179. fragment1 = fragment1 + '/';
  180. if (fragment2.StartsWith("/"))
  181. fragment2 = fragment2.Substring(1);
  182. return new Uri(uri, fragment1 + fragment2);
  183. }
  184. /// <summary>
  185. /// Combines a Uri that can contain both a base Uri and relative path
  186. /// with a second relative path fragment. If the fragment is absolute,
  187. /// it will be returned without modification
  188. /// </summary>
  189. /// <param name="uri">Starting (base) Uri</param>
  190. /// <param name="fragment">Relative path fragment to append to the end
  191. /// of the Uri, or an absolute Uri to return unmodified</param>
  192. /// <returns>The combined Uri</returns>
  193. public static Uri Combine(this Uri uri, Uri fragment)
  194. {
  195. if (fragment.IsAbsoluteUri)
  196. return fragment;
  197. string fragment1 = uri.Fragment;
  198. string fragment2 = fragment.ToString();
  199. if (!fragment1.EndsWith("/"))
  200. fragment1 = fragment1 + '/';
  201. if (fragment2.StartsWith("/"))
  202. fragment2 = fragment2.Substring(1);
  203. return new Uri(uri, fragment1 + fragment2);
  204. }
  205. /// <summary>
  206. /// Appends a query string to a Uri that may or may not have existing
  207. /// query parameters
  208. /// </summary>
  209. /// <param name="uri">Uri to append the query to</param>
  210. /// <param name="query">Query string to append. Can either start with ?
  211. /// or just containg key/value pairs</param>
  212. /// <returns>String representation of the Uri with the query string
  213. /// appended</returns>
  214. public static string AppendQuery(this Uri uri, string query)
  215. {
  216. if (String.IsNullOrEmpty(query))
  217. return uri.ToString();
  218. if (query[0] == '?' || query[0] == '&')
  219. query = query.Substring(1);
  220. string uriStr = uri.ToString();
  221. if (uriStr.Contains("?"))
  222. return uriStr + '&' + query;
  223. else
  224. return uriStr + '?' + query;
  225. }
  226. #endregion Uri
  227. #region NameValueCollection
  228. /// <summary>
  229. /// Convert a NameValueCollection into a query string. This is the
  230. /// inverse of HttpUtility.ParseQueryString()
  231. /// </summary>
  232. /// <param name="parameters">Collection of key/value pairs to convert</param>
  233. /// <returns>A query string with URL-escaped values</returns>
  234. public static string BuildQueryString(NameValueCollection parameters)
  235. {
  236. List<string> items = new List<string>(parameters.Count);
  237. foreach (string key in parameters.Keys)
  238. {
  239. string[] values = parameters.GetValues(key);
  240. if (values != null)
  241. {
  242. foreach (string value in values)
  243. items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
  244. }
  245. }
  246. return String.Join("&", items.ToArray());
  247. }
  248. /// <summary>
  249. ///
  250. /// </summary>
  251. /// <param name="collection"></param>
  252. /// <param name="key"></param>
  253. /// <returns></returns>
  254. public static string GetOne(this NameValueCollection collection, string key)
  255. {
  256. string[] values = collection.GetValues(key);
  257. if (values != null && values.Length > 0)
  258. return values[0];
  259. return null;
  260. }
  261. #endregion NameValueCollection
  262. #region Stream
  263. /// <summary>
  264. /// Copies the contents of one stream to another, starting at the
  265. /// current position of each stream
  266. /// </summary>
  267. /// <param name="copyFrom">The stream to copy from, at the position
  268. /// where copying should begin</param>
  269. /// <param name="copyTo">The stream to copy to, at the position where
  270. /// bytes should be written</param>
  271. /// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
  272. /// <returns>The total number of bytes copied</returns>
  273. /// <remarks>
  274. /// Copying begins at the streams' current positions. The positions are
  275. /// NOT reset after copying is complete.
  276. /// </remarks>
  277. public static int CopyTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
  278. {
  279. byte[] buffer = new byte[4096];
  280. int readBytes;
  281. int totalCopiedBytes = 0;
  282. while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
  283. {
  284. int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
  285. copyTo.Write(buffer, 0, writeBytes);
  286. totalCopiedBytes += writeBytes;
  287. maximumBytesToCopy -= writeBytes;
  288. }
  289. return totalCopiedBytes;
  290. }
  291. /// <summary>
  292. /// Converts an entire stream to a string, regardless of current stream
  293. /// position
  294. /// </summary>
  295. /// <param name="stream">The stream to convert to a string</param>
  296. /// <returns></returns>
  297. /// <remarks>When this method is done, the stream position will be
  298. /// reset to its previous position before this method was called</remarks>
  299. public static string GetStreamString(this Stream stream)
  300. {
  301. string value = null;
  302. if (stream != null && stream.CanRead)
  303. {
  304. long rewindPos = -1;
  305. if (stream.CanSeek)
  306. {
  307. rewindPos = stream.Position;
  308. stream.Seek(0, SeekOrigin.Begin);
  309. }
  310. StreamReader reader = new StreamReader(stream);
  311. value = reader.ReadToEnd();
  312. if (rewindPos >= 0)
  313. stream.Seek(rewindPos, SeekOrigin.Begin);
  314. }
  315. return value;
  316. }
  317. #endregion Stream
  318. }
  319. }