2 // HttpWebRequestTest.cs - NUnit Test Cases for System.Net.HttpWebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Martin Willemoes Hansen (mwh@sysrq.dk)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 // (C) 2003 Martin Willemoes Hansen
10 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com
13 using NUnit.Framework;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Globalization;
20 using System.Net.Sockets;
21 using System.Security.Cryptography;
22 using System.Security.Cryptography.X509Certificates;
24 using System.Threading;
26 using Mono.Security.Authenticode;
27 using Mono.Security.Protocol.Tls;
30 namespace MonoTests.System.Net
33 public class HttpWebRequestTest
36 private Random rand = new Random ();
37 private byte [] data64KB = new byte [64 * 1024];
42 ServicePointManager.Expect100Continue = false;
43 rand.NextBytes (data64KB);
49 [Ignore ("Ignore failures in Sys.Net")]
51 public void Proxy_Null ()
53 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
54 Assert.IsNotNull (req.Proxy, "#1");
57 Assert.IsNull (req.Proxy, "#2");
62 } catch (ArgumentNullException ex) {
63 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#3");
64 Assert.IsNull (ex.InnerException, "#4");
65 Assert.IsNotNull (ex.Message, "#5");
66 Assert.IsNotNull (ex.ParamName, "#6");
67 Assert.AreEqual ("value", ex.ParamName, "#7");
73 [Category("InetAccess")]
75 [Ignore ("NMA - wrong cookies number returned")]
79 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
80 Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
82 req.UserAgent = "MonoClient v1.0";
83 Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
84 Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
86 HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
87 Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
88 Assert.AreEqual ("OK", res.StatusDescription, "#B2");
90 Assert.AreEqual ("text/html; charset=ISO-8859-1", res.Headers.Get ("Content-Type"), "#C1");
91 Assert.IsNotNull (res.LastModified, "#C2");
92 Assert.AreEqual (0, res.Cookies.Count, "#C3");
98 public void AddRange ()
100 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
102 req.AddRange (50, 90);
103 req.AddRange ("bytes", 100);
104 req.AddRange ("bytes", 100, 120);
105 Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
107 req.AddRange ("bits", 2000);
109 } catch (InvalidOperationException) {}
112 [Test] // bug #471782
113 public void CloseRequestStreamAfterReadingResponse ()
115 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9152);
116 string url = "http://" + ep.ToString () + "/test/";
118 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
121 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
124 req.ReadWriteTimeout = 2000;
126 byte [] data = new byte [128];
127 req.ContentLength = data.Length;
129 Stream rs = req.GetRequestStream ();
130 rs.Write (data, 0, data.Length);
133 HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
143 [Category("InetAccess")]
144 public void Cookies1 ()
146 // The purpose of this test is to ensure that the cookies we get from a request
147 // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
148 // in HttpWebRequest.
149 // If this URL stops sending *one* and only one cookie, replace it.
150 string url = "http://www.elmundo.es";
151 CookieContainer cookies = new CookieContainer ();
152 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
153 req.KeepAlive = false;
154 req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
155 req.CookieContainer = cookies;
156 Assert.AreEqual (0, cookies.Count, "#01");
157 using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
158 CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
159 Assert.AreEqual (1, coll.Count, "#02");
160 Assert.AreEqual (1, res.Cookies.Count, "#03");
161 Cookie one = coll [0];
162 Cookie two = res.Cookies [0];
163 Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
167 #if !TARGET_JVM //NotWorking
169 [Ignore ("Fails on MS.NET")]
170 public void SslClientBlock ()
172 // This tests that the write request/initread/write body sequence does not hang
174 // If there's a regression for this, the test will hang.
175 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
177 SslHttpServer server = new SslHttpServer ();
180 string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
181 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
182 request.Method = "POST";
183 Stream stream = request.GetRequestStream ();
184 byte [] bytes = new byte [100];
185 stream.Write (bytes, 0, bytes.Length);
187 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
188 Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
189 StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
194 if (server.Error != null)
197 ServicePointManager.CertificatePolicy = null;
203 [Category("NotWorking")]
205 public void Missing_ContentEncoding ()
207 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
209 BadChunkedServer server = new BadChunkedServer ();
212 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
213 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
214 request.Method = "GET";
215 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
216 Assert.AreEqual ("", resp.ContentEncoding);
219 if (server.Error != null)
222 ServicePointManager.CertificatePolicy = null;
228 [Category ("NotWorking")]
230 public void BadServer_ChunkedClose ()
232 // The server will send a chunked response without a 'last-chunked' mark
233 // and then shutdown the socket for sending.
234 BadChunkedServer server = new BadChunkedServer ();
236 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
237 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
238 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
241 byte [] bytes = new byte [32];
242 // Using StreamReader+UTF8Encoding here fails on MS runtime
243 Stream stream = resp.GetResponseStream ();
244 int nread = stream.Read (bytes, 0, 32);
245 Assert.AreEqual (16, nread, "#01");
246 x = Encoding.ASCII.GetString (bytes, 0, 16);
252 if (server.Error != null)
255 Assert.AreEqual ("1234567890123456", x);
259 [Ignore ("This test asserts that our code violates RFC 2616")]
260 public void MethodCase ()
262 ListDictionary methods = new ListDictionary ();
264 methods.Add ("post", "POST");
265 methods.Add ("puT", "PUT");
267 methods.Add ("post", "post");
268 methods.Add ("puT", "puT");
270 methods.Add ("POST", "POST");
271 methods.Add ("whatever", "whatever");
272 methods.Add ("PUT", "PUT");
274 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9153);
275 string url = "http://" + ep.ToString () + "/test/";
277 foreach (DictionaryEntry de in methods) {
278 SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler));
281 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
282 req.Method = (string) de.Key;
284 req.ReadWriteTimeout = 2000;
285 req.KeepAlive = false;
286 Stream rs = req.GetRequestStream ();
288 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
289 StreamReader sr = new StreamReader (resp.GetResponseStream (),
291 string line = sr.ReadLine ();
293 Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
302 public void BeginGetRequestStream_Body_NotAllowed ()
304 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9154);
305 string url = "http://" + ep.ToString () + "/test/";
307 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
310 HttpWebRequest request;
312 request = (HttpWebRequest) WebRequest.Create (url);
313 request.Method = "GET";
316 request.BeginGetRequestStream (null, null);
318 } catch (ProtocolViolationException ex) {
319 // Cannot send a content-body with this
321 Assert.IsNull (ex.InnerException, "#A2");
322 Assert.IsNotNull (ex.Message, "#A3");
325 request = (HttpWebRequest) WebRequest.Create (url);
326 request.Method = "HEAD";
329 request.BeginGetRequestStream (null, null);
331 } catch (ProtocolViolationException ex) {
332 // Cannot send a content-body with this
334 Assert.IsNull (ex.InnerException, "#B2");
335 Assert.IsNotNull (ex.Message, "#B3");
340 [Test] // bug #465613
341 public void BeginGetRequestStream_NoBuffering ()
343 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 11001);
344 string url = "http://" + ep.ToString () + "/test/";
346 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
353 req = (HttpWebRequest) WebRequest.Create (url);
355 req.SendChunked = false;
356 req.KeepAlive = false;
357 req.AllowWriteStreamBuffering = false;
359 ar = req.BeginGetRequestStream (null, null);
360 rs = req.EndGetRequestStream (ar);
363 req = (HttpWebRequest) WebRequest.Create (url);
365 req.SendChunked = false;
366 req.KeepAlive = true;
367 req.AllowWriteStreamBuffering = false;
370 req.BeginGetRequestStream (null, null);
372 } catch (ProtocolViolationException ex) {
373 // When performing a write operation with
374 // AllowWriteStreamBuffering set to false,
375 // you must either set ContentLength to a
376 // non-negative number or set SendChunked
378 Assert.IsNull (ex.InnerException, "#A2");
379 Assert.IsNotNull (ex.Message, "#A3");
382 req = (HttpWebRequest) WebRequest.Create (url);
384 req.SendChunked = false;
385 req.KeepAlive = true;
386 req.AllowWriteStreamBuffering = false;
387 req.ContentLength = 0;
389 ar = req.BeginGetRequestStream (null, null);
390 rs = req.EndGetRequestStream (ar);
395 [Test] // bug #508027
396 public void BeginGetResponse ()
398 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8001);
399 string url = "http://" + ep.ToString () + "/test/";
401 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
406 req = (HttpWebRequest) WebRequest.Create (url);
408 req.SendChunked = false;
409 req.KeepAlive = false;
410 req.AllowWriteStreamBuffering = false;
411 req.BeginGetResponse (null, null);
414 req = (HttpWebRequest) WebRequest.Create (url);
416 req.SendChunked = true;
417 req.KeepAlive = false;
418 req.AllowWriteStreamBuffering = false;
419 req.BeginGetResponse (null, null);
422 req = (HttpWebRequest) WebRequest.Create (url);
424 req.ContentLength = 5;
425 req.SendChunked = false;
426 req.KeepAlive = false;
427 req.AllowWriteStreamBuffering = false;
428 req.BeginGetResponse (null, null);
431 req = (HttpWebRequest) WebRequest.Create (url);
433 req.SendChunked = false;
434 req.KeepAlive = true;
435 req.AllowWriteStreamBuffering = false;
437 req.BeginGetResponse (null, null);
441 req.BeginGetResponse (null, null);
442 } catch (ProtocolViolationException ex) {
443 // Either ContentLength must be set to a non-negative
444 // number, or SendChunked set to true in order to perform
445 // the write operation when AllowWriteStreamBuffering
447 Assert.IsNull (ex.InnerException, "#A2");
448 Assert.IsNotNull (ex.Message, "#A3");
454 req = (HttpWebRequest) WebRequest.Create (url);
456 req.SendChunked = false;
457 req.KeepAlive = false;
458 req.AllowWriteStreamBuffering = false;
459 req.ContentLength = 5;
460 req.BeginGetResponse (null, null);
463 req = (HttpWebRequest) WebRequest.Create (url);
465 req.SendChunked = false;
466 req.KeepAlive = true;
467 req.AllowWriteStreamBuffering = false;
468 req.ContentLength = 5;
469 req.BeginGetResponse (null, null);
472 req = (HttpWebRequest) WebRequest.Create (url);
474 req.SendChunked = true;
476 req.BeginGetResponse (null, null);
480 req.BeginGetResponse (null, null);
482 } catch (ProtocolViolationException ex) {
483 // Content-Length cannot be set for a
484 // non-write operation
485 Assert.IsNull (ex.InnerException, "#B2");
486 Assert.IsNotNull (ex.Message, "#B3");
492 req = (HttpWebRequest) WebRequest.Create (url);
494 req.ContentLength = 5;
496 req.BeginGetResponse (null, null);
500 req.BeginGetResponse (null, null);
502 } catch (ProtocolViolationException ex) {
503 // Content-Length cannot be set for a
504 // non-write operation
505 Assert.IsNull (ex.InnerException, "#C2");
506 Assert.IsNotNull (ex.Message, "#C3");
512 req = (HttpWebRequest) WebRequest.Create (url);
514 req.ContentLength = 0;
516 req.BeginGetResponse (null, null);
520 req.BeginGetResponse (null, null);
522 } catch (ProtocolViolationException ex) {
523 // Content-Length cannot be set for a
524 // non-write operation
525 Assert.IsNull (ex.InnerException, "#D2");
526 Assert.IsNotNull (ex.Message, "#D3");
534 [Test] // bug #511851
536 [Category ("NotWorking")]
538 public void BeginGetRequestStream_Request_Aborted ()
540 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8002);
541 string url = "http://" + ep.ToString () + "/test/";
543 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
546 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
552 req.BeginGetRequestStream (null, null);
554 } catch (WebException ex) {
555 // The request was aborted: The request was canceled
556 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
557 Assert.IsNull (ex.InnerException, "#3");
558 Assert.IsNotNull (ex.Message, "#4");
559 Assert.IsNull (ex.Response, "#5");
560 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
563 IAsyncResult ar = req.BeginGetRequestStream (null, null);
565 req.EndGetRequestStream (ar);
567 } catch (WebException ex) {
568 // The underlying connection was closed: the request was canceled
569 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
570 Assert.IsNull (ex.InnerException, "#3");
571 Assert.IsNotNull (ex.Message, "#4");
572 Assert.IsNull (ex.Response, "#5");
573 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
579 [Test] // bug #511851
580 public void BeginGetResponse_Request_Aborted ()
582 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9155);
583 string url = "http://" + ep.ToString () + "/test/";
585 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
588 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
593 req.BeginGetResponse (null, null);
595 } catch (WebException ex) {
596 // The request was aborted: The request was canceled
597 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
598 Assert.IsNull (ex.InnerException, "#3");
599 Assert.IsNotNull (ex.Message, "#4");
600 Assert.IsNull (ex.Response, "#5");
601 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
607 public void EndGetRequestStream_AsyncResult_Null ()
609 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9156);
610 string url = "http://" + ep.ToString () + "/test/";
612 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
615 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
617 req.BeginGetRequestStream (null, null);
620 req.EndGetRequestStream (null);
622 } catch (ArgumentNullException ex) {
623 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
624 Assert.IsNull (ex.InnerException, "#3");
625 Assert.IsNotNull (ex.Message, "#4");
626 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
634 [Category ("NotWorking")] // do not get consistent result on MS
635 public void EndGetRequestStream_Request_Aborted ()
637 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8003);
638 string url = "http://" + ep.ToString () + "/test/";
640 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
643 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
645 IAsyncResult ar = req.BeginGetRequestStream (null, null);
650 req.EndGetRequestStream (ar);
652 } catch (WebException ex) {
653 // The request was aborted: The request was canceled
654 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
655 Assert.IsNull (ex.InnerException, "#3");
656 Assert.IsNotNull (ex.Message, "#4");
657 Assert.IsNull (ex.Response, "#5");
658 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
663 [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
664 [Category ("NotWorking")]
665 public void EndGetResponse_AsyncResult_Invalid ()
667 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9157);
668 string url = "http://" + ep.ToString () + "/test/";
670 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
673 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
676 req.ReadWriteTimeout = 2000;
677 IAsyncResult ar = req.BeginGetRequestStream (null, null);
679 // AsyncResult was not returned from call to BeginGetResponse
681 req.EndGetResponse (ar);
683 } catch (InvalidCastException) {
691 public void EndGetResponse_AsyncResult_Null ()
693 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9158);
694 string url = "http://" + ep.ToString () + "/test/";
696 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
699 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
701 req.ReadWriteTimeout = 2000;
703 IAsyncResult ar = req.BeginGetResponse (null, null);
706 req.EndGetResponse (null);
708 } catch (ArgumentNullException ex) {
709 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
710 Assert.IsNull (ex.InnerException, "#3");
711 Assert.IsNotNull (ex.Message, "#4");
712 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
716 using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
723 [Test] // bug #429200
724 public void GetRequestStream ()
726 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10000);
727 string url = "http://" + ep.ToString () + "/test/";
729 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
732 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
735 req.ReadWriteTimeout = 2000;
737 Stream rs1 = req.GetRequestStream ();
738 Stream rs2 = req.GetRequestStream ();
740 Assert.IsNotNull (rs1, "#1");
741 Assert.AreSame (rs1, rs2, "#2");
747 [Test] // bug #511851
748 public void GetRequestStream_Request_Aborted ()
750 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10001);
751 string url = "http://" + ep.ToString () + "/test/";
753 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
756 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
761 req.GetRequestStream ();
763 } catch (WebException ex) {
764 // The request was aborted: The request was canceled
765 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
766 Assert.IsNull (ex.InnerException, "#3");
767 Assert.IsNotNull (ex.Message, "#4");
768 Assert.IsNull (ex.Response, "#5");
769 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
774 [Test] // bug #510661
775 public void GetRequestStream_Close_NotAllBytesWritten ()
777 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10002);
778 string url = "http://" + ep.ToString () + "/test/";
780 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
786 req = (HttpWebRequest) WebRequest.Create (url);
788 req.ContentLength = 2;
789 rs = req.GetRequestStream ();
793 } catch (WebException ex) {
794 // The request was aborted: The request was canceled
795 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
796 Assert.IsNotNull (ex.Message, "#A3");
797 Assert.IsNull (ex.Response, "#A4");
798 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
800 // Cannot close stream until all bytes are written
801 Exception inner = ex.InnerException;
802 Assert.IsNotNull (inner, "#A6");
803 Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
804 Assert.IsNull (inner.InnerException, "#A8");
805 Assert.IsNotNull (inner.Message, "#A9");
808 req = (HttpWebRequest) WebRequest.Create (url);
810 req.ContentLength = 2;
811 rs = req.GetRequestStream ();
816 } catch (WebException ex) {
817 // The request was aborted: The request was canceled
818 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
819 Assert.IsNotNull (ex.Message, "#B3");
820 Assert.IsNull (ex.Response, "#B4");
821 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
823 // Cannot close stream until all bytes are written
824 Exception inner = ex.InnerException;
825 Assert.IsNotNull (inner, "#B6");
826 Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
827 Assert.IsNull (inner.InnerException, "#B8");
828 Assert.IsNotNull (inner.Message, "#B9");
831 req = (HttpWebRequest) WebRequest.Create (url);
833 req.ContentLength = 2;
834 rs = req.GetRequestStream ();
841 [Test] // bug #510642
842 public void GetRequestStream_Write_Overflow ()
844 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8010);
845 string url = "http://" + ep.ToString () + "/test/";
847 // buffered, non-chunked
848 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
855 req = (HttpWebRequest) WebRequest.Create (url);
858 req.ReadWriteTimeout = 2000;
859 req.ContentLength = 2;
861 rs = req.GetRequestStream ();
864 buffer = new byte [] { 0x2a, 0x1d };
866 rs.Write (buffer, 0, buffer.Length);
868 } catch (ProtocolViolationException ex) {
869 // Bytes to be written to the stream exceed
870 // Content-Length bytes size specified
871 Assert.IsNull (ex.InnerException, "#A2");
872 Assert.IsNotNull (ex.Message, "#A3");
877 req = (HttpWebRequest) WebRequest.Create (url);
880 req.ReadWriteTimeout = 2000;
881 req.ContentLength = 2;
883 rs = req.GetRequestStream ();
885 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
887 rs.Write (buffer, 0, buffer.Length);
889 } catch (ProtocolViolationException ex) {
890 // Bytes to be written to the stream exceed
891 // Content-Length bytes size specified
892 Assert.IsNull (ex.InnerException, "#B2");
893 Assert.IsNotNull (ex.Message, "#B3");
900 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
908 req = (HttpWebRequest) WebRequest.Create (url);
910 req.SendChunked = true;
912 req.ReadWriteTimeout = 2000;
913 req.ContentLength = 2;
915 rs = req.GetRequestStream ();
918 buffer = new byte [] { 0x2a, 0x1d };
919 rs.Write (buffer, 0, buffer.Length);
923 req = (HttpWebRequest) WebRequest.Create (url);
925 req.SendChunked = true;
927 req.ReadWriteTimeout = 2000;
928 req.ContentLength = 2;
930 rs = req.GetRequestStream ();
932 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
933 rs.Write (buffer, 0, buffer.Length);
937 // non-buffered, non-chunked
938 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
945 req = (HttpWebRequest) WebRequest.Create (url);
946 req.AllowWriteStreamBuffering = false;
949 req.ReadWriteTimeout = 2000;
950 req.ContentLength = 2;
952 rs = req.GetRequestStream ();
955 buffer = new byte [] { 0x2a, 0x1d };
957 rs.Write (buffer, 0, buffer.Length);
959 } catch (ProtocolViolationException ex) {
960 // Bytes to be written to the stream exceed
961 // Content-Length bytes size specified
962 Assert.IsNull (ex.InnerException, "#C2");
963 Assert.IsNotNull (ex.Message, "#3");
968 req = (HttpWebRequest) WebRequest.Create (url);
969 req.AllowWriteStreamBuffering = false;
972 req.ReadWriteTimeout = 2000;
973 req.ContentLength = 2;
975 rs = req.GetRequestStream ();
977 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
979 rs.Write (buffer, 0, buffer.Length);
981 } catch (ProtocolViolationException ex) {
982 // Bytes to be written to the stream exceed
983 // Content-Length bytes size specified
984 Assert.IsNull (ex.InnerException, "#D2");
985 Assert.IsNotNull (ex.Message, "#D3");
991 // non-buffered, chunked
992 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
999 req = (HttpWebRequest) WebRequest.Create (url);
1000 req.AllowWriteStreamBuffering = false;
1001 req.Method = "POST";
1002 req.SendChunked = true;
1004 req.ReadWriteTimeout = 2000;
1005 req.ContentLength = 2;
1007 rs = req.GetRequestStream ();
1008 rs.WriteByte (0x2c);
1010 buffer = new byte [] { 0x2a, 0x1d };
1011 rs.Write (buffer, 0, buffer.Length);
1014 req = (HttpWebRequest) WebRequest.Create (url);
1015 req.AllowWriteStreamBuffering = false;
1016 req.Method = "POST";
1017 req.SendChunked = true;
1019 req.ReadWriteTimeout = 2000;
1020 req.ContentLength = 2;
1022 rs = req.GetRequestStream ();
1024 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
1025 rs.Write (buffer, 0, buffer.Length);
1031 [Ignore ("This test asserts that our code violates RFC 2616")]
1032 public void GetRequestStream_Body_NotAllowed ()
1034 string [] methods = new string [] { "GET", "HEAD", "CONNECT",
1035 "get", "HeAd", "ConNect" };
1037 foreach (string method in methods) {
1038 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
1039 "http://localhost:8000");
1040 req.Method = method;
1042 req.GetRequestStream ();
1043 Assert.Fail ("#1:" + method);
1044 } catch (ProtocolViolationException ex) {
1045 Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
1046 Assert.IsNull (ex.InnerException, "#3:" + method);
1047 Assert.IsNotNull (ex.Message, "#4:" + method);
1052 [Test] // bug #511851
1053 public void GetResponse_Request_Aborted ()
1055 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10100);
1056 string url = "http://" + ep.ToString () + "/test/";
1058 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
1061 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1062 req.Method = "POST";
1068 } catch (WebException ex) {
1069 // The request was aborted: The request was canceled
1070 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
1071 Assert.IsNull (ex.InnerException, "#3");
1072 Assert.IsNotNull (ex.Message, "#4");
1073 Assert.IsNull (ex.Response, "#5");
1074 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
1081 [Category("NotWorking")]
1083 [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
1084 public void ReadTimeout ()
1086 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
1087 string url = "http://" + localEP.ToString () + "/original/";
1089 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1092 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1093 req.Method = "POST";
1094 req.AllowAutoRedirect = false;
1096 req.ReadWriteTimeout = 2000;
1097 req.KeepAlive = false;
1098 Stream rs = req.GetRequestStream ();
1100 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1102 Stream s = resp.GetResponseStream ();
1105 } catch (WebException ex) {
1106 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
1107 Assert.IsNull (ex.InnerException, "#3");
1108 Assert.IsNull (ex.Response, "#4");
1109 Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
1116 [Test] // bug #324300
1118 [Category("NotWorking")]
1120 public void AllowAutoRedirect ()
1122 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8765);
1123 string url = "http://" + localEP.ToString () + "/original/";
1125 // allow autoredirect
1126 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1129 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1130 req.Method = "POST";
1132 req.ReadWriteTimeout = 2000;
1133 req.KeepAlive = false;
1134 Stream rs = req.GetRequestStream ();
1136 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1137 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1139 string body = sr.ReadToEnd ();
1141 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1142 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1143 localEP.ToString () + "/moved/", "#A2");
1144 Assert.AreEqual ("GET", resp.Method, "#A3");
1145 Assert.AreEqual ("LOOKS OK", body, "#A4");
1150 // do not allow autoredirect
1151 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1154 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1155 req.Method = "POST";
1156 req.AllowAutoRedirect = false;
1158 req.ReadWriteTimeout = 1000;
1159 req.KeepAlive = false;
1160 Stream rs = req.GetRequestStream ();
1162 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1163 Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
1164 Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
1165 Assert.AreEqual ("POST", resp.Method, "#B3");
1172 public void PostAndRedirect_NoCL ()
1174 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8769);
1175 string url = "http://" + localEP.ToString () + "/original/";
1177 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1180 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1181 req.Method = "POST";
1183 req.ReadWriteTimeout = 2000;
1184 Stream rs = req.GetRequestStream ();
1187 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1188 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1190 string body = sr.ReadToEnd ();
1192 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1193 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1194 localEP.ToString () + "/moved/", "#A2");
1195 Assert.AreEqual ("GET", resp.Method, "#A3");
1196 Assert.AreEqual ("LOOKS OK", body, "#A4");
1203 public void PostAndRedirect_CL ()
1205 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8770);
1206 string url = "http://" + localEP.ToString () + "/original/";
1208 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1211 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1212 req.Method = "POST";
1214 req.ReadWriteTimeout = 2000;
1215 req.ContentLength = 1;
1216 Stream rs = req.GetRequestStream ();
1218 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1219 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1221 string body = sr.ReadToEnd ();
1223 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1224 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1225 localEP.ToString () + "/moved/", "#A2");
1226 Assert.AreEqual ("GET", resp.Method, "#A3");
1227 Assert.AreEqual ("LOOKS OK", body, "#A4");
1234 public void PostAnd401 ()
1236 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8771);
1237 string url = "http://" + localEP.ToString () + "/original/";
1239 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1242 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1243 req.Method = "POST";
1245 req.ReadWriteTimeout = 2000;
1246 req.ContentLength = 1;
1247 Stream rs = req.GetRequestStream ();
1249 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1250 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1252 string body = sr.ReadToEnd ();
1254 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1255 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1256 localEP.ToString () + "/moved/", "#A2");
1257 Assert.AreEqual ("GET", resp.Method, "#A3");
1258 Assert.AreEqual ("LOOKS OK", body, "#A4");
1264 [Test] // bug #324347
1265 [Category ("NotWorking")]
1266 public void InternalServerError ()
1268 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8766);
1269 string url = "http://" + localEP.ToString () + "/original/";
1272 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1275 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1276 req.Method = "POST";
1278 req.ReadWriteTimeout = 2000;
1279 req.KeepAlive = false;
1280 Stream rs = req.GetRequestStream ();
1285 Assert.Fail ("#A1");
1286 } catch (WebException ex) {
1287 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1288 Assert.IsNull (ex.InnerException, "#A3");
1289 Assert.IsNotNull (ex.Message, "#A4");
1290 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
1292 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1293 Assert.IsNotNull (webResponse, "#A6");
1294 Assert.AreEqual ("POST", webResponse.Method, "#A7");
1295 webResponse.Close ();
1302 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1305 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1308 req.ReadWriteTimeout = 2000;
1309 req.KeepAlive = false;
1313 Assert.Fail ("#B1");
1314 } catch (WebException ex) {
1315 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1316 Assert.IsNull (ex.InnerException, "#B3");
1317 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1319 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1320 Assert.IsNotNull (webResponse, "#B5");
1321 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1322 webResponse.Close ();
1330 [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
1331 public void NoContentLength ()
1333 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8767);
1334 string url = "http://" + localEP.ToString () + "/original/";
1337 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1340 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1341 req.Method = "POST";
1343 req.ReadWriteTimeout = 2000;
1344 req.KeepAlive = false;
1345 Stream rs = req.GetRequestStream ();
1350 Assert.Fail ("#A1");
1351 } catch (WebException ex) {
1353 // The underlying connection was closed:
1354 // An unexpected error occurred on a
1356 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1357 Assert.IsNotNull (ex.InnerException, "#A3");
1358 Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
1359 Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
1361 // Unable to read data from the transport connection:
1362 // A connection attempt failed because the connected party
1363 // did not properly respond after a period of time, or
1364 // established connection failed because connected host has
1365 // failed to respond
1366 IOException ioe = (IOException) ex.InnerException;
1367 Assert.IsNotNull (ioe.InnerException, "#A6");
1368 Assert.IsNotNull (ioe.Message, "#A7");
1369 Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
1371 // An existing connection was forcibly
1372 // closed by the remote host
1373 SocketException soe = (SocketException) ioe.InnerException;
1374 Assert.IsNull (soe.InnerException, "#A9");
1375 Assert.IsNotNull (soe.Message, "#A10");
1377 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1378 Assert.IsNull (webResponse, "#A11");
1380 // The remote server returned an error:
1381 // (500) Internal Server Error
1382 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1383 Assert.IsNull (ex.InnerException, "#A3");
1384 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A4");
1386 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1387 Assert.IsNotNull (webResponse, "#A5");
1388 Assert.AreEqual ("POST", webResponse.Method, "#A6");
1389 webResponse.Close ();
1397 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1400 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1403 req.ReadWriteTimeout = 2000;
1404 req.KeepAlive = false;
1408 Assert.Fail ("#B1");
1409 } catch (WebException ex) {
1410 // The remote server returned an error:
1411 // (500) Internal Server Error
1412 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1413 Assert.IsNull (ex.InnerException, "#B3");
1414 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1416 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1417 Assert.IsNotNull (webResponse, "#B5");
1418 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1419 webResponse.Close ();
1426 [Test] // bug #513087
1427 public void NonStandardVerb ()
1429 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8123);
1430 string url = "http://" + ep.ToString () + "/moved/";
1432 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (VerbEchoHandler))) {
1435 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1436 req.Method = "WhatEver";
1437 req.KeepAlive = false;
1438 req.Timeout = 20000;
1439 req.ReadWriteTimeout = 20000;
1441 Stream rs = req.GetRequestStream ();
1444 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1445 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1447 string body = sr.ReadToEnd ();
1449 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
1450 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1451 ep.ToString () + "/moved/", "#2");
1452 Assert.AreEqual ("WhatEver", resp.Method, "#3");
1453 Assert.AreEqual ("WhatEver", body, "#4");
1461 [Category ("NotWorking")] // Assert #2 fails
1462 public void NotModifiedSince ()
1464 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9123);
1465 string url = "http://" + ep.ToString () + "/test/";
1467 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (NotModifiedSinceHandler))) {
1470 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1472 req.KeepAlive = false;
1473 req.Timeout = 20000;
1474 req.ReadWriteTimeout = 20000;
1476 req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
1478 req.Headers.Add ("If-None-Match", "898bbr2347056cc2e096afc66e104653");
1480 req.IfModifiedSince = new DateTime (2010, 01, 04);
1482 DateTime start = DateTime.Now;
1483 HttpWebResponse response = null;
1488 } catch (WebException e) {
1489 response = (HttpWebResponse) e.Response;
1492 Assert.IsNotNull (response, "#2");
1493 using (Stream stream = response.GetResponseStream ()) {
1494 byte [] buffer = new byte [4096];
1495 int bytesRead = stream.Read (buffer, 0, buffer.Length);
1496 Assert.AreEqual (0, bytesRead, "#3");
1499 TimeSpan elapsed = DateTime.Now - start;
1500 Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
1506 [Test] // bug #353495
1507 [Category ("NotWorking")]
1508 public void LastModifiedKind ()
1510 const string reqURL = "http://coffeefaq.com/site/node/25";
1511 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
1512 HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
1513 DateTime lastMod = resp.LastModified;
1514 //string rawLastMod = resp.Headers ["Last-Modified"];
1516 //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
1518 Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
1520 req = (HttpWebRequest) WebRequest.Create (reqURL);
1521 req.IfModifiedSince = lastMod;
1523 resp = (HttpWebResponse) req.GetResponse ();
1525 Assert.Fail ("Should result in 304");
1526 } catch (WebException ex) {
1527 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
1528 Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
1532 internal static byte [] EchoRequestHandler (Socket socket)
1534 MemoryStream ms = new MemoryStream ();
1535 byte [] buffer = new byte [4096];
1536 int bytesReceived = socket.Receive (buffer);
1537 while (bytesReceived > 0) {
1538 ms.Write (buffer, 0, bytesReceived);
1539 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1540 // after sending the headers
1542 if (socket.Available > 0) {
1543 bytesReceived = socket.Receive (buffer);
1550 StreamReader sr = new StreamReader (ms, Encoding.UTF8);
1551 string request = sr.ReadToEnd ();
1553 StringWriter sw = new StringWriter ();
1554 sw.WriteLine ("HTTP/1.1 200 OK");
1555 sw.WriteLine ("Content-Type: text/xml");
1556 sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
1561 return Encoding.UTF8.GetBytes (sw.ToString ());
1564 static byte [] RedirectRequestHandler (Socket socket)
1566 MemoryStream ms = new MemoryStream ();
1567 byte [] buffer = new byte [4096];
1568 int bytesReceived = socket.Receive (buffer);
1569 while (bytesReceived > 0) {
1570 ms.Write (buffer, 0, bytesReceived);
1571 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1572 // after sending the headers
1574 if (socket.Available > 0) {
1575 bytesReceived = socket.Receive (buffer);
1582 string statusLine = null;
1583 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1584 statusLine = sr.ReadLine ();
1587 StringWriter sw = new StringWriter ();
1588 if (statusLine.StartsWith ("POST /original/")) {
1589 sw.WriteLine ("HTTP/1.0 302 Found");
1590 EndPoint ep = socket.LocalEndPoint;
1591 sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
1594 } else if (statusLine.StartsWith ("GET /moved/")) {
1595 sw.WriteLine ("HTTP/1.0 200 OK");
1596 sw.WriteLine ("Content-Type: text/plain");
1597 sw.WriteLine ("Content-Length: 8");
1599 sw.Write ("LOOKS OK");
1602 sw.WriteLine ("HTTP/1.0 500 Too Lazy");
1607 return Encoding.UTF8.GetBytes (sw.ToString ());
1610 static byte [] InternalErrorHandler (Socket socket)
1612 byte [] buffer = new byte [4096];
1613 int bytesReceived = socket.Receive (buffer);
1614 while (bytesReceived > 0) {
1615 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1616 // after sending the headers
1618 if (socket.Available > 0) {
1619 bytesReceived = socket.Receive (buffer);
1624 StringWriter sw = new StringWriter ();
1625 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1626 sw.WriteLine ("Content-Length: 0");
1630 return Encoding.UTF8.GetBytes (sw.ToString ());
1633 static byte [] NoContentLengthHandler (Socket socket)
1635 StringWriter sw = new StringWriter ();
1636 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1640 return Encoding.UTF8.GetBytes (sw.ToString ());
1643 static byte [] NotModifiedSinceHandler (Socket socket)
1645 StringWriter sw = new StringWriter ();
1646 sw.WriteLine ("HTTP/1.1 304 Not Modified");
1647 sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
1648 sw.WriteLine ("Server: Apache/2.2.6 (Debian) PHP/5.2.6-2+b1 with Suhosin-Patch mod_ssl/2.2.6 OpenSSL/0.9.8g");
1649 sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
1650 sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
1651 sw.WriteLine ("Connection: close");
1655 return Encoding.UTF8.GetBytes (sw.ToString ());
1658 static byte [] VerbEchoHandler (Socket socket)
1660 MemoryStream ms = new MemoryStream ();
1661 byte [] buffer = new byte [4096];
1662 int bytesReceived = socket.Receive (buffer);
1663 while (bytesReceived > 0) {
1664 ms.Write (buffer, 0, bytesReceived);
1665 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1666 // after sending the headers
1668 if (socket.Available > 0) {
1669 bytesReceived = socket.Receive (buffer);
1676 string statusLine = null;
1677 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1678 statusLine = sr.ReadLine ();
1681 string verb = "DEFAULT";
1682 if (statusLine != null) {
1683 string [] parts = statusLine.Split (' ');
1684 if (parts.Length > 0)
1688 StringWriter sw = new StringWriter ();
1689 sw.WriteLine ("HTTP/1.1 200 OK");
1690 sw.WriteLine ("Content-Type: text/plain");
1691 sw.WriteLine ("Content-Length: " + verb.Length);
1696 return Encoding.UTF8.GetBytes (sw.ToString ());
1699 static byte [] PostAnd401Handler (Socket socket)
1701 MemoryStream ms = new MemoryStream ();
1702 byte [] buffer = new byte [4096];
1703 int bytesReceived = socket.Receive (buffer);
1704 while (bytesReceived > 0) {
1705 ms.Write (buffer, 0, bytesReceived);
1706 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1707 // after sending the headers
1709 if (socket.Available > 0) {
1710 bytesReceived = socket.Receive (buffer);
1717 string statusLine = null;
1718 bool have_auth = false;
1720 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1722 while ((l = sr.ReadLine ()) != null) {
1723 if (statusLine == null) {
1725 } else if (l.StartsWith ("Authorization:")) {
1727 } else if (l.StartsWith ("Content-Length:")) {
1728 cl = Int32.Parse (l.Substring ("content-length: ".Length));
1733 StringWriter sw = new StringWriter ();
1735 sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
1736 sw.WriteLine ("WWW-Authenticate: basic Yeah");
1739 } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
1740 sw.WriteLine ("HTTP/1.0 200 OK");
1741 sw.WriteLine ("Content-Type: text/plain");
1742 sw.WriteLine ("Content-Length: 8");
1744 sw.Write ("LOOKS OK");
1747 sw.WriteLine ("HTTP/1.0 500 test failed");
1748 sw.WriteLine ("Content-Length: 0");
1753 return Encoding.UTF8.GetBytes (sw.ToString ());
1756 public void NtlmAuthentication ()
1758 NtlmServer server = new NtlmServer ();
1761 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
1762 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
1763 request.Timeout = 5000;
1764 request.Credentials = new NetworkCredential ("user", "password", "domain");
1765 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
1767 using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
1768 res = reader.ReadToEnd ();
1772 Assert.AreEqual ("OK", res);
1775 class NtlmServer : HttpServer {
1776 public string Where = "";
1777 protected override void Run ()
1779 Where = "before accept";
1780 Socket client = sock.Accept ();
1781 NetworkStream ns = new NetworkStream (client, false);
1782 StreamReader reader = new StreamReader (ns, Encoding.ASCII);
1784 Where = "first read";
1785 while ((line = reader.ReadLine ()) != null) {
1786 if (line.Trim () == String.Empty) {
1790 Where = "first write";
1791 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1792 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1793 "WWW-Authenticate: NTLM\r\n" +
1794 "Content-Length: 5\r\n\r\nWRONG");
1797 Where = "second read";
1798 while ((line = reader.ReadLine ()) != null) {
1799 if (line.Trim () == String.Empty) {
1803 Where = "second write";
1804 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1805 "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
1806 "Content-Length: 5\r\n\r\nWRONG");
1809 Where = "third read";
1810 while ((line = reader.ReadLine ()) != null) {
1811 if (line.Trim () == String.Empty) {
1815 Where = "third write";
1816 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1817 "Keep-Alive: true\r\n" +
1818 "Content-Length: 2\r\n\r\nOK");
1820 Thread.Sleep (1000);
1827 class BadChunkedServer : HttpServer {
1828 protected override void Run ()
1830 Socket client = sock.Accept ();
1831 NetworkStream ns = new NetworkStream (client, true);
1832 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1833 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1834 "Transfer-Encoding: chunked\r\n" +
1835 "Connection: close\r\n" +
1836 "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
1838 // This body lacks a 'last-chunk' (see RFC 2616)
1839 writer.Write ("10\r\n1234567890123456\r\n");
1841 client.Shutdown (SocketShutdown.Send);
1842 Thread.Sleep (1000);
1847 class AcceptAllPolicy : ICertificatePolicy {
1848 public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
1854 abstract class HttpServer
1856 protected Socket sock;
1857 protected Exception error;
1858 protected ManualResetEvent evt;
1860 public HttpServer ()
1862 sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
1863 sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
1867 public void Start ()
1869 evt = new ManualResetEvent (false);
1870 Thread th = new Thread (new ThreadStart (Run));
1880 public IPAddress IPAddress {
1881 get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
1885 get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
1888 public Exception Error {
1889 get { return error; }
1892 protected abstract void Run ();
1897 public void BeginGetRequestStream ()
1903 r.ContentLength = 0;
1904 r.BeginGetRequestStream ((a) =>
1906 using (Stream s = r.EndGetRequestStream (a)) { };
1915 public void BeginGetRequestStreamNoClose ()
1920 r.ContentLength = 1;
1921 r.BeginGetRequestStream ((a) =>
1923 r.EndGetRequestStream (a);
1932 public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
1938 r.ContentLength = 10;
1939 r.BeginGetRequestStream ((a) =>
1941 WebException ex = ExceptionAssert.Throws<WebException> (() =>
1943 using (Stream s = r.EndGetRequestStream (a)) {
1947 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1956 public void GetRequestStream2 ()
1962 r.ContentLength = data64KB.Length;
1963 using (Stream s = r.GetRequestStream ()) {
1964 s.Write (data64KB, 0, data64KB.Length);
1972 public void GetRequestStreamNotAllBytesWritten ()
1978 r.ContentLength = data64KB.Length;
1979 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
1980 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1987 public void GetRequestStreamTimeout ()
1993 r.ContentLength = data64KB.Length;
1995 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
1996 Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
2002 public void BeginWrite ()
2004 byte[] received = new byte[data64KB.Length];
2010 r.ContentLength = data64KB.Length;
2012 Stream s = r.GetRequestStream ();
2013 s.BeginWrite (data64KB, 0, data64KB.Length,
2018 r.GetResponse ().Close ();
2025 c.Request.InputStream.ReadAll (received, 0, received.Length);
2026 c.Response.StatusCode = 204;
2027 c.Response.Close ();
2030 Assert.AreEqual (data64KB, received);
2034 public void BeginWriteAfterAbort ()
2036 byte [] received = new byte [data64KB.Length];
2042 r.ContentLength = data64KB.Length;
2044 Stream s = r.GetRequestStream ();
2047 WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
2048 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2054 c.Request.InputStream.ReadAll (received, 0, received.Length);
2055 c.Response.StatusCode = 204;
2061 public void PrematureStreamCloseAborts ()
2063 byte [] received = new byte [data64KB.Length];
2069 r.ContentLength = data64KB.Length * 2;
2071 Stream s = r.GetRequestStream ();
2072 s.Write (data64KB, 0, data64KB.Length);
2074 WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
2075 Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
2081 c.Request.InputStream.ReadAll (received, 0, received.Length);
2082 c.Response.StatusCode = 204;
2083 c.Response.Close ();
2088 public void Write ()
2090 byte [] received = new byte [data64KB.Length];
2096 r.ContentLength = data64KB.Length;
2098 using (Stream s = r.GetRequestStream ()) {
2099 s.Write (data64KB, 0, data64KB.Length);
2102 r.GetResponse ().Close ();
2107 c.Request.InputStream.ReadAll (received, 0, received.Length);
2108 c.Response.StatusCode = 204;
2109 c.Response.Close ();
2112 Assert.AreEqual(data64KB, received);
2116 [Category("NotWorking")]
2117 public void WriteServerAborts ()
2119 ManualResetEvent abort = new ManualResetEvent (false);
2120 byte [] received = new byte [data64KB.Length];
2126 r.ContentLength = data64KB.Length;
2128 using (Stream s = r.GetRequestStream()) {
2131 IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
2146 byte [] received = new byte [data64KB.Length];
2151 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2152 using (Stream s = x.GetResponseStream()) {
2153 s.ReadAll (received, 0, received.Length);
2160 c.Response.StatusCode = 200;
2161 c.Response.ContentLength64 = data64KB.Length;
2162 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2163 c.Response.OutputStream.Close ();
2164 c.Response.Close ();
2167 Assert.AreEqual (data64KB, received);
2171 public void ReadTimeout2 ()
2173 byte [] received = new byte [data64KB.Length];
2178 r.ReadWriteTimeout = 10;
2179 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2180 using (Stream s = x.GetResponseStream ()) {
2181 WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
2182 Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
2189 c.Response.StatusCode = 200;
2190 c.Response.ContentLength64 = data64KB.Length;
2191 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
2192 Thread.Sleep (1000);
2193 c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
2194 c.Response.OutputStream.Close ();
2195 c.Response.Close ();
2200 public void ReadServerAborted ()
2202 byte [] received = new byte [data64KB.Length];
2207 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2208 using (Stream s = x.GetResponseStream ()) {
2209 Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
2216 c.Response.StatusCode = 200;
2217 c.Response.ContentLength64 = data64KB.Length;
2218 c.Response.OutputStream.Write (data64KB, 0, 1);
2219 c.Response.Abort ();
2224 public void BeginGetResponse2 ()
2226 byte [] received = new byte [data64KB.Length];
2231 r.BeginGetResponse ((a) =>
2233 using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
2234 using (Stream s = x.GetResponseStream ()) {
2235 s.ReadAll (received, 0, received.Length);
2243 c.Response.StatusCode = 200;
2244 c.Response.ContentLength64 = data64KB.Length;
2245 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2246 c.Response.OutputStream.Close ();
2247 c.Response.Close ();
2250 Assert.AreEqual (data64KB, received);
2254 public void BeginGetResponseAborts ()
2256 ManualResetEvent aborted = new ManualResetEvent(false);
2261 r.BeginGetResponse((a) =>
2263 WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
2264 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2275 c.Response.StatusCode = 200;
2276 c.Response.ContentLength64 = 0;
2277 c.Response.Close ();
2281 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
2283 int port = rand.Next (20000, 65535);
2285 ManualResetEvent completed = new ManualResetEvent (false);
2286 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2287 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2289 request (client, completed);
2291 if (!completed.WaitOne (10000))
2292 Assert.Fail ("Test hung");
2295 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
2297 int port = rand.Next (20000, 65535);
2299 ManualResetEvent [] completed = new ManualResetEvent [2];
2300 completed [0] = new ManualResetEvent (false);
2301 completed [1] = new ManualResetEvent (false);
2303 using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
2304 ManualResetEvent clientCompleted = new ManualResetEvent (false);
2305 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2306 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2308 ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
2310 if (!WaitHandle.WaitAll (completed, 10000))
2311 Assert.Fail ("Test hung.");
2315 class ListenerScope : IDisposable {
2316 EventWaitHandle completed;
2317 public HttpListener listener;
2318 Action<HttpListenerContext> processor;
2320 public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
2322 this.processor = processor;
2323 this.completed = completed;
2325 this.listener = new HttpListener ();
2326 this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
2327 this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
2328 this.listener.Start ();
2330 this.listener.BeginGetContext (this.RequestHandler, null);
2333 void RequestHandler (IAsyncResult result)
2335 HttpListenerContext context = null;
2338 context = this.listener.EndGetContext (result);
2339 } catch (HttpListenerException ex) {
2340 // check if the thread has been aborted as in the case when we are shutting down.
2341 if (ex.ErrorCode == 995)
2343 } catch (ObjectDisposedException) {
2347 ThreadPool.QueueUserWorkItem ((o) =>
2350 this.processor (context);
2351 } catch (HttpListenerException) {
2355 this.completed.Set ();
2358 public void Dispose ()
2360 this.listener.Stop ();
2366 class SslHttpServer : HttpServer {
2367 X509Certificate _certificate;
2369 protected override void Run ()
2372 Socket client = sock.Accept ();
2373 NetworkStream ns = new NetworkStream (client, true);
2374 SslServerStream s = new SslServerStream (ns, Certificate, false, false);
2375 s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
2377 StreamReader reader = new StreamReader (s);
2378 StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
2381 string hello = "<html><body><h1>Hello World!</h1></body></html>";
2382 string answer = "HTTP/1.0 200\r\n" +
2383 "Connection: close\r\n" +
2384 "Content-Type: text/html\r\n" +
2385 "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
2386 "Content-Length: " + hello.Length + "\r\n" +
2391 line = reader.ReadLine ();
2392 } while (line != "" && line != null && line.Length > 0);
2394 // Now the content. We know it's 100 bytes.
2395 // This makes BeginRead in sslclientstream block.
2396 char [] cs = new char [100];
2397 reader.Read (cs, 0, 100);
2399 writer.Write (answer);
2401 if (evt.WaitOne (5000, false))
2402 error = new Exception ("Timeout when stopping the server");
2403 } catch (Exception e) {
2408 X509Certificate Certificate {
2410 if (_certificate == null)
2411 _certificate = new X509Certificate (CertData.Certificate);
2413 return _certificate;
2417 AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
2419 PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
2425 public readonly static byte [] Certificate = {
2426 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
2427 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
2428 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
2429 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
2430 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
2431 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
2432 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
2433 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
2434 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
2435 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
2436 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
2437 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
2438 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
2439 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
2440 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
2441 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
2442 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
2443 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
2444 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
2445 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
2446 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
2447 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
2448 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
2449 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
2450 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
2451 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
2452 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
2453 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
2457 public readonly static byte [] PrivateKey = {
2458 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
2459 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
2460 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
2461 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
2462 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
2463 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
2464 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
2465 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
2466 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
2467 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
2468 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
2469 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
2470 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
2471 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
2472 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
2473 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
2474 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
2475 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
2476 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
2477 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
2478 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
2479 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
2480 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
2481 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
2482 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
2483 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
2484 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
2485 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
2486 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
2487 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
2488 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
2489 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
2490 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
2491 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
2492 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
2493 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
2494 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
2495 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
2496 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
2503 public class HttpRequestStreamTest
2506 public void BeginRead ()
2508 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9124);
2509 string url = "http://" + ep.ToString () + "/test/";
2511 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2514 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2515 req.Method = "POST";
2517 using (Stream rs = req.GetRequestStream ()) {
2518 byte [] buffer = new byte [10];
2520 rs.BeginRead (buffer, 0, buffer.Length, null, null);
2522 } catch (NotSupportedException ex) {
2523 // The stream does not support reading
2524 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2525 Assert.IsNull (ex.InnerException, "#3");
2526 Assert.IsNotNull (ex.Message, "#4");
2535 public void BeginWrite_Request_Aborted ()
2537 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9125);
2538 string url = "http://" + ep.ToString () + "/test/";
2540 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2543 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2544 req.Method = "POST";
2546 using (Stream rs = req.GetRequestStream ()) {
2549 rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
2551 } catch (WebException ex) {
2552 // The request was aborted: The request was canceled
2553 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2554 Assert.IsNull (ex.InnerException, "#3");
2555 Assert.IsNotNull (ex.Message, "#4");
2556 Assert.IsNull (ex.Response, "#5");
2557 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2564 public void CanRead ()
2566 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9126);
2567 string url = "http://" + ep.ToString () + "/test/";
2569 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2572 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2573 req.Method = "POST";
2575 Stream rs = req.GetRequestStream ();
2577 Assert.IsFalse (rs.CanRead, "#1");
2579 Assert.IsFalse (rs.CanRead, "#2");
2588 public void CanSeek ()
2590 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9127);
2591 string url = "http://" + ep.ToString () + "/test/";
2593 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2596 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2597 req.Method = "POST";
2599 Stream rs = req.GetRequestStream ();
2601 Assert.IsFalse (rs.CanSeek, "#1");
2603 Assert.IsFalse (rs.CanSeek, "#2");
2612 [Test] // bug #324182
2614 [Category ("NotWorking")]
2616 public void CanTimeout ()
2618 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9128);
2619 string url = "http://" + ep.ToString () + "/test/";
2621 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2624 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2625 req.Method = "POST";
2627 Stream rs = req.GetRequestStream ();
2629 Assert.IsTrue (rs.CanTimeout, "#1");
2631 Assert.IsTrue (rs.CanTimeout, "#2");
2641 public void CanWrite ()
2643 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9129);
2644 string url = "http://" + ep.ToString () + "/test/";
2646 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2649 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2650 req.Method = "POST";
2652 Stream rs = req.GetRequestStream ();
2654 Assert.IsTrue (rs.CanWrite, "#1");
2656 Assert.IsFalse (rs.CanWrite, "#2");
2667 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9130);
2668 string url = "http://" + ep.ToString () + "/test/";
2670 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2673 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2674 req.Method = "POST";
2676 using (Stream rs = req.GetRequestStream ()) {
2677 byte [] buffer = new byte [10];
2679 rs.Read (buffer, 0, buffer.Length);
2681 } catch (NotSupportedException ex) {
2682 // The stream does not support reading
2683 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2684 Assert.IsNull (ex.InnerException, "#3");
2685 Assert.IsNotNull (ex.Message, "#4");
2694 public void ReadByte ()
2696 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9140);
2697 string url = "http://" + ep.ToString () + "/test/";
2699 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2702 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2703 req.Method = "POST";
2705 using (Stream rs = req.GetRequestStream ()) {
2709 } catch (NotSupportedException ex) {
2710 // The stream does not support reading
2711 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2712 Assert.IsNull (ex.InnerException, "#3");
2713 Assert.IsNotNull (ex.Message, "#4");
2723 public void ReadTimeout ()
2725 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9141);
2726 string url = "http://" + ep.ToString () + "/test/";
2728 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2731 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2732 req.Method = "POST";
2734 Stream rs = req.GetRequestStream ();
2736 Assert.AreEqual (300000, rs.ReadTimeout, "#1");
2738 Assert.AreEqual (300000, rs.ReadTimeout, "#2");
2750 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9142);
2751 string url = "http://" + ep.ToString () + "/test/";
2753 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2756 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2757 req.Method = "POST";
2759 using (Stream rs = req.GetRequestStream ()) {
2761 rs.Seek (0, SeekOrigin.Current);
2763 } catch (NotSupportedException ex) {
2764 // This stream does not support seek operations
2765 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2766 Assert.IsNull (ex.InnerException, "#3");
2767 Assert.IsNotNull (ex.Message, "#4");
2776 public void Write_Buffer_Null ()
2778 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9143);
2779 string url = "http://" + ep.ToString () + "/test/";
2781 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2784 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2785 req.Method = "POST";
2787 using (Stream rs = req.GetRequestStream ()) {
2789 rs.Write ((byte []) null, -1, -1);
2791 } catch (ArgumentNullException ex) {
2792 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2793 Assert.IsNull (ex.InnerException, "#3");
2794 Assert.IsNotNull (ex.Message, "#4");
2795 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2804 public void Write_Count_Negative ()
2806 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9144);
2807 string url = "http://" + ep.ToString () + "/test/";
2809 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2812 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2813 req.Method = "POST";
2815 using (Stream rs = req.GetRequestStream ()) {
2816 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2818 rs.Write (buffer, 1, -1);
2820 } catch (ArgumentOutOfRangeException ex) {
2821 // Specified argument was out of the range of valid values
2822 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
2823 Assert.IsNull (ex.InnerException, "#A3");
2824 Assert.IsNotNull (ex.Message, "#A4");
2825 Assert.AreEqual ("size", ex.ParamName, "#A5");
2834 public void Write_Count_Overflow ()
2836 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9145);
2837 string url = "http://" + ep.ToString () + "/test/";
2839 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2842 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2843 req.Method = "POST";
2845 using (Stream rs = req.GetRequestStream ()) {
2846 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2848 rs.Write (buffer, buffer.Length - 2, 3);
2850 } catch (ArgumentOutOfRangeException ex) {
2851 // Specified argument was out of the range of valid values
2852 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
2853 Assert.IsNull (ex.InnerException, "#3");
2854 Assert.IsNotNull (ex.Message, "#4");
2855 Assert.AreEqual ("size", ex.ParamName, "#5");
2864 public void Write_Offset_Negative ()
2866 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9146);
2867 string url = "http://" + ep.ToString () + "/test/";
2869 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2872 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2873 req.Method = "POST";
2875 using (Stream rs = req.GetRequestStream ()) {
2876 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2878 rs.Write (buffer, -1, 0);
2880 } catch (ArgumentOutOfRangeException ex) {
2881 // Specified argument was out of the range of valid values
2882 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
2883 Assert.IsNull (ex.InnerException, "#3");
2884 Assert.IsNotNull (ex.Message, "#4");
2885 Assert.AreEqual ("offset", ex.ParamName, "#5");
2894 public void Write_Offset_Overflow ()
2896 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9147);
2897 string url = "http://" + ep.ToString () + "/test/";
2899 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2902 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2903 req.Method = "POST";
2905 using (Stream rs = req.GetRequestStream ()) {
2906 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2908 rs.Write (buffer, buffer.Length + 1, 0);
2910 } catch (ArgumentOutOfRangeException ex) {
2911 // Specified argument was out of the range of valid values
2912 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
2913 Assert.IsNull (ex.InnerException, "#3");
2914 Assert.IsNotNull (ex.Message, "#4");
2915 Assert.AreEqual ("offset", ex.ParamName, "#5");
2924 public void Write_Request_Aborted ()
2926 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9148);
2927 string url = "http://" + ep.ToString () + "/test/";
2929 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2932 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2933 req.Method = "POST";
2935 using (Stream rs = req.GetRequestStream ()) {
2938 rs.Write (new byte [0], 0, 0);
2940 } catch (WebException ex) {
2941 // The request was aborted: The request was canceled
2942 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2943 Assert.IsNull (ex.InnerException, "#3");
2944 Assert.IsNotNull (ex.Message, "#4");
2945 Assert.IsNull (ex.Response, "#5");
2946 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2953 [Category ("NotWorking")]
2954 public void Write_Stream_Closed ()
2956 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9149);
2957 string url = "http://" + ep.ToString () + "/test/";
2959 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2962 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2963 req.Method = "POST";
2965 using (Stream rs = req.GetRequestStream ()) {
2968 rs.Write (new byte [0], 0, 0);
2970 } catch (WebException ex) {
2971 // The request was aborted: The connection was closed unexpectedly
2972 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2973 Assert.IsNull (ex.InnerException, "#3");
2974 Assert.IsNotNull (ex.Message, "#4");
2975 Assert.IsNull (ex.Response, "#5");
2976 Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
2983 public void WriteByte_Request_Aborted ()
2985 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9150);
2986 string url = "http://" + ep.ToString () + "/test/";
2988 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2991 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2992 req.Method = "POST";
2994 using (Stream rs = req.GetRequestStream ()) {
2997 rs.WriteByte (0x2a);
2999 } catch (WebException ex) {
3000 // The request was aborted: The request was canceled
3001 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3002 Assert.IsNull (ex.InnerException, "#3");
3003 Assert.IsNotNull (ex.Message, "#4");
3004 Assert.IsNull (ex.Response, "#5");
3005 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3013 public void WriteTimeout ()
3015 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9151);
3016 string url = "http://" + ep.ToString () + "/test/";
3018 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3021 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3022 req.Method = "POST";
3024 Stream rs = req.GetRequestStream ();
3026 Assert.AreEqual (300000, rs.WriteTimeout, "#1");
3028 Assert.AreEqual (300000, rs.WriteTimeout, "#2");
3039 public static class StreamExtensions {
3040 public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
3044 while (totalRead < count) {
3045 int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
3049 totalRead += bytesRead;
3056 public class ExceptionAssert {
3058 /// Asserts that the function throws an exception.
3060 /// <param name="f">A function execute that is expected to raise an exception.</param>
3061 /// <typeparam name="T">The type of exception that is expected.</typeparam>
3062 /// <returns>The exception thrown.</returns>
3063 /// <exception cref="AssertFailedException">If the function does not throw an exception
3064 /// or throws a different exception.</exception>
3065 /// <example><![CDATA[
3066 /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
3067 /// myObject.myFunction(null); });
3069 public static T Throws<T> (Action f) where T : Exception {
3070 Exception actualException = null;
3074 } catch (Exception ex) {
3075 actualException = ex;
3078 if (actualException == null)
3079 throw new AssertionException (string.Format (
3080 "No exception thrown. Expected '{0}'",
3081 typeof (T).FullName));
3082 else if (typeof(T) != actualException.GetType())
3083 throw new AssertionException (string.Format (
3084 "Caught exception of type '{0}'. Expected '{1}':{2}",
3085 actualException.GetType().FullName,
3086 typeof (T).FullName,
3087 Environment.NewLine + actualException));
3089 return (T) actualException;