RestClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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.IO;
  30. using System.Net;
  31. using System.Net.Http;
  32. using System.Reflection;
  33. using System.Runtime.CompilerServices;
  34. using System.Text;
  35. using System.Threading;
  36. using System.Web;
  37. using log4net;
  38. using OpenSim.Framework.ServiceAuth;
  39. namespace OpenSim.Framework
  40. {
  41. /// <summary>
  42. /// Implementation of a generic REST client
  43. /// </summary>
  44. /// <remarks>
  45. /// This class is a generic implementation of a REST (Representational State Transfer) web service. This
  46. /// </remarks>
  47. public class RestClient : IDisposable
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. // private string realuri;
  51. #region member variables
  52. /// <summary>
  53. /// The base Uri of the web-service e.g. http://www.google.com
  54. /// </summary>
  55. private readonly string _url;
  56. /// <summary>
  57. /// Path elements of the query
  58. /// </summary>
  59. private readonly List<string> _pathElements = new();
  60. /// <summary>
  61. /// Parameter elements of the query, e.g. min=34
  62. /// </summary>
  63. private readonly Dictionary<string, string> _parameterElements = new();
  64. /// <summary>
  65. /// Request method. E.g. GET, POST, PUT or DELETE
  66. /// </summary>
  67. private string _method;
  68. /// <summary>
  69. /// Temporary buffer used to store bytes temporarily as they come in from the server
  70. /// </summary>
  71. private readonly byte[] _readbuf;
  72. /// <summary>
  73. /// MemoryStream representing the resulting resource
  74. /// </summary>
  75. private readonly MemoryStream _resource;
  76. /// <summary>
  77. /// Default time out period
  78. /// </summary>
  79. private const int DefaultTimeout = 90000; // 90 seconds timeout
  80. /// <summary>
  81. /// Default Buffer size of a block requested from the web-server
  82. /// </summary>
  83. private const int BufferSize = 4 * 4096; // Read blocks of 4 * 4 KB.
  84. #endregion member variables
  85. #region constructors
  86. /// <summary>
  87. /// Instantiate a new RestClient
  88. /// </summary>
  89. /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
  90. public RestClient(string url)
  91. {
  92. _url = url;
  93. _readbuf = new byte[BufferSize];
  94. _resource = new MemoryStream();
  95. _lock = new object();
  96. }
  97. private readonly object _lock;
  98. #endregion constructors
  99. #region Dispose
  100. private bool disposed = false;
  101. public void Dispose()
  102. {
  103. Dispose(true);
  104. GC.SuppressFinalize(this);
  105. }
  106. protected virtual void Dispose(bool disposing)
  107. {
  108. if (disposed)
  109. return;
  110. if (disposing)
  111. {
  112. _resource.Dispose();
  113. }
  114. disposed = true;
  115. }
  116. #endregion Dispose
  117. /// <summary>
  118. /// Add a path element to the query, e.g. assets
  119. /// </summary>
  120. /// <param name="element">path entry</param>
  121. public void AddResourcePath(string element)
  122. {
  123. _pathElements.Add(Util.TrimEndSlash(element));
  124. }
  125. /// <summary>
  126. /// Add a query parameter to the Url
  127. /// </summary>
  128. /// <param name="name">Name of the parameter, e.g. min</param>
  129. /// <param name="value">Value of the parameter, e.g. 42</param>
  130. public void AddQueryParameter(string name, string value)
  131. {
  132. try
  133. {
  134. _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
  135. }
  136. catch (ArgumentException)
  137. {
  138. m_log.Error("[REST]: Query parameter " + name + " is already added.");
  139. }
  140. catch (Exception e)
  141. {
  142. m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
  143. }
  144. }
  145. /// <summary>
  146. /// Add a query parameter to the Url
  147. /// </summary>
  148. /// <param name="name">Name of the parameter, e.g. min</param>
  149. public void AddQueryParameter(string name)
  150. {
  151. try
  152. {
  153. _parameterElements.Add(HttpUtility.UrlEncode(name), null);
  154. }
  155. catch (ArgumentException)
  156. {
  157. m_log.Error("[REST]: Query parameter " + name + " is already added.");
  158. }
  159. catch (Exception e)
  160. {
  161. m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
  162. }
  163. }
  164. /// <summary>
  165. /// Web-Request method, e.g. GET, PUT, POST, DELETE
  166. /// </summary>
  167. public string RequestMethod
  168. {
  169. get { return _method; }
  170. set { _method = value; }
  171. }
  172. /// <summary>
  173. /// Build a Uri based on the initial Url, path elements and parameters
  174. /// </summary>
  175. /// <returns>fully constructed Uri</returns>
  176. private Uri buildUri()
  177. {
  178. StringBuilder sb = new();
  179. sb.Append(_url);
  180. foreach (string e in _pathElements)
  181. {
  182. sb.Append('/');
  183. sb.Append(e);
  184. }
  185. bool firstElement = true;
  186. foreach (KeyValuePair<string, string> kv in _parameterElements)
  187. {
  188. if (firstElement)
  189. {
  190. sb.Append('?');
  191. firstElement = false;
  192. }
  193. else
  194. sb.Append('&');
  195. sb.Append(kv.Key);
  196. if (!string.IsNullOrEmpty(kv.Value))
  197. {
  198. sb.Append('=');
  199. sb.Append(kv.Value);
  200. }
  201. }
  202. // realuri = sb.ToString();
  203. //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
  204. return new Uri(sb.ToString());
  205. }
  206. /// <summary>
  207. /// Perform a synchronous request
  208. /// </summary>
  209. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  210. public MemoryStream Request()
  211. {
  212. return Request(null);
  213. }
  214. /// <summary>
  215. /// Perform a synchronous request
  216. /// </summary>
  217. public MemoryStream Request(IServiceAuth auth)
  218. {
  219. lock (_lock)
  220. {
  221. Uri uri = null;
  222. HttpResponseMessage responseMessage = null;
  223. HttpRequestMessage request = null;
  224. HttpClient client = null;
  225. try
  226. {
  227. client = WebUtil.GetNewGlobalHttpClient(DefaultTimeout);
  228. uri = buildUri();
  229. request = new(new HttpMethod(RequestMethod), uri);
  230. auth?.AddAuthorization(request.Headers);
  231. request.Headers.ExpectContinue = false;
  232. request.Headers.TransferEncodingChunked = false;
  233. //if (keepalive)
  234. {
  235. request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
  236. request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
  237. request.Headers.ConnectionClose = false;
  238. }
  239. //else
  240. // request.Headers.TryAddWithoutValidation("Connection", "close");
  241. if (WebUtil.DebugLevel >= 3)
  242. m_log.DebugFormat("[REST CLIENT] {0} to {1}", RequestMethod, uri);
  243. //_request.ContentType = "application/xml";
  244. responseMessage = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
  245. responseMessage.EnsureSuccessStatusCode();
  246. Stream respStream = responseMessage.Content.ReadAsStream();
  247. int length = respStream.Read(_readbuf, 0, BufferSize);
  248. while (length > 0)
  249. {
  250. _resource.Write(_readbuf, 0, length);
  251. length = respStream.Read(_readbuf, 0, BufferSize);
  252. }
  253. }
  254. catch (HttpRequestException e)
  255. {
  256. if(uri is not null)
  257. {
  258. if (e.StatusCode is HttpStatusCode status)
  259. {
  260. if (status == HttpStatusCode.NotFound)
  261. {
  262. // This is often benign. E.g., requesting a missing asset will return 404.
  263. m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", uri.ToString());
  264. }
  265. else
  266. {
  267. m_log.Error($"[REST CLIENT] Error fetching resource from server: {uri} status: {status} {e.Message}");
  268. }
  269. }
  270. else
  271. {
  272. m_log.Error($"[REST CLIENT] Error fetching resource from server: {uri} {e.Message}");
  273. }
  274. }
  275. else
  276. {
  277. m_log.Error($"[REST CLIENT] Error fetching null resource from server: {e.Message}");
  278. }
  279. return null;
  280. }
  281. finally
  282. {
  283. request?.Dispose();
  284. responseMessage?.Dispose();
  285. client?.Dispose();
  286. }
  287. if (_resource != null)
  288. {
  289. _resource.Flush();
  290. _resource.Seek(0, SeekOrigin.Begin);
  291. }
  292. if (WebUtil.DebugLevel >= 5)
  293. WebUtil.LogOutgoingDetail("[REST CLIENT]", _resource);
  294. return _resource;
  295. }
  296. }
  297. // just sync post data, ignoring result
  298. public void POSTRequest(byte[] src, IServiceAuth auth)
  299. {
  300. Uri uri = null;
  301. HttpResponseMessage responseMessage = null;
  302. HttpRequestMessage request = null;
  303. HttpClient client = null;
  304. try
  305. {
  306. client = WebUtil.GetNewGlobalHttpClient(DefaultTimeout);
  307. uri = buildUri();
  308. request = new(HttpMethod.Post, uri);
  309. auth?.AddAuthorization(request.Headers);
  310. request.Headers.ExpectContinue = false;
  311. request.Headers.TransferEncodingChunked = false;
  312. //if (keepalive)
  313. {
  314. request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=30, max=10");
  315. request.Headers.TryAddWithoutValidation("Connection", "Keep-Alive");
  316. request.Headers.ConnectionClose = false;
  317. }
  318. //else
  319. // request.Headers.TryAddWithoutValidation("Connection", "close");
  320. request.Content = new ByteArrayContent(src);
  321. request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/xml");
  322. request.Content.Headers.TryAddWithoutValidation("Content-Length", src.Length.ToString());
  323. responseMessage = client.Send(request, HttpCompletionOption.ResponseContentRead);
  324. responseMessage.EnsureSuccessStatusCode();
  325. }
  326. catch (HttpRequestException e)
  327. {
  328. if(uri is not null)
  329. {
  330. if (e.StatusCode is HttpStatusCode status)
  331. m_log.Warn($"[REST]: POST {uri} failed with status {status} and message {e.Message}");
  332. else
  333. m_log.Warn($"[REST]: POST {uri} failed with message {e.Message}");
  334. }
  335. else
  336. m_log.Warn($"[REST]: POST failed {e.Message}");
  337. return;
  338. }
  339. catch (Exception e)
  340. {
  341. if (uri is not null)
  342. m_log.Warn($"[REST]: POST {uri} failed with message {e.Message}");
  343. else
  344. m_log.Warn($"[REST]: POST failed {e.Message}");
  345. return;
  346. }
  347. finally
  348. {
  349. request?.Dispose();
  350. responseMessage?.Dispose();
  351. client?.Dispose();
  352. }
  353. }
  354. }
  355. }