WebUtil.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. using (Stream requestStream = request.GetRequestStream())
  129. requestStream.Write(requestData, 0, requestData.Length);
  130. using (WebResponse response = request.GetResponse())
  131. {
  132. using (Stream responseStream = response.GetResponseStream())
  133. {
  134. string responseStr = null;
  135. try
  136. {
  137. responseStr = responseStream.GetStreamString();
  138. OSD responseOSD = OSDParser.Deserialize(responseStr);
  139. if (responseOSD.Type == OSDType.Map)
  140. return (OSDMap)responseOSD;
  141. else
  142. errorMessage = "Response format was invalid.";
  143. }
  144. catch (Exception ex)
  145. {
  146. if (!String.IsNullOrEmpty(responseStr))
  147. errorMessage = "Failed to parse the response:\n" + responseStr;
  148. else
  149. errorMessage = "Failed to retrieve the response: " + ex.Message;
  150. }
  151. }
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. m_log.Warn("POST to URL " + url + " failed: " + ex.Message);
  157. errorMessage = ex.Message;
  158. }
  159. return new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } };
  160. }
  161. #region Uri
  162. /// <summary>
  163. /// Combines a Uri that can contain both a base Uri and relative path
  164. /// with a second relative path fragment
  165. /// </summary>
  166. /// <param name="uri">Starting (base) Uri</param>
  167. /// <param name="fragment">Relative path fragment to append to the end
  168. /// of the Uri</param>
  169. /// <returns>The combined Uri</returns>
  170. /// <remarks>This is similar to the Uri constructor that takes a base
  171. /// Uri and the relative path, except this method can append a relative
  172. /// path fragment on to an existing relative path</remarks>
  173. public static Uri Combine(this Uri uri, string fragment)
  174. {
  175. string fragment1 = uri.Fragment;
  176. string fragment2 = fragment;
  177. if (!fragment1.EndsWith("/"))
  178. fragment1 = fragment1 + '/';
  179. if (fragment2.StartsWith("/"))
  180. fragment2 = fragment2.Substring(1);
  181. return new Uri(uri, fragment1 + fragment2);
  182. }
  183. /// <summary>
  184. /// Combines a Uri that can contain both a base Uri and relative path
  185. /// with a second relative path fragment. If the fragment is absolute,
  186. /// it will be returned without modification
  187. /// </summary>
  188. /// <param name="uri">Starting (base) Uri</param>
  189. /// <param name="fragment">Relative path fragment to append to the end
  190. /// of the Uri, or an absolute Uri to return unmodified</param>
  191. /// <returns>The combined Uri</returns>
  192. public static Uri Combine(this Uri uri, Uri fragment)
  193. {
  194. if (fragment.IsAbsoluteUri)
  195. return fragment;
  196. string fragment1 = uri.Fragment;
  197. string fragment2 = fragment.ToString();
  198. if (!fragment1.EndsWith("/"))
  199. fragment1 = fragment1 + '/';
  200. if (fragment2.StartsWith("/"))
  201. fragment2 = fragment2.Substring(1);
  202. return new Uri(uri, fragment1 + fragment2);
  203. }
  204. /// <summary>
  205. /// Appends a query string to a Uri that may or may not have existing
  206. /// query parameters
  207. /// </summary>
  208. /// <param name="uri">Uri to append the query to</param>
  209. /// <param name="query">Query string to append. Can either start with ?
  210. /// or just containg key/value pairs</param>
  211. /// <returns>String representation of the Uri with the query string
  212. /// appended</returns>
  213. public static string AppendQuery(this Uri uri, string query)
  214. {
  215. if (String.IsNullOrEmpty(query))
  216. return uri.ToString();
  217. if (query[0] == '?' || query[0] == '&')
  218. query = query.Substring(1);
  219. string uriStr = uri.ToString();
  220. if (uriStr.Contains("?"))
  221. return uriStr + '&' + query;
  222. else
  223. return uriStr + '?' + query;
  224. }
  225. #endregion Uri
  226. #region NameValueCollection
  227. /// <summary>
  228. /// Convert a NameValueCollection into a query string. This is the
  229. /// inverse of HttpUtility.ParseQueryString()
  230. /// </summary>
  231. /// <param name="parameters">Collection of key/value pairs to convert</param>
  232. /// <returns>A query string with URL-escaped values</returns>
  233. public static string BuildQueryString(NameValueCollection parameters)
  234. {
  235. List<string> items = new List<string>(parameters.Count);
  236. foreach (string key in parameters.Keys)
  237. {
  238. string[] values = parameters.GetValues(key);
  239. if (values != null)
  240. {
  241. foreach (string value in values)
  242. items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
  243. }
  244. }
  245. return String.Join("&", items.ToArray());
  246. }
  247. /// <summary>
  248. ///
  249. /// </summary>
  250. /// <param name="collection"></param>
  251. /// <param name="key"></param>
  252. /// <returns></returns>
  253. public static string GetOne(this NameValueCollection collection, string key)
  254. {
  255. string[] values = collection.GetValues(key);
  256. if (values != null && values.Length > 0)
  257. return values[0];
  258. return null;
  259. }
  260. #endregion NameValueCollection
  261. #region Stream
  262. /// <summary>
  263. /// Copies the contents of one stream to another, starting at the
  264. /// current position of each stream
  265. /// </summary>
  266. /// <param name="copyFrom">The stream to copy from, at the position
  267. /// where copying should begin</param>
  268. /// <param name="copyTo">The stream to copy to, at the position where
  269. /// bytes should be written</param>
  270. /// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
  271. /// <returns>The total number of bytes copied</returns>
  272. /// <remarks>
  273. /// Copying begins at the streams' current positions. The positions are
  274. /// NOT reset after copying is complete.
  275. /// </remarks>
  276. public static int CopyTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
  277. {
  278. byte[] buffer = new byte[4096];
  279. int readBytes;
  280. int totalCopiedBytes = 0;
  281. while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
  282. {
  283. int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
  284. copyTo.Write(buffer, 0, writeBytes);
  285. totalCopiedBytes += writeBytes;
  286. maximumBytesToCopy -= writeBytes;
  287. }
  288. return totalCopiedBytes;
  289. }
  290. /// <summary>
  291. /// Converts an entire stream to a string, regardless of current stream
  292. /// position
  293. /// </summary>
  294. /// <param name="stream">The stream to convert to a string</param>
  295. /// <returns></returns>
  296. /// <remarks>When this method is done, the stream position will be
  297. /// reset to its previous position before this method was called</remarks>
  298. public static string GetStreamString(this Stream stream)
  299. {
  300. string value = null;
  301. if (stream != null && stream.CanRead)
  302. {
  303. long rewindPos = -1;
  304. if (stream.CanSeek)
  305. {
  306. rewindPos = stream.Position;
  307. stream.Seek(0, SeekOrigin.Begin);
  308. }
  309. StreamReader reader = new StreamReader(stream);
  310. value = reader.ReadToEnd();
  311. if (rewindPos >= 0)
  312. stream.Seek(rewindPos, SeekOrigin.Begin);
  313. }
  314. return value;
  315. }
  316. #endregion Stream
  317. }
  318. }