HttpConnection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. //
  2. // System.Net.HttpConnection
  3. //
  4. // Author:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
  8. // Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if SECURITY_DEP
  30. #if MONO_SECURITY_ALIAS
  31. extern alias MonoSecurity;
  32. #endif
  33. #if MONO_SECURITY_ALIAS
  34. using MSI = MonoSecurity::Mono.Security.Interface;
  35. #else
  36. using MSI = Mono.Security.Interface;
  37. #endif
  38. using System.IO;
  39. using System.Net.Sockets;
  40. using System.Text;
  41. using System.Threading;
  42. using System.Security.Authentication;
  43. using System.Security.Cryptography;
  44. using System.Security.Cryptography.X509Certificates;
  45. using Mono.Net.Security;
  46. namespace System.Net {
  47. sealed class HttpConnection
  48. {
  49. static AsyncCallback onread_cb = new AsyncCallback (OnRead);
  50. const int BufferSize = 8192;
  51. Socket sock;
  52. Stream stream;
  53. EndPointListener epl;
  54. MemoryStream ms;
  55. byte [] buffer;
  56. HttpListenerContext context;
  57. StringBuilder current_line;
  58. ListenerPrefix prefix;
  59. RequestStream i_stream;
  60. ResponseStream o_stream;
  61. bool chunked;
  62. int reuses;
  63. bool context_bound;
  64. bool secure;
  65. X509Certificate cert;
  66. int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
  67. Timer timer;
  68. IPEndPoint local_ep;
  69. HttpListener last_listener;
  70. int [] client_cert_errors;
  71. X509Certificate2 client_cert;
  72. IMonoSslStream ssl_stream;
  73. public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate cert)
  74. {
  75. this.sock = sock;
  76. this.epl = epl;
  77. this.secure = secure;
  78. this.cert = cert;
  79. if (secure == false) {
  80. stream = new NetworkStream (sock, false);
  81. } else {
  82. ssl_stream = epl.Listener.CreateSslStream (new NetworkStream (sock, false), false, (t, c, ch, e) => {
  83. if (c == null)
  84. return true;
  85. var c2 = c as X509Certificate2;
  86. if (c2 == null)
  87. c2 = new X509Certificate2 (c.GetRawCertData ());
  88. client_cert = c2;
  89. client_cert_errors = new int[] { (int)e };
  90. return true;
  91. });
  92. stream = ssl_stream.AuthenticatedStream;
  93. }
  94. timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
  95. Init ();
  96. }
  97. internal int [] ClientCertificateErrors {
  98. get { return client_cert_errors; }
  99. }
  100. internal X509Certificate2 ClientCertificate {
  101. get { return client_cert; }
  102. }
  103. void Init ()
  104. {
  105. if (ssl_stream != null) {
  106. ssl_stream.AuthenticateAsServer (cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
  107. }
  108. context_bound = false;
  109. i_stream = null;
  110. o_stream = null;
  111. prefix = null;
  112. chunked = false;
  113. ms = new MemoryStream ();
  114. position = 0;
  115. input_state = InputState.RequestLine;
  116. line_state = LineState.None;
  117. context = new HttpListenerContext (this);
  118. }
  119. public bool IsClosed {
  120. get { return (sock == null); }
  121. }
  122. public int Reuses {
  123. get { return reuses; }
  124. }
  125. public IPEndPoint LocalEndPoint {
  126. get {
  127. if (local_ep != null)
  128. return local_ep;
  129. local_ep = (IPEndPoint) sock.LocalEndPoint;
  130. return local_ep;
  131. }
  132. }
  133. public IPEndPoint RemoteEndPoint {
  134. get { return (IPEndPoint) sock.RemoteEndPoint; }
  135. }
  136. public bool IsSecure {
  137. get { return secure; }
  138. }
  139. public ListenerPrefix Prefix {
  140. get { return prefix; }
  141. set { prefix = value; }
  142. }
  143. void OnTimeout (object unused)
  144. {
  145. CloseSocket ();
  146. Unbind ();
  147. }
  148. public void BeginReadRequest ()
  149. {
  150. if (buffer == null)
  151. buffer = new byte [BufferSize];
  152. try {
  153. if (reuses == 1)
  154. s_timeout = 15000;
  155. timer.Change (s_timeout, Timeout.Infinite);
  156. stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
  157. } catch {
  158. timer.Change (Timeout.Infinite, Timeout.Infinite);
  159. CloseSocket ();
  160. Unbind ();
  161. }
  162. }
  163. public RequestStream GetRequestStream (bool chunked, long contentlength)
  164. {
  165. if (i_stream == null) {
  166. byte [] buffer = ms.GetBuffer ();
  167. int length = (int) ms.Length;
  168. ms = null;
  169. if (chunked) {
  170. this.chunked = true;
  171. context.Response.SendChunked = true;
  172. i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
  173. } else {
  174. i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
  175. }
  176. }
  177. return i_stream;
  178. }
  179. public ResponseStream GetResponseStream ()
  180. {
  181. // TODO: can we get this stream before reading the input?
  182. if (o_stream == null) {
  183. HttpListener listener = context.Listener;
  184. if(listener == null)
  185. return new ResponseStream (stream, context.Response, true);
  186. o_stream = new ResponseStream (stream, context.Response, listener.IgnoreWriteExceptions);
  187. }
  188. return o_stream;
  189. }
  190. static void OnRead (IAsyncResult ares)
  191. {
  192. HttpConnection cnc = (HttpConnection) ares.AsyncState;
  193. cnc.OnReadInternal (ares);
  194. }
  195. void OnReadInternal (IAsyncResult ares)
  196. {
  197. timer.Change (Timeout.Infinite, Timeout.Infinite);
  198. int nread = -1;
  199. try {
  200. nread = stream.EndRead (ares);
  201. ms.Write (buffer, 0, nread);
  202. if (ms.Length > 32768) {
  203. SendError ("Bad request", 400);
  204. Close (true);
  205. return;
  206. }
  207. } catch {
  208. if (ms != null && ms.Length > 0)
  209. SendError ();
  210. if (sock != null) {
  211. CloseSocket ();
  212. Unbind ();
  213. }
  214. return;
  215. }
  216. if (nread == 0) {
  217. //if (ms.Length > 0)
  218. // SendError (); // Why bother?
  219. CloseSocket ();
  220. Unbind ();
  221. return;
  222. }
  223. if (ProcessInput (ms)) {
  224. if (!context.HaveError)
  225. context.Request.FinishInitialization ();
  226. if (context.HaveError) {
  227. SendError ();
  228. Close (true);
  229. return;
  230. }
  231. if (!epl.BindContext (context)) {
  232. SendError ("Invalid host", 400);
  233. Close (true);
  234. return;
  235. }
  236. HttpListener listener = context.Listener;
  237. if (last_listener != listener) {
  238. RemoveConnection ();
  239. listener.AddConnection (this);
  240. last_listener = listener;
  241. }
  242. context_bound = true;
  243. listener.RegisterContext (context);
  244. return;
  245. }
  246. stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
  247. }
  248. void RemoveConnection ()
  249. {
  250. if (last_listener == null)
  251. epl.RemoveConnection (this);
  252. else
  253. last_listener.RemoveConnection (this);
  254. }
  255. enum InputState {
  256. RequestLine,
  257. Headers
  258. }
  259. enum LineState {
  260. None,
  261. CR,
  262. LF
  263. }
  264. InputState input_state = InputState.RequestLine;
  265. LineState line_state = LineState.None;
  266. int position;
  267. // true -> done processing
  268. // false -> need more input
  269. bool ProcessInput (MemoryStream ms)
  270. {
  271. byte [] buffer = ms.GetBuffer ();
  272. int len = (int) ms.Length;
  273. int used = 0;
  274. string line;
  275. while (true) {
  276. if (context.HaveError)
  277. return true;
  278. if (position >= len)
  279. break;
  280. try {
  281. line = ReadLine (buffer, position, len - position, ref used);
  282. position += used;
  283. } catch {
  284. context.ErrorMessage = "Bad request";
  285. context.ErrorStatus = 400;
  286. return true;
  287. }
  288. if (line == null)
  289. break;
  290. if (line == "") {
  291. if (input_state == InputState.RequestLine)
  292. continue;
  293. current_line = null;
  294. ms = null;
  295. return true;
  296. }
  297. if (input_state == InputState.RequestLine) {
  298. context.Request.SetRequestLine (line);
  299. input_state = InputState.Headers;
  300. } else {
  301. try {
  302. context.Request.AddHeader (line);
  303. } catch (Exception e) {
  304. context.ErrorMessage = e.Message;
  305. context.ErrorStatus = 400;
  306. return true;
  307. }
  308. }
  309. }
  310. if (used == len) {
  311. ms.SetLength (0);
  312. position = 0;
  313. }
  314. return false;
  315. }
  316. string ReadLine (byte [] buffer, int offset, int len, ref int used)
  317. {
  318. if (current_line == null)
  319. current_line = new StringBuilder (128);
  320. int last = offset + len;
  321. used = 0;
  322. for (int i = offset; i < last && line_state != LineState.LF; i++) {
  323. used++;
  324. byte b = buffer [i];
  325. if (b == 13) {
  326. line_state = LineState.CR;
  327. } else if (b == 10) {
  328. line_state = LineState.LF;
  329. } else {
  330. current_line.Append ((char) b);
  331. }
  332. }
  333. string result = null;
  334. if (line_state == LineState.LF) {
  335. line_state = LineState.None;
  336. result = current_line.ToString ();
  337. current_line.Length = 0;
  338. }
  339. return result;
  340. }
  341. public void SendError (string msg, int status)
  342. {
  343. try {
  344. HttpListenerResponse response = context.Response;
  345. response.StatusCode = status;
  346. response.ContentType = "text/html";
  347. string description = HttpListenerResponseHelper.GetStatusDescription (status);
  348. string str;
  349. if (msg != null)
  350. str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
  351. else
  352. str = String.Format ("<h1>{0}</h1>", description);
  353. byte [] error = context.Response.ContentEncoding.GetBytes (str);
  354. response.Close (error, false);
  355. } catch {
  356. // response was already closed
  357. }
  358. }
  359. public void SendError ()
  360. {
  361. SendError (context.ErrorMessage, context.ErrorStatus);
  362. }
  363. void Unbind ()
  364. {
  365. if (context_bound) {
  366. epl.UnbindContext (context);
  367. context_bound = false;
  368. }
  369. }
  370. public void Close ()
  371. {
  372. Close (false);
  373. }
  374. void CloseSocket ()
  375. {
  376. if (sock == null)
  377. return;
  378. try {
  379. sock.Close ();
  380. } catch {
  381. } finally {
  382. sock = null;
  383. }
  384. RemoveConnection ();
  385. }
  386. internal void Close (bool force_close)
  387. {
  388. if (sock != null) {
  389. Stream st = GetResponseStream ();
  390. if (st != null)
  391. st.Close ();
  392. o_stream = null;
  393. }
  394. if (sock != null) {
  395. force_close |= !context.Request.KeepAlive;
  396. if (!force_close)
  397. force_close = (context.Response.Headers ["connection"] == "close");
  398. /*
  399. if (!force_close) {
  400. // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
  401. // status_code == 413 || status_code == 414 || status_code == 500 ||
  402. // status_code == 503);
  403. force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
  404. }
  405. */
  406. if (!force_close && context.Request.FlushInput ()) {
  407. if (chunked && context.Response.ForceCloseChunked == false) {
  408. // Don't close. Keep working.
  409. reuses++;
  410. Unbind ();
  411. Init ();
  412. BeginReadRequest ();
  413. return;
  414. }
  415. reuses++;
  416. Unbind ();
  417. Init ();
  418. BeginReadRequest ();
  419. return;
  420. }
  421. Socket s = sock;
  422. sock = null;
  423. try {
  424. if (s != null)
  425. s.Shutdown (SocketShutdown.Both);
  426. } catch {
  427. } finally {
  428. if (s != null)
  429. s.Close ();
  430. }
  431. Unbind ();
  432. RemoveConnection ();
  433. return;
  434. }
  435. }
  436. }
  437. }
  438. #endif