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
35 private Random rand = new Random ();
36 private byte [] data64KB = new byte [64 * 1024];
41 ServicePointManager.Expect100Continue = false;
42 rand.NextBytes (data64KB);
47 [Ignore ("Ignore failures in Sys.Net")]
49 public void Proxy_Null ()
51 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
52 Assert.IsNotNull (req.Proxy, "#1");
54 Assert.IsNull (req.Proxy, "#2");
58 [Category("InetAccess")]
60 [Ignore ("NMA - wrong cookies number returned")]
64 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
65 Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
67 req.UserAgent = "MonoClient v1.0";
68 Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
69 Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
71 HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
72 Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
73 Assert.AreEqual ("OK", res.StatusDescription, "#B2");
75 Assert.AreEqual ("text/html; charset=ISO-8859-1", res.Headers.Get ("Content-Type"), "#C1");
76 Assert.IsNotNull (res.LastModified, "#C2");
77 Assert.AreEqual (0, res.Cookies.Count, "#C3");
83 public void AddRange ()
85 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
87 req.AddRange (50, 90);
88 req.AddRange ("bytes", 100);
89 req.AddRange ("bytes", 100, 120);
90 Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
92 req.AddRange ("bits", 2000);
94 } catch (InvalidOperationException) {}
98 public void CloseRequestStreamAfterReadingResponse ()
100 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9152);
101 string url = "http://" + ep.ToString () + "/test/";
103 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
106 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
109 req.ReadWriteTimeout = 2000;
111 byte [] data = new byte [128];
112 req.ContentLength = data.Length;
114 Stream rs = req.GetRequestStream ();
115 rs.Write (data, 0, data.Length);
118 HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
128 [Category("InetAccess")]
129 public void Cookies1 ()
131 // The purpose of this test is to ensure that the cookies we get from a request
132 // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
133 // in HttpWebRequest.
134 // If this URL stops sending *one* and only one cookie, replace it.
135 string url = "http://www.elmundo.es";
136 CookieContainer cookies = new CookieContainer ();
137 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
138 req.KeepAlive = false;
139 req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
140 req.CookieContainer = cookies;
141 Assert.AreEqual (0, cookies.Count, "#01");
142 using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
143 CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
144 Assert.AreEqual (1, coll.Count, "#02");
145 Assert.AreEqual (1, res.Cookies.Count, "#03");
146 Cookie one = coll [0];
147 Cookie two = res.Cookies [0];
148 Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
152 #if !TARGET_JVM //NotWorking
154 [Ignore ("Fails on MS.NET")]
155 public void SslClientBlock ()
157 // This tests that the write request/initread/write body sequence does not hang
159 // If there's a regression for this, the test will hang.
160 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
162 SslHttpServer server = new SslHttpServer ();
165 string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
166 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
167 request.Method = "POST";
168 Stream stream = request.GetRequestStream ();
169 byte [] bytes = new byte [100];
170 stream.Write (bytes, 0, bytes.Length);
172 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
173 Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
174 StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
179 if (server.Error != null)
182 ServicePointManager.CertificatePolicy = null;
188 [Category("NotWorking")]
190 public void Missing_ContentEncoding ()
192 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
194 BadChunkedServer server = new BadChunkedServer ();
197 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
198 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
199 request.Method = "GET";
200 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
201 Assert.AreEqual ("", resp.ContentEncoding);
204 if (server.Error != null)
207 ServicePointManager.CertificatePolicy = null;
213 [Category ("NotWorking")]
215 public void BadServer_ChunkedClose ()
217 // The server will send a chunked response without a 'last-chunked' mark
218 // and then shutdown the socket for sending.
219 BadChunkedServer server = new BadChunkedServer ();
221 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
222 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
223 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
226 byte [] bytes = new byte [32];
227 // Using StreamReader+UTF8Encoding here fails on MS runtime
228 Stream stream = resp.GetResponseStream ();
229 int nread = stream.Read (bytes, 0, 32);
230 Assert.AreEqual (16, nread, "#01");
231 x = Encoding.ASCII.GetString (bytes, 0, 16);
237 if (server.Error != null)
240 Assert.AreEqual ("1234567890123456", x);
244 [Ignore ("This test asserts that our code violates RFC 2616")]
245 public void MethodCase ()
247 ListDictionary methods = new ListDictionary ();
248 methods.Add ("post", "POST");
249 methods.Add ("puT", "PUT");
250 methods.Add ("POST", "POST");
251 methods.Add ("whatever", "whatever");
252 methods.Add ("PUT", "PUT");
254 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9153);
255 string url = "http://" + ep.ToString () + "/test/";
257 foreach (DictionaryEntry de in methods) {
258 SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler));
261 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
262 req.Method = (string) de.Key;
264 req.ReadWriteTimeout = 2000;
265 req.KeepAlive = false;
266 Stream rs = req.GetRequestStream ();
268 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
269 StreamReader sr = new StreamReader (resp.GetResponseStream (),
271 string line = sr.ReadLine ();
273 Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
282 public void BeginGetRequestStream_Body_NotAllowed ()
284 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9154);
285 string url = "http://" + ep.ToString () + "/test/";
287 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
290 HttpWebRequest request;
292 request = (HttpWebRequest) WebRequest.Create (url);
293 request.Method = "GET";
296 request.BeginGetRequestStream (null, null);
298 } catch (ProtocolViolationException ex) {
299 // Cannot send a content-body with this
301 Assert.IsNull (ex.InnerException, "#A2");
302 Assert.IsNotNull (ex.Message, "#A3");
305 request = (HttpWebRequest) WebRequest.Create (url);
306 request.Method = "HEAD";
309 request.BeginGetRequestStream (null, null);
311 } catch (ProtocolViolationException ex) {
312 // Cannot send a content-body with this
314 Assert.IsNull (ex.InnerException, "#B2");
315 Assert.IsNotNull (ex.Message, "#B3");
320 [Test] // bug #465613
321 public void BeginGetRequestStream_NoBuffering ()
323 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 11001);
324 string url = "http://" + ep.ToString () + "/test/";
326 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
333 req = (HttpWebRequest) WebRequest.Create (url);
335 req.SendChunked = false;
336 req.KeepAlive = false;
337 req.AllowWriteStreamBuffering = false;
339 ar = req.BeginGetRequestStream (null, null);
340 rs = req.EndGetRequestStream (ar);
343 req = (HttpWebRequest) WebRequest.Create (url);
345 req.SendChunked = false;
346 req.KeepAlive = true;
347 req.AllowWriteStreamBuffering = false;
350 req.BeginGetRequestStream (null, null);
352 } catch (ProtocolViolationException ex) {
353 // When performing a write operation with
354 // AllowWriteStreamBuffering set to false,
355 // you must either set ContentLength to a
356 // non-negative number or set SendChunked
358 Assert.IsNull (ex.InnerException, "#A2");
359 Assert.IsNotNull (ex.Message, "#A3");
362 req = (HttpWebRequest) WebRequest.Create (url);
364 req.SendChunked = false;
365 req.KeepAlive = true;
366 req.AllowWriteStreamBuffering = false;
367 req.ContentLength = 0;
369 ar = req.BeginGetRequestStream (null, null);
370 rs = req.EndGetRequestStream (ar);
375 [Test] // bug #508027
376 public void BeginGetResponse ()
378 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8001);
379 string url = "http://" + ep.ToString () + "/test/";
381 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
386 req = (HttpWebRequest) WebRequest.Create (url);
389 req.SendChunked = false;
390 req.KeepAlive = false;
391 req.AllowWriteStreamBuffering = false;
392 req.BeginGetResponse (null, null);
395 req = (HttpWebRequest) WebRequest.Create (url);
398 req.SendChunked = true;
399 req.KeepAlive = false;
400 req.AllowWriteStreamBuffering = false;
401 req.GetRequestStream ().WriteByte (1);
402 req.BeginGetResponse (null, null);
405 req = (HttpWebRequest) WebRequest.Create (url);
408 req.ContentLength = 5;
409 req.SendChunked = false;
410 req.KeepAlive = false;
411 req.AllowWriteStreamBuffering = false;
412 req.GetRequestStream ().WriteByte (5);
413 req.BeginGetResponse (null, null);
416 req = (HttpWebRequest) WebRequest.Create (url);
419 req.SendChunked = false;
420 req.KeepAlive = true;
421 req.AllowWriteStreamBuffering = false;
423 req.BeginGetResponse (null, null);
426 req = (HttpWebRequest) WebRequest.Create (url);
429 req.SendChunked = false;
430 req.KeepAlive = false;
431 req.AllowWriteStreamBuffering = false;
432 req.ContentLength = 5;
433 req.BeginGetResponse (null, null);
436 req = (HttpWebRequest) WebRequest.Create (url);
439 req.SendChunked = false;
440 req.KeepAlive = true;
441 req.AllowWriteStreamBuffering = false;
442 req.ContentLength = 5;
443 req.BeginGetResponse (null, null);
446 req = (HttpWebRequest) WebRequest.Create (url);
449 req.SendChunked = true;
451 req.BeginGetResponse (null, null);
454 req = (HttpWebRequest) WebRequest.Create (url);
457 req.ContentLength = 5;
459 req.BeginGetResponse (null, null);
462 req = (HttpWebRequest) WebRequest.Create (url);
465 req.ContentLength = 0;
467 req.BeginGetResponse (null, null);
472 [Test] // bug #511851
473 public void BeginGetRequestStream_Request_Aborted ()
475 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8002);
476 string url = "http://" + ep.ToString () + "/test/";
478 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
481 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
486 req.BeginGetRequestStream (null, null);
488 } catch (WebException ex) {
489 // The request was aborted: The request was canceled
490 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
491 Assert.IsNull (ex.InnerException, "#3");
492 Assert.IsNotNull (ex.Message, "#4");
493 Assert.IsNull (ex.Response, "#5");
494 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
499 [Test] // bug #511851
500 public void BeginGetResponse_Request_Aborted ()
502 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9155);
503 string url = "http://" + ep.ToString () + "/test/";
505 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
508 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
513 req.BeginGetResponse (null, null);
515 } catch (WebException ex) {
516 // The request was aborted: The request was canceled
517 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
518 Assert.IsNull (ex.InnerException, "#3");
519 Assert.IsNotNull (ex.Message, "#4");
520 Assert.IsNull (ex.Response, "#5");
521 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
527 public void EndGetRequestStream_AsyncResult_Null ()
529 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9156);
530 string url = "http://" + ep.ToString () + "/test/";
532 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
535 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
537 req.BeginGetRequestStream (null, null);
540 req.EndGetRequestStream (null);
542 } catch (ArgumentNullException ex) {
543 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
544 Assert.IsNull (ex.InnerException, "#3");
545 Assert.IsNotNull (ex.Message, "#4");
546 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
554 [Category ("NotWorking")] // do not get consistent result on MS
555 public void EndGetRequestStream_Request_Aborted ()
557 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8003);
558 string url = "http://" + ep.ToString () + "/test/";
560 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
563 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
565 IAsyncResult ar = req.BeginGetRequestStream (null, null);
570 req.EndGetRequestStream (ar);
572 } catch (WebException ex) {
573 // The request was aborted: The request was canceled
574 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
575 Assert.IsNull (ex.InnerException, "#3");
576 Assert.IsNotNull (ex.Message, "#4");
577 Assert.IsNull (ex.Response, "#5");
578 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
583 [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
584 [Category ("NotWorking")]
585 public void EndGetResponse_AsyncResult_Invalid ()
587 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9157);
588 string url = "http://" + ep.ToString () + "/test/";
590 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
593 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
596 req.ReadWriteTimeout = 2000;
597 IAsyncResult ar = req.BeginGetRequestStream (null, null);
599 // AsyncResult was not returned from call to BeginGetResponse
601 req.EndGetResponse (ar);
603 } catch (InvalidCastException) {
611 public void EndGetResponse_AsyncResult_Null ()
613 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9158);
614 string url = "http://" + ep.ToString () + "/test/";
616 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
619 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
621 req.ReadWriteTimeout = 2000;
623 IAsyncResult ar = req.BeginGetResponse (null, null);
626 req.EndGetResponse (null);
628 } catch (ArgumentNullException ex) {
629 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
630 Assert.IsNull (ex.InnerException, "#3");
631 Assert.IsNotNull (ex.Message, "#4");
632 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
636 using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
643 [Test] // bug #429200
644 public void GetRequestStream ()
646 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10000);
647 string url = "http://" + ep.ToString () + "/test/";
649 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
652 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
655 req.ReadWriteTimeout = 2000;
657 Stream rs1 = req.GetRequestStream ();
658 Stream rs2 = req.GetRequestStream ();
660 Assert.IsNotNull (rs1, "#1");
661 Assert.AreSame (rs1, rs2, "#2");
667 [Test] // bug #511851
668 public void GetRequestStream_Request_Aborted ()
670 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10001);
671 string url = "http://" + ep.ToString () + "/test/";
673 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
676 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
681 req.GetRequestStream ();
683 } catch (WebException ex) {
684 // The request was aborted: The request was canceled
685 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
686 Assert.IsNull (ex.InnerException, "#3");
687 Assert.IsNotNull (ex.Message, "#4");
688 Assert.IsNull (ex.Response, "#5");
689 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
694 [Test] // bug #510661
695 public void GetRequestStream_Close_NotAllBytesWritten ()
697 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10002);
698 string url = "http://" + ep.ToString () + "/test/";
700 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
706 req = (HttpWebRequest) WebRequest.Create (url);
708 req.ContentLength = 2;
709 rs = req.GetRequestStream ();
713 } catch (WebException ex) {
714 // The request was aborted: The request was canceled
715 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
716 Assert.IsNotNull (ex.Message, "#A3");
717 Assert.IsNull (ex.Response, "#A4");
718 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
720 // Cannot close stream until all bytes are written
721 Exception inner = ex.InnerException;
722 Assert.IsNotNull (inner, "#A6");
723 Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
724 Assert.IsNull (inner.InnerException, "#A8");
725 Assert.IsNotNull (inner.Message, "#A9");
728 req = (HttpWebRequest) WebRequest.Create (url);
730 req.ContentLength = 2;
731 rs = req.GetRequestStream ();
736 } catch (WebException ex) {
737 // The request was aborted: The request was canceled
738 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
739 Assert.IsNotNull (ex.Message, "#B3");
740 Assert.IsNull (ex.Response, "#B4");
741 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
743 // Cannot close stream until all bytes are written
744 Exception inner = ex.InnerException;
745 Assert.IsNotNull (inner, "#B6");
746 Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
747 Assert.IsNull (inner.InnerException, "#B8");
748 Assert.IsNotNull (inner.Message, "#B9");
751 req = (HttpWebRequest) WebRequest.Create (url);
753 req.ContentLength = 2;
754 rs = req.GetRequestStream ();
761 [Test] // bug #510642
762 public void GetRequestStream_Write_Overflow ()
764 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8010);
765 string url = "http://" + ep.ToString () + "/test/";
767 // buffered, non-chunked
768 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
775 req = (HttpWebRequest) WebRequest.Create (url);
778 req.ReadWriteTimeout = 2000;
779 req.ContentLength = 2;
781 rs = req.GetRequestStream ();
784 buffer = new byte [] { 0x2a, 0x1d };
786 rs.Write (buffer, 0, buffer.Length);
788 } catch (ProtocolViolationException ex) {
789 // Bytes to be written to the stream exceed
790 // Content-Length bytes size specified
791 Assert.IsNull (ex.InnerException, "#A2");
792 Assert.IsNotNull (ex.Message, "#A3");
797 req = (HttpWebRequest) WebRequest.Create (url);
800 req.ReadWriteTimeout = 2000;
801 req.ContentLength = 2;
803 rs = req.GetRequestStream ();
805 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
807 rs.Write (buffer, 0, buffer.Length);
809 } catch (ProtocolViolationException ex) {
810 // Bytes to be written to the stream exceed
811 // Content-Length bytes size specified
812 Assert.IsNull (ex.InnerException, "#B2");
813 Assert.IsNotNull (ex.Message, "#B3");
820 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
828 req = (HttpWebRequest) WebRequest.Create (url);
830 req.SendChunked = true;
832 req.ReadWriteTimeout = 2000;
833 req.ContentLength = 2;
835 rs = req.GetRequestStream ();
838 buffer = new byte [] { 0x2a, 0x1d };
839 rs.Write (buffer, 0, buffer.Length);
843 req = (HttpWebRequest) WebRequest.Create (url);
845 req.SendChunked = true;
847 req.ReadWriteTimeout = 2000;
848 req.ContentLength = 2;
850 rs = req.GetRequestStream ();
852 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
853 rs.Write (buffer, 0, buffer.Length);
857 // non-buffered, non-chunked
858 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
865 req = (HttpWebRequest) WebRequest.Create (url);
866 req.AllowWriteStreamBuffering = false;
869 req.ReadWriteTimeout = 2000;
870 req.ContentLength = 2;
872 rs = req.GetRequestStream ();
875 buffer = new byte [] { 0x2a, 0x1d };
877 rs.Write (buffer, 0, buffer.Length);
879 } catch (ProtocolViolationException ex) {
880 // Bytes to be written to the stream exceed
881 // Content-Length bytes size specified
882 Assert.IsNull (ex.InnerException, "#C2");
883 Assert.IsNotNull (ex.Message, "#3");
888 req = (HttpWebRequest) WebRequest.Create (url);
889 req.AllowWriteStreamBuffering = false;
892 req.ReadWriteTimeout = 2000;
893 req.ContentLength = 2;
895 rs = req.GetRequestStream ();
897 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
899 rs.Write (buffer, 0, buffer.Length);
901 } catch (ProtocolViolationException ex) {
902 // Bytes to be written to the stream exceed
903 // Content-Length bytes size specified
904 Assert.IsNull (ex.InnerException, "#D2");
905 Assert.IsNotNull (ex.Message, "#D3");
911 // non-buffered, chunked
912 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
919 req = (HttpWebRequest) WebRequest.Create (url);
920 req.AllowWriteStreamBuffering = false;
922 req.SendChunked = true;
924 req.ReadWriteTimeout = 2000;
925 req.ContentLength = 2;
927 rs = req.GetRequestStream ();
930 buffer = new byte [] { 0x2a, 0x1d };
931 rs.Write (buffer, 0, buffer.Length);
934 req = (HttpWebRequest) WebRequest.Create (url);
935 req.AllowWriteStreamBuffering = false;
937 req.SendChunked = true;
939 req.ReadWriteTimeout = 2000;
940 req.ContentLength = 2;
942 rs = req.GetRequestStream ();
944 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
945 rs.Write (buffer, 0, buffer.Length);
951 [Ignore ("This test asserts that our code violates RFC 2616")]
952 public void GetRequestStream_Body_NotAllowed ()
954 string [] methods = new string [] { "GET", "HEAD", "CONNECT",
955 "get", "HeAd", "ConNect" };
957 foreach (string method in methods) {
958 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
959 "http://localhost:8000");
962 req.GetRequestStream ();
963 Assert.Fail ("#1:" + method);
964 } catch (ProtocolViolationException ex) {
965 Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
966 Assert.IsNull (ex.InnerException, "#3:" + method);
967 Assert.IsNotNull (ex.Message, "#4:" + method);
972 [Test] // bug #511851
973 public void GetResponse_Request_Aborted ()
975 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 10100);
976 string url = "http://" + ep.ToString () + "/test/";
978 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
981 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
988 } catch (WebException ex) {
989 // The request was aborted: The request was canceled
990 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
991 Assert.IsNull (ex.InnerException, "#3");
992 Assert.IsNotNull (ex.Message, "#4");
993 Assert.IsNull (ex.Response, "#5");
994 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
1001 [Category("NotWorking")]
1003 [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
1004 public void ReadTimeout ()
1006 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
1007 string url = "http://" + localEP.ToString () + "/original/";
1009 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1012 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1013 req.Method = "POST";
1014 req.AllowAutoRedirect = false;
1016 req.ReadWriteTimeout = 2000;
1017 req.KeepAlive = false;
1018 Stream rs = req.GetRequestStream ();
1020 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1022 Stream s = resp.GetResponseStream ();
1025 } catch (WebException ex) {
1026 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
1027 Assert.IsNull (ex.InnerException, "#3");
1028 Assert.IsNull (ex.Response, "#4");
1029 Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
1036 [Test] // bug #324300
1038 [Category("NotWorking")]
1040 public void AllowAutoRedirect ()
1042 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8765);
1043 string url = "http://" + localEP.ToString () + "/original/";
1045 // allow autoredirect
1046 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1049 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1050 req.Method = "POST";
1052 req.ReadWriteTimeout = 2000;
1053 req.KeepAlive = false;
1054 Stream rs = req.GetRequestStream ();
1056 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1057 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1059 string body = sr.ReadToEnd ();
1061 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1062 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1063 localEP.ToString () + "/moved/", "#A2");
1064 Assert.AreEqual ("GET", resp.Method, "#A3");
1065 Assert.AreEqual ("LOOKS OK", body, "#A4");
1070 // do not allow autoredirect
1071 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1074 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1075 req.Method = "POST";
1076 req.AllowAutoRedirect = false;
1078 req.ReadWriteTimeout = 1000;
1079 req.KeepAlive = false;
1080 Stream rs = req.GetRequestStream ();
1082 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1083 Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
1084 Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
1085 Assert.AreEqual ("POST", resp.Method, "#B3");
1092 public void PostAndRedirect_NoCL ()
1094 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8769);
1095 string url = "http://" + localEP.ToString () + "/original/";
1097 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1100 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1101 req.Method = "POST";
1103 req.ReadWriteTimeout = 2000;
1104 Stream rs = req.GetRequestStream ();
1107 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1108 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1110 string body = sr.ReadToEnd ();
1112 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1113 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1114 localEP.ToString () + "/moved/", "#A2");
1115 Assert.AreEqual ("GET", resp.Method, "#A3");
1116 Assert.AreEqual ("LOOKS OK", body, "#A4");
1123 public void PostAndRedirect_CL ()
1125 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8770);
1126 string url = "http://" + localEP.ToString () + "/original/";
1128 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1131 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1132 req.Method = "POST";
1134 req.ReadWriteTimeout = 2000;
1135 req.ContentLength = 1;
1136 Stream rs = req.GetRequestStream ();
1138 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1139 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1141 string body = sr.ReadToEnd ();
1143 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1144 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1145 localEP.ToString () + "/moved/", "#A2");
1146 Assert.AreEqual ("GET", resp.Method, "#A3");
1147 Assert.AreEqual ("LOOKS OK", body, "#A4");
1154 public void PostAnd401 ()
1156 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8771);
1157 string url = "http://" + localEP.ToString () + "/original/";
1159 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1162 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1163 req.Method = "POST";
1165 req.ReadWriteTimeout = 2000;
1166 req.ContentLength = 1;
1167 Stream rs = req.GetRequestStream ();
1169 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1170 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1172 string body = sr.ReadToEnd ();
1174 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1175 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1176 localEP.ToString () + "/moved/", "#A2");
1177 Assert.AreEqual ("GET", resp.Method, "#A3");
1178 Assert.AreEqual ("LOOKS OK", body, "#A4");
1184 [Test] // bug #324347
1185 [Category ("NotWorking")]
1186 public void InternalServerError ()
1188 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8766);
1189 string url = "http://" + localEP.ToString () + "/original/";
1192 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1195 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1196 req.Method = "POST";
1198 req.ReadWriteTimeout = 2000;
1199 req.KeepAlive = false;
1200 Stream rs = req.GetRequestStream ();
1205 Assert.Fail ("#A1");
1206 } catch (WebException ex) {
1207 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1208 Assert.IsNull (ex.InnerException, "#A3");
1209 Assert.IsNotNull (ex.Message, "#A4");
1210 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
1212 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1213 Assert.IsNotNull (webResponse, "#A6");
1214 Assert.AreEqual ("POST", webResponse.Method, "#A7");
1215 webResponse.Close ();
1222 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1225 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1228 req.ReadWriteTimeout = 2000;
1229 req.KeepAlive = false;
1233 Assert.Fail ("#B1");
1234 } catch (WebException ex) {
1235 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1236 Assert.IsNull (ex.InnerException, "#B3");
1237 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1239 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1240 Assert.IsNotNull (webResponse, "#B5");
1241 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1242 webResponse.Close ();
1250 [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
1251 public void NoContentLength ()
1253 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8767);
1254 string url = "http://" + localEP.ToString () + "/original/";
1257 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1260 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1261 req.Method = "POST";
1263 req.ReadWriteTimeout = 2000;
1264 req.KeepAlive = false;
1265 Stream rs = req.GetRequestStream ();
1270 Assert.Fail ("#A1");
1271 } catch (WebException ex) {
1272 // The underlying connection was closed:
1273 // An unexpected error occurred on a
1275 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1276 Assert.IsNotNull (ex.InnerException, "#A3");
1277 Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
1278 Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
1280 // Unable to read data from the transport connection:
1281 // A connection attempt failed because the connected party
1282 // did not properly respond after a period of time, or
1283 // established connection failed because connected host has
1284 // failed to respond
1285 IOException ioe = (IOException) ex.InnerException;
1286 Assert.IsNotNull (ioe.InnerException, "#A6");
1287 Assert.IsNotNull (ioe.Message, "#A7");
1288 Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
1290 // An existing connection was forcibly
1291 // closed by the remote host
1292 SocketException soe = (SocketException) ioe.InnerException;
1293 Assert.IsNull (soe.InnerException, "#A9");
1294 Assert.IsNotNull (soe.Message, "#A10");
1296 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1297 Assert.IsNull (webResponse, "#A11");
1304 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1307 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1310 req.ReadWriteTimeout = 2000;
1311 req.KeepAlive = false;
1315 Assert.Fail ("#B1");
1316 } catch (WebException ex) {
1317 // The remote server returned an error:
1318 // (500) Internal Server Error
1319 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1320 Assert.IsNull (ex.InnerException, "#B3");
1321 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1323 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1324 Assert.IsNotNull (webResponse, "#B5");
1325 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1326 webResponse.Close ();
1333 [Test] // bug #513087
1334 public void NonStandardVerb ()
1336 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8123);
1337 string url = "http://" + ep.ToString () + "/moved/";
1339 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (VerbEchoHandler))) {
1342 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1343 req.Method = "WhatEver";
1344 req.KeepAlive = false;
1345 req.Timeout = 20000;
1346 req.ReadWriteTimeout = 20000;
1348 Stream rs = req.GetRequestStream ();
1351 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1352 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1354 string body = sr.ReadToEnd ();
1356 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
1357 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1358 ep.ToString () + "/moved/", "#2");
1359 Assert.AreEqual ("WhatEver", resp.Method, "#3");
1360 Assert.AreEqual ("WhatEver", body, "#4");
1368 [Category ("NotWorking")] // Assert #2 fails
1369 public void NotModifiedSince ()
1371 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9123);
1372 string url = "http://" + ep.ToString () + "/test/";
1374 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (NotModifiedSinceHandler))) {
1377 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1379 req.KeepAlive = false;
1380 req.Timeout = 20000;
1381 req.ReadWriteTimeout = 20000;
1382 req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
1383 req.IfModifiedSince = new DateTime (2010, 01, 04);
1385 DateTime start = DateTime.Now;
1386 HttpWebResponse response = null;
1391 } catch (WebException e) {
1392 response = (HttpWebResponse) e.Response;
1395 Assert.IsNotNull (response, "#2");
1396 using (Stream stream = response.GetResponseStream ()) {
1397 byte [] buffer = new byte [4096];
1398 int bytesRead = stream.Read (buffer, 0, buffer.Length);
1399 Assert.AreEqual (0, bytesRead, "#3");
1402 TimeSpan elapsed = DateTime.Now - start;
1403 Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
1409 [Test] // bug #353495
1410 [Category ("NotWorking")]
1411 public void LastModifiedKind ()
1413 const string reqURL = "http://coffeefaq.com/site/node/25";
1414 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
1415 HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
1416 DateTime lastMod = resp.LastModified;
1417 //string rawLastMod = resp.Headers ["Last-Modified"];
1419 //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
1420 Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
1421 req = (HttpWebRequest) WebRequest.Create (reqURL);
1422 req.IfModifiedSince = lastMod;
1424 resp = (HttpWebResponse) req.GetResponse ();
1426 Assert.Fail ("Should result in 304");
1427 } catch (WebException ex) {
1428 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
1429 Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
1433 internal static byte [] EchoRequestHandler (Socket socket)
1435 MemoryStream ms = new MemoryStream ();
1436 byte [] buffer = new byte [4096];
1437 int bytesReceived = socket.Receive (buffer);
1438 while (bytesReceived > 0) {
1439 ms.Write (buffer, 0, bytesReceived);
1440 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1441 // after sending the headers
1443 if (socket.Available > 0) {
1444 bytesReceived = socket.Receive (buffer);
1451 StreamReader sr = new StreamReader (ms, Encoding.UTF8);
1452 string request = sr.ReadToEnd ();
1454 StringWriter sw = new StringWriter ();
1455 sw.WriteLine ("HTTP/1.1 200 OK");
1456 sw.WriteLine ("Content-Type: text/xml");
1457 sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
1462 return Encoding.UTF8.GetBytes (sw.ToString ());
1465 static byte [] RedirectRequestHandler (Socket socket)
1467 MemoryStream ms = new MemoryStream ();
1468 byte [] buffer = new byte [4096];
1469 int bytesReceived = socket.Receive (buffer);
1470 while (bytesReceived > 0) {
1471 ms.Write (buffer, 0, bytesReceived);
1472 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1473 // after sending the headers
1475 if (socket.Available > 0) {
1476 bytesReceived = socket.Receive (buffer);
1483 string statusLine = null;
1484 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1485 statusLine = sr.ReadLine ();
1488 StringWriter sw = new StringWriter ();
1489 if (statusLine.StartsWith ("POST /original/")) {
1490 sw.WriteLine ("HTTP/1.0 302 Found");
1491 EndPoint ep = socket.LocalEndPoint;
1492 sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
1495 } else if (statusLine.StartsWith ("GET /moved/")) {
1496 sw.WriteLine ("HTTP/1.0 200 OK");
1497 sw.WriteLine ("Content-Type: text/plain");
1498 sw.WriteLine ("Content-Length: 8");
1500 sw.Write ("LOOKS OK");
1503 sw.WriteLine ("HTTP/1.0 500 Too Lazy");
1508 return Encoding.UTF8.GetBytes (sw.ToString ());
1511 static byte [] InternalErrorHandler (Socket socket)
1513 byte [] buffer = new byte [4096];
1514 int bytesReceived = socket.Receive (buffer);
1515 while (bytesReceived > 0) {
1516 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1517 // after sending the headers
1519 if (socket.Available > 0) {
1520 bytesReceived = socket.Receive (buffer);
1525 StringWriter sw = new StringWriter ();
1526 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1527 sw.WriteLine ("Content-Length: 0");
1531 return Encoding.UTF8.GetBytes (sw.ToString ());
1534 static byte [] NoContentLengthHandler (Socket socket)
1536 StringWriter sw = new StringWriter ();
1537 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1541 return Encoding.UTF8.GetBytes (sw.ToString ());
1544 static byte [] NotModifiedSinceHandler (Socket socket)
1546 StringWriter sw = new StringWriter ();
1547 sw.WriteLine ("HTTP/1.1 304 Not Modified");
1548 sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
1549 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");
1550 sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
1551 sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
1552 sw.WriteLine ("Connection: close");
1556 return Encoding.UTF8.GetBytes (sw.ToString ());
1559 static byte [] VerbEchoHandler (Socket socket)
1561 MemoryStream ms = new MemoryStream ();
1562 byte [] buffer = new byte [4096];
1563 int bytesReceived = socket.Receive (buffer);
1564 while (bytesReceived > 0) {
1565 ms.Write (buffer, 0, bytesReceived);
1566 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1567 // after sending the headers
1569 if (socket.Available > 0) {
1570 bytesReceived = socket.Receive (buffer);
1577 string statusLine = null;
1578 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1579 statusLine = sr.ReadLine ();
1582 string verb = "DEFAULT";
1583 if (statusLine != null) {
1584 string [] parts = statusLine.Split (' ');
1585 if (parts.Length > 0)
1589 StringWriter sw = new StringWriter ();
1590 sw.WriteLine ("HTTP/1.1 200 OK");
1591 sw.WriteLine ("Content-Type: text/plain");
1592 sw.WriteLine ("Content-Length: " + verb.Length);
1597 return Encoding.UTF8.GetBytes (sw.ToString ());
1600 static byte [] PostAnd401Handler (Socket socket)
1602 MemoryStream ms = new MemoryStream ();
1603 byte [] buffer = new byte [4096];
1604 int bytesReceived = socket.Receive (buffer);
1605 while (bytesReceived > 0) {
1606 ms.Write (buffer, 0, bytesReceived);
1607 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1608 // after sending the headers
1610 if (socket.Available > 0) {
1611 bytesReceived = socket.Receive (buffer);
1618 string statusLine = null;
1619 bool have_auth = false;
1621 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1623 while ((l = sr.ReadLine ()) != null) {
1624 if (statusLine == null) {
1626 } else if (l.StartsWith ("Authorization:")) {
1628 } else if (l.StartsWith ("Content-Length:")) {
1629 cl = Int32.Parse (l.Substring ("content-length: ".Length));
1634 StringWriter sw = new StringWriter ();
1636 sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
1637 sw.WriteLine ("WWW-Authenticate: basic Yeah");
1640 } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
1641 sw.WriteLine ("HTTP/1.0 200 OK");
1642 sw.WriteLine ("Content-Type: text/plain");
1643 sw.WriteLine ("Content-Length: 8");
1645 sw.Write ("LOOKS OK");
1648 sw.WriteLine ("HTTP/1.0 500 test failed");
1649 sw.WriteLine ("Content-Length: 0");
1654 return Encoding.UTF8.GetBytes (sw.ToString ());
1657 public void NtlmAuthentication ()
1659 NtlmServer server = new NtlmServer ();
1662 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
1663 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
1664 request.Timeout = 5000;
1665 request.Credentials = new NetworkCredential ("user", "password", "domain");
1666 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
1668 using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
1669 res = reader.ReadToEnd ();
1673 Assert.AreEqual ("OK", res);
1676 class NtlmServer : HttpServer {
1677 public string Where = "";
1678 protected override void Run ()
1680 Where = "before accept";
1681 Socket client = sock.Accept ();
1682 NetworkStream ns = new NetworkStream (client, false);
1683 StreamReader reader = new StreamReader (ns, Encoding.ASCII);
1685 Where = "first read";
1686 while ((line = reader.ReadLine ()) != null) {
1687 if (line.Trim () == String.Empty) {
1691 Where = "first write";
1692 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1693 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1694 "WWW-Authenticate: NTLM\r\n" +
1695 "Content-Length: 5\r\n\r\nWRONG");
1698 Where = "second read";
1699 while ((line = reader.ReadLine ()) != null) {
1700 if (line.Trim () == String.Empty) {
1704 Where = "second write";
1705 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1706 "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
1707 "Content-Length: 5\r\n\r\nWRONG");
1710 Where = "third read";
1711 while ((line = reader.ReadLine ()) != null) {
1712 if (line.Trim () == String.Empty) {
1716 Where = "third write";
1717 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1718 "Keep-Alive: true\r\n" +
1719 "Content-Length: 2\r\n\r\nOK");
1721 Thread.Sleep (1000);
1728 class BadChunkedServer : HttpServer {
1729 protected override void Run ()
1731 Socket client = sock.Accept ();
1732 NetworkStream ns = new NetworkStream (client, true);
1733 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1734 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1735 "Transfer-Encoding: chunked\r\n" +
1736 "Connection: close\r\n" +
1737 "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
1739 // This body lacks a 'last-chunk' (see RFC 2616)
1740 writer.Write ("10\r\n1234567890123456\r\n");
1742 client.Shutdown (SocketShutdown.Send);
1743 Thread.Sleep (1000);
1748 class AcceptAllPolicy : ICertificatePolicy {
1749 public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
1755 abstract class HttpServer
1757 protected Socket sock;
1758 protected Exception error;
1759 protected ManualResetEvent evt;
1761 public HttpServer ()
1763 sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
1764 sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
1768 public void Start ()
1770 evt = new ManualResetEvent (false);
1771 Thread th = new Thread (new ThreadStart (Run));
1781 public IPAddress IPAddress {
1782 get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
1786 get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
1789 public Exception Error {
1790 get { return error; }
1793 protected abstract void Run ();
1797 public void BeginGetRequestStream ()
1803 r.ContentLength = 0;
1804 r.BeginGetRequestStream ((a) =>
1806 using (Stream s = r.EndGetRequestStream (a)) { };
1815 public void BeginGetRequestStreamNoClose ()
1820 r.ContentLength = 1;
1821 r.BeginGetRequestStream ((a) =>
1823 r.EndGetRequestStream (a);
1832 public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
1838 r.ContentLength = 10;
1839 r.BeginGetRequestStream ((a) =>
1841 WebException ex = ExceptionAssert.Throws<WebException> (() =>
1843 using (Stream s = r.EndGetRequestStream (a)) {
1847 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1856 public void GetRequestStream2 ()
1862 r.ContentLength = data64KB.Length;
1863 using (Stream s = r.GetRequestStream ()) {
1864 s.Write (data64KB, 0, data64KB.Length);
1872 public void GetRequestStreamNotAllBytesWritten ()
1878 r.ContentLength = data64KB.Length;
1879 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
1880 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1887 public void GetRequestStreamTimeout ()
1893 r.ContentLength = data64KB.Length;
1895 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
1896 Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
1902 public void BeginWrite ()
1904 byte[] received = new byte[data64KB.Length];
1910 r.ContentLength = data64KB.Length;
1912 Stream s = r.GetRequestStream ();
1913 s.BeginWrite (data64KB, 0, data64KB.Length,
1918 r.GetResponse ().Close ();
1925 c.Request.InputStream.ReadAll (received, 0, received.Length);
1926 c.Response.StatusCode = 204;
1927 c.Response.Close ();
1930 Assert.AreEqual (data64KB, received);
1934 public void BeginWriteAfterAbort ()
1936 byte [] received = new byte [data64KB.Length];
1942 r.ContentLength = data64KB.Length;
1944 Stream s = r.GetRequestStream ();
1947 WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
1948 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1954 c.Request.InputStream.ReadAll (received, 0, received.Length);
1955 c.Response.StatusCode = 204;
1961 public void PrematureStreamCloseAborts ()
1963 byte [] received = new byte [data64KB.Length];
1969 r.ContentLength = data64KB.Length * 2;
1971 Stream s = r.GetRequestStream ();
1972 s.Write (data64KB, 0, data64KB.Length);
1974 WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
1975 Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
1981 c.Request.InputStream.ReadAll (received, 0, received.Length);
1982 c.Response.StatusCode = 204;
1983 c.Response.Close ();
1988 public void Write ()
1990 byte [] received = new byte [data64KB.Length];
1996 r.ContentLength = data64KB.Length;
1998 using (Stream s = r.GetRequestStream ()) {
1999 s.Write (data64KB, 0, data64KB.Length);
2002 r.GetResponse ().Close ();
2007 c.Request.InputStream.ReadAll (received, 0, received.Length);
2008 c.Response.StatusCode = 204;
2009 c.Response.Close ();
2012 Assert.AreEqual(data64KB, received);
2016 Invalid test: it does not work on linux.
2017 [pid 30973] send(9, "POST / HTTP/1.1\r\nContent-Length:"..., 89, 0) = 89
2019 [pid 30970] send(16, "HTTP/1.1 200 OK\r\nServer: Mono-HT"..., 133, 0) = 133
2021 [pid 30970] close(16) = 0
2023 [pid 30980] send(9, "\213t\326\350\312u\36n\234\351\225L\r\243a\200\226\371\350F\271~oZ\32\270\24\226z4\211\345"..., 65536, 0) = 65536
2025 [pid 30966] close(4) = 0
2028 The server sideis closed (FD 16) and the send on the client side (FD 9) succeeds.
2030 [Category("NotWorking")]
2031 public void WriteServerAborts ()
2033 ManualResetEvent abort = new ManualResetEvent (false);
2034 byte [] received = new byte [data64KB.Length];
2040 r.ContentLength = data64KB.Length;
2042 using (Stream s = r.GetRequestStream()) {
2045 IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
2061 byte [] received = new byte [data64KB.Length];
2066 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2067 using (Stream s = x.GetResponseStream()) {
2068 s.ReadAll (received, 0, received.Length);
2075 c.Response.StatusCode = 200;
2076 c.Response.ContentLength64 = data64KB.Length;
2077 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2078 c.Response.OutputStream.Close ();
2079 c.Response.Close ();
2082 Assert.AreEqual (data64KB, received);
2086 public void ReadTimeout2 ()
2088 byte [] received = new byte [data64KB.Length];
2093 r.ReadWriteTimeout = 10;
2094 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2095 using (Stream s = x.GetResponseStream ()) {
2096 WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
2097 Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
2104 c.Response.StatusCode = 200;
2105 c.Response.ContentLength64 = data64KB.Length;
2106 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
2107 Thread.Sleep (1000);
2108 c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
2109 c.Response.OutputStream.Close ();
2110 c.Response.Close ();
2115 public void ReadServerAborted ()
2117 byte [] received = new byte [data64KB.Length];
2122 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2123 using (Stream s = x.GetResponseStream ()) {
2124 Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
2131 c.Response.StatusCode = 200;
2132 c.Response.ContentLength64 = data64KB.Length;
2133 c.Response.OutputStream.Write (data64KB, 0, 1);
2134 c.Response.Abort ();
2139 public void BeginGetResponse2 ()
2141 byte [] received = new byte [data64KB.Length];
2146 r.BeginGetResponse ((a) =>
2148 using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
2149 using (Stream s = x.GetResponseStream ()) {
2150 s.ReadAll (received, 0, received.Length);
2158 c.Response.StatusCode = 200;
2159 c.Response.ContentLength64 = data64KB.Length;
2160 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2161 c.Response.OutputStream.Close ();
2162 c.Response.Close ();
2165 Assert.AreEqual (data64KB, received);
2169 public void BeginGetResponseAborts ()
2171 ManualResetEvent aborted = new ManualResetEvent(false);
2176 r.BeginGetResponse((a) =>
2178 WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
2179 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2190 c.Response.StatusCode = 200;
2191 c.Response.ContentLength64 = 0;
2192 c.Response.Close ();
2196 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
2198 int port = rand.Next (20000, 65535);
2200 ManualResetEvent completed = new ManualResetEvent (false);
2201 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2202 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2204 request (client, completed);
2206 if (!completed.WaitOne (10000))
2207 Assert.Fail ("Test hung");
2210 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
2212 int port = rand.Next (20000, 65535);
2214 ManualResetEvent [] completed = new ManualResetEvent [2];
2215 completed [0] = new ManualResetEvent (false);
2216 completed [1] = new ManualResetEvent (false);
2218 using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
2219 ManualResetEvent clientCompleted = new ManualResetEvent (false);
2220 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2221 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2223 ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
2225 if (!WaitHandle.WaitAll (completed, 10000))
2226 Assert.Fail ("Test hung.");
2232 [ExpectedException (typeof (ArgumentNullException))]
2233 public void NullHost ()
2235 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2240 public void NoHost ()
2242 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2243 Assert.AreEqual (req.Host, "go-mono.com");
2247 [ExpectedException (typeof (ArgumentException))]
2248 public void EmptyHost ()
2250 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2255 public void HostAndPort ()
2257 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
2258 Assert.AreEqual ("go-mono.com", req.Host, "#01");
2259 req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
2260 Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
2264 public void PortRange ()
2266 for (int i = 0; i < 65536; i++) {
2269 string s = i.ToString ();
2270 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
2271 Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
2276 [ExpectedException (typeof (ArgumentException))]
2277 public void PortBelow ()
2279 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2280 req.Host = "go-mono.com:-1";
2284 [ExpectedException (typeof (ArgumentException))]
2285 public void PortAbove ()
2287 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2288 req.Host = "go-mono.com:65536";
2292 [ExpectedException (typeof (ArgumentException))]
2293 public void HostTooLong ()
2295 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2296 string s = new string ('a', 100);
2297 req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
2301 [Category ("NotWorking")] // #5490
2302 public void InvalidNamesThatWork ()
2304 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2308 req.Host = new string ('a', 64); // Should fail. Max. is 63.
2312 public void NoDate ()
2314 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2315 Assert.AreEqual (DateTime.MinValue, req.Date);
2319 public void UtcDate ()
2321 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2322 req.Date = DateTime.UtcNow;
2323 DateTime date = req.Date;
2324 Assert.AreEqual (DateTimeKind.Local, date.Kind);
2328 public void AddAndRemoveDate ()
2330 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2331 req.Date = DateTime.UtcNow;
2332 req.Date = DateTime.MinValue;
2333 Assert.AreEqual (DateTime.MinValue, req.Date);
2336 class ListenerScope : IDisposable {
2337 EventWaitHandle completed;
2338 public HttpListener listener;
2339 Action<HttpListenerContext> processor;
2341 public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
2343 this.processor = processor;
2344 this.completed = completed;
2346 this.listener = new HttpListener ();
2347 this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
2348 this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
2349 this.listener.Start ();
2351 this.listener.BeginGetContext (this.RequestHandler, null);
2354 void RequestHandler (IAsyncResult result)
2356 HttpListenerContext context = null;
2359 context = this.listener.EndGetContext (result);
2360 } catch (HttpListenerException ex) {
2361 // check if the thread has been aborted as in the case when we are shutting down.
2362 if (ex.ErrorCode == 995)
2364 } catch (ObjectDisposedException) {
2368 ThreadPool.QueueUserWorkItem ((o) =>
2371 this.processor (context);
2372 } catch (HttpListenerException) {
2376 this.completed.Set ();
2379 public void Dispose ()
2381 this.listener.Stop ();
2386 class SslHttpServer : HttpServer {
2387 X509Certificate _certificate;
2389 protected override void Run ()
2392 Socket client = sock.Accept ();
2393 NetworkStream ns = new NetworkStream (client, true);
2394 SslServerStream s = new SslServerStream (ns, Certificate, false, false);
2395 s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
2397 StreamReader reader = new StreamReader (s);
2398 StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
2401 string hello = "<html><body><h1>Hello World!</h1></body></html>";
2402 string answer = "HTTP/1.0 200\r\n" +
2403 "Connection: close\r\n" +
2404 "Content-Type: text/html\r\n" +
2405 "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
2406 "Content-Length: " + hello.Length + "\r\n" +
2411 line = reader.ReadLine ();
2412 } while (line != "" && line != null && line.Length > 0);
2414 // Now the content. We know it's 100 bytes.
2415 // This makes BeginRead in sslclientstream block.
2416 char [] cs = new char [100];
2417 reader.Read (cs, 0, 100);
2419 writer.Write (answer);
2421 if (evt.WaitOne (5000, false))
2422 error = new Exception ("Timeout when stopping the server");
2423 } catch (Exception e) {
2428 X509Certificate Certificate {
2430 if (_certificate == null)
2431 _certificate = new X509Certificate (CertData.Certificate);
2433 return _certificate;
2437 AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
2439 PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
2445 public readonly static byte [] Certificate = {
2446 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
2447 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
2448 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
2449 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
2450 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
2451 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
2452 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
2453 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
2454 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
2455 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
2456 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
2457 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
2458 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
2459 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
2460 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
2461 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
2462 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
2463 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
2464 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
2465 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
2466 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
2467 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
2468 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
2469 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
2470 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
2471 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
2472 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
2473 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
2477 public readonly static byte [] PrivateKey = {
2478 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
2479 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
2480 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
2481 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
2482 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
2483 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
2484 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
2485 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
2486 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
2487 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
2488 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
2489 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
2490 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
2491 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
2492 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
2493 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
2494 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
2495 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
2496 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
2497 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
2498 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
2499 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
2500 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
2501 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
2502 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
2503 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
2504 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
2505 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
2506 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
2507 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
2508 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
2509 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
2510 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
2511 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
2512 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
2513 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
2514 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
2515 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
2516 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
2523 public class HttpRequestStreamTest
2526 public void BeginRead ()
2528 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9124);
2529 string url = "http://" + ep.ToString () + "/test/";
2531 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2534 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2535 req.Method = "POST";
2537 using (Stream rs = req.GetRequestStream ()) {
2538 byte [] buffer = new byte [10];
2540 rs.BeginRead (buffer, 0, buffer.Length, null, null);
2542 } catch (NotSupportedException ex) {
2543 // The stream does not support reading
2544 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2545 Assert.IsNull (ex.InnerException, "#3");
2546 Assert.IsNotNull (ex.Message, "#4");
2555 public void BeginWrite_Request_Aborted ()
2557 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9125);
2558 string url = "http://" + ep.ToString () + "/test/";
2560 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2563 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2564 req.Method = "POST";
2566 using (Stream rs = req.GetRequestStream ()) {
2569 rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
2571 } catch (WebException ex) {
2572 // The request was aborted: The request was canceled
2573 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2574 Assert.IsNull (ex.InnerException, "#3");
2575 Assert.IsNotNull (ex.Message, "#4");
2576 Assert.IsNull (ex.Response, "#5");
2577 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2584 public void CanRead ()
2586 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9126);
2587 string url = "http://" + ep.ToString () + "/test/";
2589 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2592 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2593 req.Method = "POST";
2595 Stream rs = req.GetRequestStream ();
2597 Assert.IsFalse (rs.CanRead, "#1");
2599 Assert.IsFalse (rs.CanRead, "#2");
2608 public void CanSeek ()
2610 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9127);
2611 string url = "http://" + ep.ToString () + "/test/";
2613 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2616 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2617 req.Method = "POST";
2619 Stream rs = req.GetRequestStream ();
2621 Assert.IsFalse (rs.CanSeek, "#1");
2623 Assert.IsFalse (rs.CanSeek, "#2");
2631 [Test] // bug #324182
2633 [Category ("NotWorking")]
2635 public void CanTimeout ()
2637 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9128);
2638 string url = "http://" + ep.ToString () + "/test/";
2640 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2643 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2644 req.Method = "POST";
2646 Stream rs = req.GetRequestStream ();
2648 Assert.IsTrue (rs.CanTimeout, "#1");
2650 Assert.IsTrue (rs.CanTimeout, "#2");
2659 public void CanWrite ()
2661 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9129);
2662 string url = "http://" + ep.ToString () + "/test/";
2664 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2667 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2668 req.Method = "POST";
2670 Stream rs = req.GetRequestStream ();
2672 Assert.IsTrue (rs.CanWrite, "#1");
2674 Assert.IsFalse (rs.CanWrite, "#2");
2685 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9130);
2686 string url = "http://" + ep.ToString () + "/test/";
2688 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2691 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2692 req.Method = "POST";
2694 using (Stream rs = req.GetRequestStream ()) {
2695 byte [] buffer = new byte [10];
2697 rs.Read (buffer, 0, buffer.Length);
2699 } catch (NotSupportedException ex) {
2700 // The stream does not support reading
2701 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2702 Assert.IsNull (ex.InnerException, "#3");
2703 Assert.IsNotNull (ex.Message, "#4");
2712 public void ReadByte ()
2714 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9140);
2715 string url = "http://" + ep.ToString () + "/test/";
2717 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2720 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2721 req.Method = "POST";
2723 using (Stream rs = req.GetRequestStream ()) {
2727 } catch (NotSupportedException ex) {
2728 // The stream does not support reading
2729 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2730 Assert.IsNull (ex.InnerException, "#3");
2731 Assert.IsNotNull (ex.Message, "#4");
2740 public void ReadTimeout ()
2742 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9141);
2743 string url = "http://" + ep.ToString () + "/test/";
2745 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2748 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2749 req.Method = "POST";
2751 Stream rs = req.GetRequestStream ();
2753 Assert.AreEqual (300000, rs.ReadTimeout, "#1");
2755 Assert.AreEqual (300000, rs.ReadTimeout, "#2");
2766 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9142);
2767 string url = "http://" + ep.ToString () + "/test/";
2769 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2772 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2773 req.Method = "POST";
2775 using (Stream rs = req.GetRequestStream ()) {
2777 rs.Seek (0, SeekOrigin.Current);
2779 } catch (NotSupportedException ex) {
2780 // This stream does not support seek operations
2781 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2782 Assert.IsNull (ex.InnerException, "#3");
2783 Assert.IsNotNull (ex.Message, "#4");
2792 public void Write_Buffer_Null ()
2794 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9143);
2795 string url = "http://" + ep.ToString () + "/test/";
2797 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2800 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2801 req.Method = "POST";
2803 using (Stream rs = req.GetRequestStream ()) {
2805 rs.Write ((byte []) null, -1, -1);
2807 } catch (ArgumentNullException ex) {
2808 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2809 Assert.IsNull (ex.InnerException, "#3");
2810 Assert.IsNotNull (ex.Message, "#4");
2811 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2820 public void Write_Count_Negative ()
2822 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9144);
2823 string url = "http://" + ep.ToString () + "/test/";
2825 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2828 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2829 req.Method = "POST";
2831 using (Stream rs = req.GetRequestStream ()) {
2832 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2834 rs.Write (buffer, 1, -1);
2836 } catch (ArgumentOutOfRangeException ex) {
2837 // Specified argument was out of the range of valid values
2838 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
2839 Assert.IsNull (ex.InnerException, "#A3");
2840 Assert.IsNotNull (ex.Message, "#A4");
2841 Assert.AreEqual ("size", ex.ParamName, "#A5");
2850 public void Write_Count_Overflow ()
2852 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9145);
2853 string url = "http://" + ep.ToString () + "/test/";
2855 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2858 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2859 req.Method = "POST";
2861 using (Stream rs = req.GetRequestStream ()) {
2862 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2864 rs.Write (buffer, buffer.Length - 2, 3);
2866 } catch (ArgumentOutOfRangeException ex) {
2867 // Specified argument was out of the range of valid values
2868 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
2869 Assert.IsNull (ex.InnerException, "#3");
2870 Assert.IsNotNull (ex.Message, "#4");
2871 Assert.AreEqual ("size", ex.ParamName, "#5");
2880 public void Write_Offset_Negative ()
2882 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9146);
2883 string url = "http://" + ep.ToString () + "/test/";
2885 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2888 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2889 req.Method = "POST";
2891 using (Stream rs = req.GetRequestStream ()) {
2892 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2894 rs.Write (buffer, -1, 0);
2896 } catch (ArgumentOutOfRangeException ex) {
2897 // Specified argument was out of the range of valid values
2898 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
2899 Assert.IsNull (ex.InnerException, "#3");
2900 Assert.IsNotNull (ex.Message, "#4");
2901 Assert.AreEqual ("offset", ex.ParamName, "#5");
2910 public void Write_Offset_Overflow ()
2912 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9147);
2913 string url = "http://" + ep.ToString () + "/test/";
2915 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2918 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2919 req.Method = "POST";
2921 using (Stream rs = req.GetRequestStream ()) {
2922 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
2924 rs.Write (buffer, buffer.Length + 1, 0);
2926 } catch (ArgumentOutOfRangeException ex) {
2927 // Specified argument was out of the range of valid values
2928 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
2929 Assert.IsNull (ex.InnerException, "#3");
2930 Assert.IsNotNull (ex.Message, "#4");
2931 Assert.AreEqual ("offset", ex.ParamName, "#5");
2940 public void Write_Request_Aborted ()
2942 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9148);
2943 string url = "http://" + ep.ToString () + "/test/";
2945 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2948 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2949 req.Method = "POST";
2951 using (Stream rs = req.GetRequestStream ()) {
2954 rs.Write (new byte [0], 0, 0);
2956 } catch (WebException ex) {
2957 // The request was aborted: The request was canceled
2958 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2959 Assert.IsNull (ex.InnerException, "#3");
2960 Assert.IsNotNull (ex.Message, "#4");
2961 Assert.IsNull (ex.Response, "#5");
2962 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2969 [Category ("NotWorking")]
2970 public void Write_Stream_Closed ()
2972 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9149);
2973 string url = "http://" + ep.ToString () + "/test/";
2975 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2978 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2979 req.Method = "POST";
2981 using (Stream rs = req.GetRequestStream ()) {
2984 rs.Write (new byte [0], 0, 0);
2986 } catch (WebException ex) {
2987 // The request was aborted: The connection was closed unexpectedly
2988 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2989 Assert.IsNull (ex.InnerException, "#3");
2990 Assert.IsNotNull (ex.Message, "#4");
2991 Assert.IsNull (ex.Response, "#5");
2992 Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
2999 public void WriteByte_Request_Aborted ()
3001 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9150);
3002 string url = "http://" + ep.ToString () + "/test/";
3004 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3007 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3008 req.Method = "POST";
3010 using (Stream rs = req.GetRequestStream ()) {
3013 rs.WriteByte (0x2a);
3015 } catch (WebException ex) {
3016 // The request was aborted: The request was canceled
3017 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3018 Assert.IsNull (ex.InnerException, "#3");
3019 Assert.IsNotNull (ex.Message, "#4");
3020 Assert.IsNull (ex.Response, "#5");
3021 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3028 public void WriteTimeout ()
3030 IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 9151);
3031 string url = "http://" + ep.ToString () + "/test/";
3033 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3036 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3037 req.Method = "POST";
3039 Stream rs = req.GetRequestStream ();
3041 Assert.AreEqual (300000, rs.WriteTimeout, "#1");
3043 Assert.AreEqual (300000, rs.WriteTimeout, "#2");
3052 static class StreamExtensions {
3053 public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
3057 while (totalRead < count) {
3058 int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
3062 totalRead += bytesRead;
3069 static class ExceptionAssert {
3071 /// Asserts that the function throws an exception.
3073 /// <param name="f">A function execute that is expected to raise an exception.</param>
3074 /// <typeparam name="T">The type of exception that is expected.</typeparam>
3075 /// <returns>The exception thrown.</returns>
3076 /// <exception cref="AssertFailedException">If the function does not throw an exception
3077 /// or throws a different exception.</exception>
3078 /// <example><![CDATA[
3079 /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
3080 /// myObject.myFunction(null); });
3082 public static T Throws<T> (Action f) where T : Exception {
3083 Exception actualException = null;
3087 } catch (Exception ex) {
3088 actualException = ex;
3091 if (actualException == null)
3092 throw new AssertionException (string.Format (
3093 "No exception thrown. Expected '{0}'",
3094 typeof (T).FullName));
3095 else if (typeof(T) != actualException.GetType())
3096 throw new AssertionException (string.Format (
3097 "Caught exception of type '{0}'. Expected '{1}':{2}",
3098 actualException.GetType().FullName,
3099 typeof (T).FullName,
3100 Environment.NewLine + actualException));
3102 return (T) actualException;