1
0

HttpRequest.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Web;
  7. using OpenSim.Framework;
  8. using OSHttpServer.Exceptions;
  9. namespace OSHttpServer
  10. {
  11. /// <summary>
  12. /// Contains server side HTTP request information.
  13. /// </summary>
  14. public class HttpRequest : IHttpRequest
  15. {
  16. private const int MAXCONTENTLENGTH = 250 * 1024 * 1024;
  17. /// <summary>
  18. /// Chars used to split an URL path into multiple parts.
  19. /// </summary>
  20. public static readonly char[] UriSplitters = new[] { '/' };
  21. public static uint baseID = 0;
  22. private readonly NameValueCollection m_headers = new();
  23. //private readonly HttpParam m_param = new(HttpInput.Empty, HttpInput.Empty);
  24. private Stream m_body = new MemoryStream();
  25. private int m_bodyBytesLeft;
  26. private ConnectionType m_connection = ConnectionType.KeepAlive;
  27. private int m_contentLength;
  28. private string m_httpVersion = string.Empty;
  29. private string m_method = string.Empty;
  30. private NameValueCollection m_queryString = null;
  31. private Uri m_uri = null;
  32. private string m_uriPath;
  33. public IHttpClientContext m_context;
  34. IPEndPoint m_remoteIPEndPoint = null;
  35. public HttpRequest(IHttpClientContext pContext)
  36. {
  37. ID = ++baseID;
  38. m_context = pContext;
  39. }
  40. public uint ID { get; private set; }
  41. /// <summary>
  42. /// Gets or sets a value indicating whether this <see cref="HttpRequest"/> is secure.
  43. /// </summary>
  44. public bool Secure { get { return m_context.IsSecured; } }
  45. public IHttpClientContext Context { get { return m_context; } }
  46. /// <summary>
  47. /// Path and query (will be merged with the host header) and put in Uri
  48. /// </summary>
  49. /// <see cref="Uri"/>
  50. public string UriPath
  51. {
  52. get { return m_uriPath; }
  53. set { m_uriPath = value; }
  54. }
  55. /// <summary>
  56. /// Assign a form.
  57. /// </summary>
  58. /// <param name="form"></param>
  59. /*
  60. internal void AssignForm(HttpForm form)
  61. {
  62. _form = form;
  63. }
  64. */
  65. #region IHttpRequest Members
  66. /// <summary>
  67. /// Gets kind of types accepted by the client.
  68. /// </summary>
  69. public string[] AcceptTypes { get; private set; }
  70. /// <summary>
  71. /// Gets or sets body stream.
  72. /// </summary>
  73. public Stream Body
  74. {
  75. get { return m_body; }
  76. set { m_body = value; }
  77. }
  78. /// <summary>
  79. /// Gets or sets kind of connection used for the session.
  80. /// </summary>
  81. public ConnectionType Connection
  82. {
  83. get { return m_connection; }
  84. set { m_connection = value; }
  85. }
  86. /// <summary>
  87. /// Gets or sets number of bytes in the body.
  88. /// </summary>
  89. public int ContentLength
  90. {
  91. get { return m_contentLength; }
  92. set
  93. {
  94. m_contentLength = value;
  95. m_bodyBytesLeft = value;
  96. }
  97. }
  98. /// <summary>
  99. /// Gets headers sent by the client.
  100. /// </summary>
  101. public NameValueCollection Headers
  102. {
  103. get { return m_headers; }
  104. }
  105. /// <summary>
  106. /// Gets or sets version of HTTP protocol that's used.
  107. /// </summary>
  108. /// <remarks>
  109. /// Probably <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/>.
  110. /// </remarks>
  111. /// <seealso cref="HttpHelper"/>
  112. public string HttpVersion
  113. {
  114. get { return m_httpVersion; }
  115. set { m_httpVersion = value; }
  116. }
  117. /// <summary>
  118. /// Gets or sets requested method.
  119. /// </summary>
  120. /// <value></value>
  121. /// <remarks>
  122. /// Will always be in upper case.
  123. /// </remarks>
  124. /// <see cref="OSHttpServer.Method"/>
  125. public string Method
  126. {
  127. get { return m_method; }
  128. set { m_method = value; }
  129. }
  130. /// <summary>
  131. /// Gets variables sent in the query string
  132. /// </summary>
  133. public NameValueCollection QueryString
  134. {
  135. get
  136. {
  137. if(m_queryString is null)
  138. {
  139. if(m_uri is null || m_uri.Query.Length == 0)
  140. m_queryString = new NameValueCollection();
  141. else
  142. {
  143. try
  144. {
  145. m_queryString = HttpUtility.ParseQueryString(m_uri.Query);
  146. }
  147. catch { m_queryString = new NameValueCollection(); }
  148. }
  149. }
  150. return m_queryString;
  151. }
  152. }
  153. public static readonly Uri EmptyUri = new("http://localhost/");
  154. /// <summary>
  155. /// Gets or sets requested URI.
  156. /// </summary>
  157. public Uri Uri
  158. {
  159. get { return m_uri; }
  160. set { m_uri = value ?? EmptyUri; } // not safe
  161. }
  162. /*
  163. /// <summary>
  164. /// Gets parameter from <see cref="QueryString"/> or <see cref="Form"/>.
  165. /// </summary>
  166. public HttpParam Param
  167. {
  168. get { return m_param; }
  169. }
  170. */
  171. /// <summary>
  172. /// Gets form parameters.
  173. /// </summary>
  174. /*
  175. public HttpForm Form
  176. {
  177. get { return _form; }
  178. }
  179. */
  180. /// <summary>
  181. /// Gets whether the request was made by Ajax (Asynchronous JavaScript)
  182. /// </summary>
  183. public bool IsAjax { get; private set; }
  184. /// <summary>
  185. /// Gets cookies that was sent with the request.
  186. /// </summary>
  187. public RequestCookies Cookies { get; private set; }
  188. public double ArrivalTS { get; set;}
  189. ///<summary>
  190. ///Creates a new object that is a copy of the current instance.
  191. ///</summary>
  192. ///
  193. ///<returns>
  194. ///A new object that is a copy of this instance.
  195. ///</returns>
  196. ///<filterpriority>2</filterpriority>
  197. public object Clone()
  198. {
  199. // this method was mainly created for testing.
  200. // dont use it that much...
  201. var request = new HttpRequest(Context)
  202. {
  203. Method = m_method,
  204. m_httpVersion = m_httpVersion,
  205. m_queryString = m_queryString,
  206. Uri = m_uri
  207. };
  208. if (AcceptTypes != null)
  209. {
  210. request.AcceptTypes = new string[AcceptTypes.Length];
  211. AcceptTypes.CopyTo(request.AcceptTypes, 0);
  212. }
  213. var buffer = new byte[m_body.Length];
  214. m_body.Read(buffer, 0, (int)m_body.Length);
  215. request.Body = new MemoryStream();
  216. request.Body.Write(buffer, 0, buffer.Length);
  217. request.Body.Seek(0, SeekOrigin.Begin);
  218. request.Body.Flush();
  219. request.m_headers.Clear();
  220. foreach (string key in m_headers)
  221. {
  222. string[] values = m_headers.GetValues(key);
  223. if (values != null)
  224. foreach (string value in values)
  225. request.AddHeader(key, value);
  226. }
  227. return request;
  228. }
  229. /// <summary>
  230. /// Decode body into a form.
  231. /// </summary>
  232. /// <param name="providers">A list with form decoders.</param>
  233. /// <exception cref="InvalidDataException">If body contents is not valid for the chosen decoder.</exception>
  234. /// <exception cref="InvalidOperationException">If body is still being transferred.</exception>
  235. /*
  236. public void DecodeBody(FormDecoderProvider providers)
  237. {
  238. if (_bodyBytesLeft > 0)
  239. throw new InvalidOperationException("Body have not yet been completed.");
  240. _form = providers.Decode(_headers["content-type"], _body, Encoding.UTF8);
  241. if (_form != HttpInput.Empty)
  242. _param.SetForm(_form);
  243. }
  244. */
  245. ///<summary>
  246. /// Cookies
  247. ///</summary>
  248. ///<param name="cookies">the cookies</param>
  249. public void SetCookies(RequestCookies cookies)
  250. {
  251. Cookies = cookies;
  252. }
  253. public IPEndPoint LocalIPEndPoint { get {return m_context.LocalIPEndPoint; }}
  254. public IPEndPoint RemoteIPEndPoint
  255. {
  256. get
  257. {
  258. if(m_remoteIPEndPoint == null)
  259. {
  260. string addr = m_headers["x-forwarded-for"];
  261. if(!string.IsNullOrEmpty(addr))
  262. {
  263. int port = m_context.LocalIPEndPoint.Port;
  264. try
  265. {
  266. m_remoteIPEndPoint = new IPEndPoint(IPAddress.Parse(addr), port);
  267. }
  268. catch
  269. {
  270. m_remoteIPEndPoint = null;
  271. }
  272. }
  273. }
  274. m_remoteIPEndPoint ??= m_context.LocalIPEndPoint;
  275. return m_remoteIPEndPoint;
  276. }
  277. }
  278. /*
  279. /// <summary>
  280. /// Create a response object.
  281. /// </summary>
  282. /// <returns>A new <see cref="IHttpResponse"/>.</returns>
  283. public IHttpResponse CreateResponse(IHttpClientContext context)
  284. {
  285. return new HttpResponse(context, this);
  286. }
  287. */
  288. /// <summary>
  289. /// Called during parsing of a <see cref="IHttpRequest"/>.
  290. /// </summary>
  291. /// <param name="name">Name of the header, should not be URL encoded</param>
  292. /// <param name="value">Value of the header, should not be URL encoded</param>
  293. /// <exception cref="BadRequestException">If a header is incorrect.</exception>
  294. public void AddHeader(string name, string value)
  295. {
  296. if (string.IsNullOrEmpty(name))
  297. throw new BadRequestException("Invalid header name: " + name ?? "<null>");
  298. if (string.IsNullOrEmpty(value))
  299. throw new BadRequestException("Header '" + name + "' do not contain a value.");
  300. name = name.ToLowerInvariant();
  301. switch (name)
  302. {
  303. case "http_x_requested_with":
  304. case "x-requested-with":
  305. if (string.Compare(value, "XMLHttpRequest", true) == 0)
  306. IsAjax = true;
  307. break;
  308. case "accept":
  309. AcceptTypes = value.Split(',');
  310. for (int i = 0; i < AcceptTypes.Length; ++i)
  311. AcceptTypes[i] = AcceptTypes[i].Trim();
  312. break;
  313. case "content-length":
  314. if (!int.TryParse(value, out int t))
  315. throw new BadRequestException("Invalid content length.");
  316. if (t > MAXCONTENTLENGTH)
  317. throw new OSHttpServer.Exceptions.HttpException(HttpStatusCode.RequestEntityTooLarge,"Request Entity Too Large");
  318. ContentLength = t;
  319. break;
  320. case "host":
  321. try
  322. {
  323. m_uri = new Uri((Secure ? "https://" : "http://") + value + m_uriPath);
  324. m_uriPath = m_uri.AbsolutePath;
  325. }
  326. catch (UriFormatException err)
  327. {
  328. throw new BadRequestException("Failed to parse uri: " + value + m_uriPath, err);
  329. }
  330. break;
  331. case "remote_addr":
  332. if (m_headers[name] == null)
  333. m_headers.Add(name, value);
  334. break;
  335. case "forwarded":
  336. string[] parts = value.Split(Util.SplitSemicolonArray);
  337. string addr = string.Empty;
  338. for(int i = 0; i < parts.Length; ++i)
  339. {
  340. string s = parts[i].TrimStart();
  341. if(s.Length < 10)
  342. continue;
  343. if(s.StartsWith("for", StringComparison.InvariantCultureIgnoreCase))
  344. {
  345. int indx = s.IndexOf("=", 3);
  346. if(indx < 0 || indx >= s.Length - 1)
  347. continue;
  348. s = s[indx..];
  349. addr = s.Trim();
  350. }
  351. }
  352. if(addr.Length > 7)
  353. {
  354. m_headers.Add("x-forwarded-for", addr);
  355. }
  356. break;
  357. case "x-forwarded-for":
  358. if (value.Length > 7)
  359. {
  360. string[] xparts = value.Split(Util.SplitCommaArray);
  361. if(xparts.Length > 0)
  362. {
  363. string xs = xparts[0].Trim();
  364. if(xs.Length > 7)
  365. m_headers.Add("x-forwarded-for", xs);
  366. }
  367. }
  368. break;
  369. case "connection":
  370. if (string.Compare(value, "close", true) == 0)
  371. Connection = ConnectionType.Close;
  372. else if (value.StartsWith("keep-alive", StringComparison.CurrentCultureIgnoreCase))
  373. Connection = ConnectionType.KeepAlive;
  374. else if (value.StartsWith("Upgrade", StringComparison.CurrentCultureIgnoreCase))
  375. Connection = ConnectionType.KeepAlive;
  376. else
  377. throw new BadRequestException("Unknown 'Connection' header type.");
  378. break;
  379. /*
  380. case "expect":
  381. if (value.Contains("100-continue"))
  382. {
  383. }
  384. m_headers.Add(name, value);
  385. break;
  386. case "user-agent":
  387. break;
  388. */
  389. default:
  390. m_headers.Add(name, value);
  391. break;
  392. }
  393. }
  394. /// <summary>
  395. /// Add bytes to the body
  396. /// </summary>
  397. /// <param name="bytes">buffer to read bytes from</param>
  398. /// <param name="offset">where to start read</param>
  399. /// <param name="length">number of bytes to read</param>
  400. /// <returns>Number of bytes actually read (same as length unless we got all body bytes).</returns>
  401. /// <exception cref="InvalidOperationException">If body is not writable</exception>
  402. /// <exception cref="ArgumentNullException"><c>bytes</c> is null.</exception>
  403. /// <exception cref="ArgumentOutOfRangeException"><c>offset</c> is out of range.</exception>
  404. public int AddToBody(byte[] bytes, int offset, int length)
  405. {
  406. if (bytes == null)
  407. throw new ArgumentNullException("bytes");
  408. if (offset + length > bytes.Length)
  409. throw new ArgumentOutOfRangeException("offset");
  410. if (length == 0)
  411. return 0;
  412. if (!m_body.CanWrite)
  413. throw new InvalidOperationException("Body is not writable.");
  414. if (length > m_bodyBytesLeft)
  415. {
  416. length = m_bodyBytesLeft;
  417. }
  418. m_body.Write(bytes, offset, length);
  419. m_bodyBytesLeft -= length;
  420. return length;
  421. }
  422. /// <summary>
  423. /// Clear everything in the request
  424. /// </summary>
  425. public void Clear()
  426. {
  427. if (m_body != null)
  428. {
  429. m_body.Dispose();
  430. m_body = null;
  431. }
  432. m_contentLength = 0;
  433. m_method = string.Empty;
  434. m_uri = null;
  435. m_queryString = null;
  436. m_bodyBytesLeft = 0;
  437. m_headers.Clear();
  438. m_connection = ConnectionType.KeepAlive;
  439. IsAjax = false;
  440. m_context = null;
  441. //_form.Clear();
  442. }
  443. #endregion
  444. }
  445. }