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)
8 // Andres G. Aragoneses (andres@7digital.com)
10 // (C) 2003 Martin Willemoes Hansen
11 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com
12 // Copyright (c) 2013 7digital Media Ltd (http://www.7digital.com)
15 using NUnit.Framework;
17 using System.Collections;
18 using System.Collections.Specialized;
19 using System.Globalization;
22 using System.Net.Sockets;
23 using System.Security.Cryptography;
24 using System.Security.Cryptography.X509Certificates;
26 using System.Threading;
27 using Mono.Security.Authenticode;
29 using Mono.Security.Protocol.Tls;
32 using MonoTests.Helpers;
34 namespace MonoTests.System.Net
37 public class HttpWebRequestTest
39 private Random rand = new Random ();
40 private byte [] data64KB = new byte [64 * 1024];
45 ServicePointManager.Expect100Continue = false;
46 rand.NextBytes (data64KB);
50 public void Proxy_Null ()
52 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
53 Assert.IsNotNull (req.Proxy, "#1");
55 Assert.IsNull (req.Proxy, "#2");
59 [Category("InetAccess")]
62 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
63 Assert.IsNotNull (req.IfModifiedSince, "req:If Modified Since: ");
65 req.UserAgent = "MonoClient v1.0";
66 Assert.AreEqual ("User-Agent", req.Headers.GetKey (0), "#A1");
67 Assert.AreEqual ("MonoClient v1.0", req.Headers.Get (0), "#A2");
69 HttpWebResponse res = (HttpWebResponse) req.GetResponse ();
70 Assert.AreEqual ("OK", res.StatusCode.ToString (), "#B1");
71 Assert.AreEqual ("OK", res.StatusDescription, "#B2");
73 Assert.IsTrue (res.Headers.Get ("Content-Type").StartsWith ("text/html; charset=", StringComparison.OrdinalIgnoreCase), "#C1");
74 Assert.IsNotNull (res.LastModified, "#C2");
75 Assert.AreEqual (0, res.Cookies.Count, "#C3");
81 public void AddRange ()
83 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
85 req.AddRange (50, 90);
86 req.AddRange ("bytes", 100);
87 req.AddRange ("bytes", 100, 120);
88 Assert.AreEqual ("bytes=10-,50-90,100-,100-120", req.Headers ["Range"], "#1");
90 req.AddRange ("bits", 2000);
92 } catch (InvalidOperationException) {}
96 public void CloseRequestStreamAfterReadingResponse ()
98 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
99 string url = "http://" + ep.ToString () + "/test/";
101 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
104 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
107 req.ReadWriteTimeout = 2000;
109 byte [] data = new byte [128];
110 req.ContentLength = data.Length;
112 Stream rs = req.GetRequestStream ();
113 rs.Write (data, 0, data.Length);
116 HttpWebResponse response = (HttpWebResponse) req.GetResponse ();
126 //[Category("InetAccess")]
127 [Category ("NotWorking")] // Disabled until a server that meets requirements is found
128 public void Cookies1 ()
130 // The purpose of this test is to ensure that the cookies we get from a request
131 // are stored in both, the CookieCollection in HttpWebResponse and the CookieContainer
132 // in HttpWebRequest.
133 // If this URL stops sending *one* and only one cookie, replace it.
134 string url = "http://xamarin.com";
135 CookieContainer cookies = new CookieContainer ();
136 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
137 req.KeepAlive = false;
138 req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv; 1.7.6) Gecko/20050317 Firefox/1.0.2";
139 req.CookieContainer = cookies;
140 Assert.AreEqual (0, cookies.Count, "#01");
141 using (HttpWebResponse res = (HttpWebResponse) req.GetResponse()) {
142 CookieCollection coll = req.CookieContainer.GetCookies (new Uri (url));
143 Assert.AreEqual (1, coll.Count, "#02");
144 Assert.AreEqual (1, res.Cookies.Count, "#03");
145 Cookie one = coll [0];
146 Cookie two = res.Cookies [0];
147 Assert.AreEqual (true, object.ReferenceEquals (one, two), "#04");
153 [Ignore ("Fails on MS.NET")]
154 public void SslClientBlock ()
156 // This tests that the write request/initread/write body sequence does not hang
158 // If there's a regression for this, the test will hang.
159 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
161 SslHttpServer server = new SslHttpServer ();
164 string url = String.Format ("https://{0}:{1}/nothing.html", server.IPAddress, server.Port);
165 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
166 request.Method = "POST";
167 Stream stream = request.GetRequestStream ();
168 byte [] bytes = new byte [100];
169 stream.Write (bytes, 0, bytes.Length);
171 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
172 Assert.AreEqual (200, (int) resp.StatusCode, "StatusCode");
173 StreamReader sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
178 if (server.Error != null)
181 ServicePointManager.CertificatePolicy = null;
186 public void Missing_ContentEncoding ()
188 ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
190 BadChunkedServer server = new BadChunkedServer ();
193 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
194 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
195 request.Method = "GET";
196 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
197 Assert.AreEqual ("", resp.ContentEncoding);
200 if (server.Error != null)
203 ServicePointManager.CertificatePolicy = null;
208 public void BadServer_ChunkedClose ()
210 // The server will send a chunked response without a 'last-chunked' mark
211 // and then shutdown the socket for sending.
212 BadChunkedServer server = new BadChunkedServer ();
214 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
215 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
216 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
219 byte [] bytes = new byte [32];
220 // Using StreamReader+UTF8Encoding here fails on MS runtime
221 Stream stream = resp.GetResponseStream ();
222 int nread = stream.Read (bytes, 0, 32);
223 Assert.AreEqual (16, nread, "#01");
224 x = Encoding.ASCII.GetString (bytes, 0, 16);
230 if (server.Error != null)
233 Assert.AreEqual ("1234567890123456", x);
237 [Ignore ("This test asserts that our code violates RFC 2616")]
238 public void MethodCase ()
240 ListDictionary methods = new ListDictionary ();
241 methods.Add ("post", "POST");
242 methods.Add ("puT", "PUT");
243 methods.Add ("POST", "POST");
244 methods.Add ("whatever", "whatever");
245 methods.Add ("PUT", "PUT");
247 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
248 string url = "http://" + ep.ToString () + "/test/";
250 foreach (DictionaryEntry de in methods) {
251 SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler));
254 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
255 req.Method = (string) de.Key;
257 req.ReadWriteTimeout = 2000;
258 req.KeepAlive = false;
259 Stream rs = req.GetRequestStream ();
261 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
262 StreamReader sr = new StreamReader (resp.GetResponseStream (),
264 string line = sr.ReadLine ();
266 Assert.AreEqual (((string) de.Value) + " /test/ HTTP/1.1",
275 public void BeginGetRequestStream_Body_NotAllowed ()
277 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
278 string url = "http://" + ep.ToString () + "/test/";
280 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
283 HttpWebRequest request;
285 request = (HttpWebRequest) WebRequest.Create (url);
286 request.Method = "GET";
289 request.BeginGetRequestStream (null, null);
291 } catch (ProtocolViolationException ex) {
292 // Cannot send a content-body with this
294 Assert.IsNull (ex.InnerException, "#A2");
295 Assert.IsNotNull (ex.Message, "#A3");
298 request = (HttpWebRequest) WebRequest.Create (url);
299 request.Method = "HEAD";
302 request.BeginGetRequestStream (null, null);
304 } catch (ProtocolViolationException ex) {
305 // Cannot send a content-body with this
307 Assert.IsNull (ex.InnerException, "#B2");
308 Assert.IsNotNull (ex.Message, "#B3");
313 [Test] // bug #465613
314 public void BeginGetRequestStream_NoBuffering ()
316 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
317 string url = "http://" + ep.ToString () + "/test/";
319 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
326 req = (HttpWebRequest) WebRequest.Create (url);
328 req.SendChunked = false;
329 req.KeepAlive = false;
330 req.AllowWriteStreamBuffering = false;
332 ar = req.BeginGetRequestStream (null, null);
333 rs = req.EndGetRequestStream (ar);
336 req = (HttpWebRequest) WebRequest.Create (url);
338 req.SendChunked = false;
339 req.KeepAlive = true;
340 req.AllowWriteStreamBuffering = false;
343 req.BeginGetRequestStream (null, null);
345 } catch (ProtocolViolationException ex) {
346 // When performing a write operation with
347 // AllowWriteStreamBuffering set to false,
348 // you must either set ContentLength to a
349 // non-negative number or set SendChunked
351 Assert.IsNull (ex.InnerException, "#A2");
352 Assert.IsNotNull (ex.Message, "#A3");
355 req = (HttpWebRequest) WebRequest.Create (url);
357 req.SendChunked = false;
358 req.KeepAlive = true;
359 req.AllowWriteStreamBuffering = false;
360 req.ContentLength = 0;
362 ar = req.BeginGetRequestStream (null, null);
363 rs = req.EndGetRequestStream (ar);
368 [Test] // bug #508027
369 [Category ("NotWorking")] // #5842
370 public void BeginGetResponse ()
372 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
373 string url = "http://" + ep.ToString () + "/test/";
375 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
380 req = (HttpWebRequest) WebRequest.Create (url);
383 req.SendChunked = false;
384 req.KeepAlive = false;
385 req.AllowWriteStreamBuffering = false;
386 req.BeginGetResponse (null, null);
389 req = (HttpWebRequest) WebRequest.Create (url);
392 req.SendChunked = true;
393 req.KeepAlive = false;
394 req.AllowWriteStreamBuffering = false;
395 req.GetRequestStream ().WriteByte (1);
396 req.BeginGetResponse (null, null);
399 req = (HttpWebRequest) WebRequest.Create (url);
402 req.ContentLength = 5;
403 req.SendChunked = false;
404 req.KeepAlive = false;
405 req.AllowWriteStreamBuffering = false;
406 req.GetRequestStream ().WriteByte (5);
407 req.BeginGetResponse (null, null);
410 req = (HttpWebRequest) WebRequest.Create (url);
413 req.SendChunked = false;
414 req.KeepAlive = true;
415 req.AllowWriteStreamBuffering = false;
417 req.BeginGetResponse (null, null);
420 req = (HttpWebRequest) WebRequest.Create (url);
423 req.SendChunked = false;
424 req.KeepAlive = false;
425 req.AllowWriteStreamBuffering = false;
426 req.ContentLength = 5;
427 req.BeginGetResponse (null, null);
430 req = (HttpWebRequest) WebRequest.Create (url);
433 req.SendChunked = false;
434 req.KeepAlive = true;
435 req.AllowWriteStreamBuffering = false;
436 req.ContentLength = 5;
437 req.BeginGetResponse (null, null);
440 req = (HttpWebRequest) WebRequest.Create (url);
443 req.SendChunked = true;
445 req.BeginGetResponse (null, null);
448 req = (HttpWebRequest) WebRequest.Create (url);
451 req.ContentLength = 5;
453 req.BeginGetResponse (null, null);
456 req = (HttpWebRequest) WebRequest.Create (url);
459 req.ContentLength = 0;
461 req.BeginGetResponse (null, null);
466 [Test] // bug #511851
467 public void BeginGetRequestStream_Request_Aborted ()
469 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
470 string url = "http://" + ep.ToString () + "/test/";
472 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
475 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
480 req.BeginGetRequestStream (null, null);
482 } catch (WebException ex) {
483 // The request was aborted: The request was canceled
484 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
485 Assert.IsNull (ex.InnerException, "#3");
486 Assert.IsNotNull (ex.Message, "#4");
487 Assert.IsNull (ex.Response, "#5");
488 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
493 [Test] // bug #511851
494 public void BeginGetResponse_Request_Aborted ()
496 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
497 string url = "http://" + ep.ToString () + "/test/";
499 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
502 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
507 req.BeginGetResponse (null, null);
509 } catch (WebException ex) {
510 // The request was aborted: The request was canceled
511 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
512 Assert.IsNull (ex.InnerException, "#3");
513 Assert.IsNotNull (ex.Message, "#4");
514 Assert.IsNull (ex.Response, "#5");
515 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
521 public void EndGetRequestStream_AsyncResult_Null ()
523 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
524 string url = "http://" + ep.ToString () + "/test/";
526 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
529 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
531 req.BeginGetRequestStream (null, null);
534 req.EndGetRequestStream (null);
536 } catch (ArgumentNullException ex) {
537 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
538 Assert.IsNull (ex.InnerException, "#3");
539 Assert.IsNotNull (ex.Message, "#4");
540 Assert.AreEqual ("asyncResult", ex.ParamName, "#5");
548 [Category ("NotWorking")] // do not get consistent result on MS
549 public void EndGetRequestStream_Request_Aborted ()
551 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
552 string url = "http://" + ep.ToString () + "/test/";
554 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
557 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
559 IAsyncResult ar = req.BeginGetRequestStream (null, null);
564 req.EndGetRequestStream (ar);
566 } catch (WebException ex) {
567 // The request was aborted: The request was canceled
568 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
569 Assert.IsNull (ex.InnerException, "#3");
570 Assert.IsNotNull (ex.Message, "#4");
571 Assert.IsNull (ex.Response, "#5");
572 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
577 [Test] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=471522
578 [Category ("NotWorking")]
579 public void EndGetResponse_AsyncResult_Invalid ()
581 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
582 string url = "http://" + ep.ToString () + "/test/";
584 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
587 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
590 req.ReadWriteTimeout = 2000;
591 IAsyncResult ar = req.BeginGetRequestStream (null, null);
593 // AsyncResult was not returned from call to BeginGetResponse
595 req.EndGetResponse (ar);
597 } catch (InvalidCastException) {
605 public void EndGetResponse_AsyncResult_Null ()
607 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
608 string url = "http://" + ep.ToString () + "/test/";
610 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
613 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
615 req.ReadWriteTimeout = 2000;
617 IAsyncResult ar = req.BeginGetResponse (null, null);
620 req.EndGetResponse (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");
630 using (HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse (ar)) {
637 [Test] // bug #429200
638 public void GetRequestStream ()
640 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
641 string url = "http://" + ep.ToString () + "/test/";
643 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
646 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
649 req.ReadWriteTimeout = 2000;
651 Stream rs1 = req.GetRequestStream ();
652 Stream rs2 = req.GetRequestStream ();
654 Assert.IsNotNull (rs1, "#1");
655 Assert.AreSame (rs1, rs2, "#2");
661 [Test] // bug #511851
662 public void GetRequestStream_Request_Aborted ()
664 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
665 string url = "http://" + ep.ToString () + "/test/";
667 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
670 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
675 req.GetRequestStream ();
677 } catch (WebException ex) {
678 // The request was aborted: The request was canceled
679 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
680 Assert.IsNull (ex.InnerException, "#3");
681 Assert.IsNotNull (ex.Message, "#4");
682 Assert.IsNull (ex.Response, "#5");
683 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
688 [Test] // bug #510661
689 [Category ("NotWorking")] // #5842
690 public void GetRequestStream_Close_NotAllBytesWritten ()
692 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
693 string url = "http://" + ep.ToString () + "/test/";
695 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
701 req = (HttpWebRequest) WebRequest.Create (url);
703 req.ContentLength = 2;
704 rs = req.GetRequestStream ();
708 } catch (WebException ex) {
709 // The request was aborted: The request was canceled
710 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
711 Assert.IsNotNull (ex.Message, "#A3");
712 Assert.IsNull (ex.Response, "#A4");
713 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#A5");
715 // Cannot close stream until all bytes are written
716 Exception inner = ex.InnerException;
717 Assert.IsNotNull (inner, "#A6");
718 Assert.AreEqual (typeof (IOException), inner.GetType (), "#A7");
719 Assert.IsNull (inner.InnerException, "#A8");
720 Assert.IsNotNull (inner.Message, "#A9");
723 req = (HttpWebRequest) WebRequest.Create (url);
725 req.ContentLength = 2;
726 rs = req.GetRequestStream ();
731 } catch (WebException ex) {
732 // The request was aborted: The request was canceled
733 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
734 Assert.IsNotNull (ex.Message, "#B3");
735 Assert.IsNull (ex.Response, "#B4");
736 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#B5");
738 // Cannot close stream until all bytes are written
739 Exception inner = ex.InnerException;
740 Assert.IsNotNull (inner, "#B6");
741 Assert.AreEqual (typeof (IOException), inner.GetType (), "#B7");
742 Assert.IsNull (inner.InnerException, "#B8");
743 Assert.IsNotNull (inner.Message, "#B9");
746 req = (HttpWebRequest) WebRequest.Create (url);
748 req.ContentLength = 2;
749 rs = req.GetRequestStream ();
756 [Test] // bug #510642
757 [Category ("NotWorking")] // #5842
758 public void GetRequestStream_Write_Overflow ()
760 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
761 string url = "http://" + ep.ToString () + "/test/";
763 // buffered, non-chunked
764 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
771 req = (HttpWebRequest) WebRequest.Create (url);
774 req.ReadWriteTimeout = 2000;
775 req.ContentLength = 2;
777 rs = req.GetRequestStream ();
780 buffer = new byte [] { 0x2a, 0x1d };
782 rs.Write (buffer, 0, buffer.Length);
784 } catch (ProtocolViolationException ex) {
785 // Bytes to be written to the stream exceed
786 // Content-Length bytes size specified
787 Assert.IsNull (ex.InnerException, "#A2");
788 Assert.IsNotNull (ex.Message, "#A3");
793 req = (HttpWebRequest) WebRequest.Create (url);
796 req.ReadWriteTimeout = 2000;
797 req.ContentLength = 2;
799 rs = req.GetRequestStream ();
801 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
803 rs.Write (buffer, 0, buffer.Length);
805 } catch (ProtocolViolationException ex) {
806 // Bytes to be written to the stream exceed
807 // Content-Length bytes size specified
808 Assert.IsNull (ex.InnerException, "#B2");
809 Assert.IsNotNull (ex.Message, "#B3");
816 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
824 req = (HttpWebRequest) WebRequest.Create (url);
826 req.SendChunked = true;
828 req.ReadWriteTimeout = 2000;
829 req.ContentLength = 2;
831 rs = req.GetRequestStream ();
834 buffer = new byte [] { 0x2a, 0x1d };
835 rs.Write (buffer, 0, buffer.Length);
839 req = (HttpWebRequest) WebRequest.Create (url);
841 req.SendChunked = true;
843 req.ReadWriteTimeout = 2000;
844 req.ContentLength = 2;
846 rs = req.GetRequestStream ();
848 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
849 rs.Write (buffer, 0, buffer.Length);
853 // non-buffered, non-chunked
854 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
861 req = (HttpWebRequest) WebRequest.Create (url);
862 req.AllowWriteStreamBuffering = false;
865 req.ReadWriteTimeout = 2000;
866 req.ContentLength = 2;
868 rs = req.GetRequestStream ();
871 buffer = new byte [] { 0x2a, 0x1d };
873 rs.Write (buffer, 0, buffer.Length);
875 } catch (ProtocolViolationException ex) {
876 // Bytes to be written to the stream exceed
877 // Content-Length bytes size specified
878 Assert.IsNull (ex.InnerException, "#C2");
879 Assert.IsNotNull (ex.Message, "#3");
884 req = (HttpWebRequest) WebRequest.Create (url);
885 req.AllowWriteStreamBuffering = false;
888 req.ReadWriteTimeout = 2000;
889 req.ContentLength = 2;
891 rs = req.GetRequestStream ();
893 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
895 rs.Write (buffer, 0, buffer.Length);
897 } catch (ProtocolViolationException ex) {
898 // Bytes to be written to the stream exceed
899 // Content-Length bytes size specified
900 Assert.IsNull (ex.InnerException, "#D2");
901 Assert.IsNotNull (ex.Message, "#D3");
907 // non-buffered, chunked
908 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
915 req = (HttpWebRequest) WebRequest.Create (url);
916 req.AllowWriteStreamBuffering = false;
918 req.SendChunked = true;
920 req.ReadWriteTimeout = 2000;
921 req.ContentLength = 2;
923 rs = req.GetRequestStream ();
926 buffer = new byte [] { 0x2a, 0x1d };
927 rs.Write (buffer, 0, buffer.Length);
930 req = (HttpWebRequest) WebRequest.Create (url);
931 req.AllowWriteStreamBuffering = false;
933 req.SendChunked = true;
935 req.ReadWriteTimeout = 2000;
936 req.ContentLength = 2;
938 rs = req.GetRequestStream ();
940 buffer = new byte [] { 0x2a, 0x2c, 0x1d };
941 rs.Write (buffer, 0, buffer.Length);
947 [Ignore ("This test asserts that our code violates RFC 2616")]
948 public void GetRequestStream_Body_NotAllowed ()
950 string [] methods = new string [] { "GET", "HEAD", "CONNECT",
951 "get", "HeAd", "ConNect" };
953 foreach (string method in methods) {
954 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (
955 "http://localhost:8000");
958 req.GetRequestStream ();
959 Assert.Fail ("#1:" + method);
960 } catch (ProtocolViolationException ex) {
961 Assert.AreEqual (typeof (ProtocolViolationException), ex.GetType (), "#2:" + method);
962 Assert.IsNull (ex.InnerException, "#3:" + method);
963 Assert.IsNotNull (ex.Message, "#4:" + method);
968 [Test] // bug #511851
969 public void GetResponse_Request_Aborted ()
971 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
972 string url = "http://" + ep.ToString () + "/test/";
974 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (EchoRequestHandler))) {
977 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
984 } catch (WebException ex) {
985 // The request was aborted: The request was canceled
986 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
987 Assert.IsNull (ex.InnerException, "#3");
988 Assert.IsNotNull (ex.Message, "#4");
989 Assert.IsNull (ex.Response, "#5");
990 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
996 [Ignore ("This does not timeout any more. That's how MS works when reading small responses")]
997 public void ReadTimeout ()
999 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8764);
1000 string url = "http://" + localEP.ToString () + "/original/";
1002 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1005 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1006 req.Method = "POST";
1007 req.AllowAutoRedirect = false;
1009 req.ReadWriteTimeout = 2000;
1010 req.KeepAlive = false;
1011 Stream rs = req.GetRequestStream ();
1013 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1015 Stream s = resp.GetResponseStream ();
1018 } catch (WebException ex) {
1019 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
1020 Assert.IsNull (ex.InnerException, "#3");
1021 Assert.IsNull (ex.Response, "#4");
1022 Assert.AreEqual (WebExceptionStatus.Timeout, ex.Status, "#5");
1029 [Test] // bug #324300
1030 public void AllowAutoRedirect ()
1032 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8765);
1033 string url = "http://" + localEP.ToString () + "/original/";
1035 // allow autoredirect
1036 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1039 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1040 req.Method = "POST";
1042 req.ReadWriteTimeout = 2000;
1043 req.KeepAlive = false;
1044 Stream rs = req.GetRequestStream ();
1046 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1047 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1049 string body = sr.ReadToEnd ();
1051 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1052 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1053 localEP.ToString () + "/moved/", "#A2");
1054 Assert.AreEqual ("GET", resp.Method, "#A3");
1055 Assert.AreEqual ("LOOKS OK", body, "#A4");
1060 // do not allow autoredirect
1061 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1064 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1065 req.Method = "POST";
1066 req.AllowAutoRedirect = false;
1068 req.ReadWriteTimeout = 1000;
1069 req.KeepAlive = false;
1070 Stream rs = req.GetRequestStream ();
1072 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1073 Assert.AreEqual (resp.StatusCode, HttpStatusCode.Found, "#B1");
1074 Assert.AreEqual (url, resp.ResponseUri.ToString (), "#B2");
1075 Assert.AreEqual ("POST", resp.Method, "#B3");
1082 public void PostAndRedirect_NoCL ()
1084 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8769);
1085 string url = "http://" + localEP.ToString () + "/original/";
1087 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1090 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1091 req.Method = "POST";
1093 req.ReadWriteTimeout = 2000;
1094 Stream rs = req.GetRequestStream ();
1097 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1098 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1100 string body = sr.ReadToEnd ();
1102 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1103 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1104 localEP.ToString () + "/moved/", "#A2");
1105 Assert.AreEqual ("GET", resp.Method, "#A3");
1106 Assert.AreEqual ("LOOKS OK", body, "#A4");
1113 public void PostAndRedirect_CL ()
1115 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8770);
1116 string url = "http://" + localEP.ToString () + "/original/";
1118 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1121 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1122 req.Method = "POST";
1124 req.ReadWriteTimeout = 2000;
1125 req.ContentLength = 1;
1126 Stream rs = req.GetRequestStream ();
1128 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1129 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1131 string body = sr.ReadToEnd ();
1133 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1134 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1135 localEP.ToString () + "/moved/", "#A2");
1136 Assert.AreEqual ("GET", resp.Method, "#A3");
1137 Assert.AreEqual ("LOOKS OK", body, "#A4");
1144 public void PostAnd401 ()
1146 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8771);
1147 string url = "http://" + localEP.ToString () + "/original/";
1149 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (RedirectRequestHandler))) {
1152 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1153 req.Method = "POST";
1155 req.ReadWriteTimeout = 2000;
1156 req.ContentLength = 1;
1157 Stream rs = req.GetRequestStream ();
1159 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1160 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1162 string body = sr.ReadToEnd ();
1164 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#A1");
1165 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1166 localEP.ToString () + "/moved/", "#A2");
1167 Assert.AreEqual ("GET", resp.Method, "#A3");
1168 Assert.AreEqual ("LOOKS OK", body, "#A4");
1174 [Test] // bug #324347
1175 [Category ("NotWorking")]
1176 public void InternalServerError ()
1178 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8766);
1179 string url = "http://" + localEP.ToString () + "/original/";
1182 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1185 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1186 req.Method = "POST";
1188 req.ReadWriteTimeout = 2000;
1189 req.KeepAlive = false;
1190 Stream rs = req.GetRequestStream ();
1195 Assert.Fail ("#A1");
1196 } catch (WebException ex) {
1197 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1198 Assert.IsNull (ex.InnerException, "#A3");
1199 Assert.IsNotNull (ex.Message, "#A4");
1200 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A5");
1202 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1203 Assert.IsNotNull (webResponse, "#A6");
1204 Assert.AreEqual ("POST", webResponse.Method, "#A7");
1205 webResponse.Close ();
1212 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (InternalErrorHandler))) {
1215 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1218 req.ReadWriteTimeout = 2000;
1219 req.KeepAlive = false;
1223 Assert.Fail ("#B1");
1224 } catch (WebException ex) {
1225 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1226 Assert.IsNull (ex.InnerException, "#B3");
1227 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1229 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1230 Assert.IsNotNull (webResponse, "#B5");
1231 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1232 webResponse.Close ();
1240 [Category ("NotWorking")] // #B3 fails; we get a SocketException: An existing connection was forcibly closed by the remote host
1241 public void NoContentLength ()
1243 IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, 8767);
1244 string url = "http://" + localEP.ToString () + "/original/";
1247 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1250 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1251 req.Method = "POST";
1253 req.ReadWriteTimeout = 2000;
1254 req.KeepAlive = false;
1255 Stream rs = req.GetRequestStream ();
1260 Assert.Fail ("#A1");
1261 } catch (WebException ex) {
1262 // The underlying connection was closed:
1263 // An unexpected error occurred on a
1265 Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2");
1266 Assert.IsNotNull (ex.InnerException, "#A3");
1267 Assert.AreEqual (WebExceptionStatus.ReceiveFailure, ex.Status, "#A4");
1268 Assert.AreEqual (typeof (IOException), ex.InnerException.GetType (), "#A5");
1270 // Unable to read data from the transport connection:
1271 // A connection attempt failed because the connected party
1272 // did not properly respond after a period of time, or
1273 // established connection failed because connected host has
1274 // failed to respond
1275 IOException ioe = (IOException) ex.InnerException;
1276 Assert.IsNotNull (ioe.InnerException, "#A6");
1277 Assert.IsNotNull (ioe.Message, "#A7");
1278 Assert.AreEqual (typeof (SocketException), ioe.InnerException.GetType (), "#A8");
1280 // An existing connection was forcibly
1281 // closed by the remote host
1282 SocketException soe = (SocketException) ioe.InnerException;
1283 Assert.IsNull (soe.InnerException, "#A9");
1284 Assert.IsNotNull (soe.Message, "#A10");
1286 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1287 Assert.IsNull (webResponse, "#A11");
1294 using (SocketResponder responder = new SocketResponder (localEP, new SocketRequestHandler (NoContentLengthHandler))) {
1297 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1300 req.ReadWriteTimeout = 2000;
1301 req.KeepAlive = false;
1305 Assert.Fail ("#B1");
1306 } catch (WebException ex) {
1307 // The remote server returned an error:
1308 // (500) Internal Server Error
1309 Assert.AreEqual (typeof (WebException), ex.GetType (), "#B2");
1310 Assert.IsNull (ex.InnerException, "#B3");
1311 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#B4");
1313 HttpWebResponse webResponse = ex.Response as HttpWebResponse;
1314 Assert.IsNotNull (webResponse, "#B5");
1315 Assert.AreEqual ("GET", webResponse.Method, "#B6");
1316 webResponse.Close ();
1323 [Test] // bug #513087
1324 public void NonStandardVerb ()
1326 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
1327 string url = "http://" + ep.ToString () + "/moved/";
1329 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (VerbEchoHandler))) {
1332 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1333 req.Method = "WhatEver";
1334 req.KeepAlive = false;
1335 req.Timeout = 20000;
1336 req.ReadWriteTimeout = 20000;
1338 Stream rs = req.GetRequestStream ();
1341 using (HttpWebResponse resp = (HttpWebResponse) req.GetResponse ()) {
1342 StreamReader sr = new StreamReader (resp.GetResponseStream (),
1344 string body = sr.ReadToEnd ();
1346 Assert.AreEqual (resp.StatusCode, HttpStatusCode.OK, "#1");
1347 Assert.AreEqual (resp.ResponseUri.ToString (), "http://" +
1348 ep.ToString () + "/moved/", "#2");
1349 Assert.AreEqual ("WhatEver", resp.Method, "#3");
1350 Assert.AreEqual ("WhatEver", body, "#4");
1358 [Category ("NotWorking")] // Assert #2 fails
1359 public void NotModifiedSince ()
1361 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
1362 string url = "http://" + ep.ToString () + "/test/";
1364 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (NotModifiedSinceHandler))) {
1367 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
1369 req.KeepAlive = false;
1370 req.Timeout = 20000;
1371 req.ReadWriteTimeout = 20000;
1372 req.Headers.Add (HttpRequestHeader.IfNoneMatch, "898bbr2347056cc2e096afc66e104653");
1373 req.IfModifiedSince = new DateTime (2010, 01, 04);
1375 DateTime start = DateTime.Now;
1376 HttpWebResponse response = null;
1381 } catch (WebException e) {
1382 response = (HttpWebResponse) e.Response;
1385 Assert.IsNotNull (response, "#2");
1386 using (Stream stream = response.GetResponseStream ()) {
1387 byte [] buffer = new byte [4096];
1388 int bytesRead = stream.Read (buffer, 0, buffer.Length);
1389 Assert.AreEqual (0, bytesRead, "#3");
1392 TimeSpan elapsed = DateTime.Now - start;
1393 Assert.IsTrue (elapsed.TotalMilliseconds < 2000, "#4");
1399 [Test] // bug #353495
1400 [Category ("NotWorking")]
1401 public void LastModifiedKind ()
1403 const string reqURL = "http://coffeefaq.com/site/node/25";
1404 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (reqURL);
1405 HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
1406 DateTime lastMod = resp.LastModified;
1407 //string rawLastMod = resp.Headers ["Last-Modified"];
1409 //Assert.AreEqual ("Tue, 15 Jan 2008 08:59:59 GMT", rawLastMod, "#1");
1410 Assert.AreEqual (DateTimeKind.Local, lastMod.Kind, "#2");
1411 req = (HttpWebRequest) WebRequest.Create (reqURL);
1412 req.IfModifiedSince = lastMod;
1414 resp = (HttpWebResponse) req.GetResponse ();
1416 Assert.Fail ("Should result in 304");
1417 } catch (WebException ex) {
1418 Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#3");
1419 Assert.AreEqual (((HttpWebResponse) ex.Response).StatusCode, HttpStatusCode.NotModified, "#4");
1424 #region Timeout_Bug // https://bugzilla.novell.com/show_bug.cgi?id=317553
1426 class TimeoutTestHelper {
1429 internal DateTime? Start { get; private set; }
1430 internal DateTime? End { get; private set; }
1431 internal Exception Exception { get; private set; }
1432 internal string Body { get; private set; }
1433 internal int TimeOutInMilliSeconds { get; private set; }
1435 internal TimeoutTestHelper (string url, int timeoutInMilliseconds)
1438 TimeOutInMilliSeconds = timeoutInMilliseconds;
1441 internal void LaunchWebRequest ()
1443 var req = (HttpWebRequest) WebRequest.Create (url_to_test);
1444 req.Timeout = TimeOutInMilliSeconds;
1446 Start = DateTime.Now;
1448 using (var resp = (HttpWebResponse) req.GetResponse ())
1450 var sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
1451 Body = sr.ReadToEnd ();
1453 } catch (Exception e) {
1460 void TestTimeOut (string url, WebExceptionStatus expectedExceptionStatus)
1462 var timeoutWorker = new TimeoutTestHelper (url, three_seconds_in_milliseconds);
1463 var threadStart = new ThreadStart (timeoutWorker.LaunchWebRequest);
1464 var thread = new Thread (threadStart);
1466 Thread.Sleep (three_seconds_in_milliseconds * 3);
1468 if (timeoutWorker.End == null) {
1470 Assert.Fail ("Thread finished after triple the timeout specified has passed");
1473 if (!String.IsNullOrEmpty (timeoutWorker.Body)) {
1474 if (timeoutWorker.Body == response_of_timeout_handler) {
1475 Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve proper body");
1477 Assert.Fail ("Should not be reached, timeout exception was not thrown and webrequest managed to retrieve an incorrect body: " + timeoutWorker.Body);
1480 Assert.IsNotNull (timeoutWorker.Exception, "Exception was not thrown");
1482 var webEx = timeoutWorker.Exception as WebException;
1483 Assert.IsNotNull (webEx, "Exception thrown should be WebException, but was: " +
1484 timeoutWorker.Exception.GetType ().FullName);
1486 Assert.AreEqual (expectedExceptionStatus, webEx.Status,
1487 "WebException was thrown, but with a wrong status (should be " + expectedExceptionStatus + "): " + webEx.Status);
1489 Assert.IsFalse (timeoutWorker.End > (timeoutWorker.Start + TimeSpan.FromMilliseconds (three_seconds_in_milliseconds + 500)),
1490 "Timeout exception should have been thrown shortly after timeout is reached, however it was at least half-second late");
1493 [Test] // 1st possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
1494 public void TestTimeoutPropertyWithServerThatExistsAndRespondsButTooLate ()
1496 var ep = new IPEndPoint (IPAddress.Loopback, 8123);
1497 string url = "http://" + ep + "/foobar/";
1499 using (var responder = new SocketResponder (ep, TimeOutHandler))
1503 TestTimeOut (url, WebExceptionStatus.Timeout);
1509 [Test] // 2nd possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
1510 public void TestTimeoutWithEndpointThatDoesntExistThrowsConnectFailureBeforeTimeout ()
1512 string url = "http://127.0.0.1:8271/"; // some endpoint that is unlikely to exist
1514 // connecting to a non-existing endpoint should throw a ConnectFailure before the timeout is reached
1515 TestTimeOut (url, WebExceptionStatus.ConnectFailure);
1518 const string response_of_timeout_handler = "RESPONSE_OF_TIMEOUT_HANDLER";
1519 const int three_seconds_in_milliseconds = 3000;
1521 private static byte[] TimeOutHandler (Socket socket)
1523 socket.Receive (new byte[4096]);
1525 Thread.Sleep (three_seconds_in_milliseconds * 2);
1527 var sw = new StringWriter ();
1528 sw.WriteLine ("HTTP/1.1 200 OK");
1529 sw.WriteLine ("Content-Type: text/plain");
1530 sw.WriteLine ("Content-Length: " + response_of_timeout_handler.Length);
1532 sw.Write (response_of_timeout_handler);
1535 return Encoding.UTF8.GetBytes (sw.ToString ());
1540 internal static byte [] EchoRequestHandler (Socket socket)
1542 MemoryStream ms = new MemoryStream ();
1543 byte [] buffer = new byte [4096];
1544 int bytesReceived = socket.Receive (buffer);
1545 while (bytesReceived > 0) {
1546 ms.Write (buffer, 0, bytesReceived);
1547 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1548 // after sending the headers
1550 if (socket.Available > 0) {
1551 bytesReceived = socket.Receive (buffer);
1558 StreamReader sr = new StreamReader (ms, Encoding.UTF8);
1559 string request = sr.ReadToEnd ();
1561 StringWriter sw = new StringWriter ();
1562 sw.WriteLine ("HTTP/1.1 200 OK");
1563 sw.WriteLine ("Content-Type: text/xml");
1564 sw.WriteLine ("Content-Length: " + request.Length.ToString (CultureInfo.InvariantCulture));
1569 return Encoding.UTF8.GetBytes (sw.ToString ());
1572 static byte [] RedirectRequestHandler (Socket socket)
1574 MemoryStream ms = new MemoryStream ();
1575 byte [] buffer = new byte [4096];
1576 int bytesReceived = socket.Receive (buffer);
1577 while (bytesReceived > 0) {
1578 ms.Write (buffer, 0, bytesReceived);
1579 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1580 // after sending the headers
1582 if (socket.Available > 0) {
1583 bytesReceived = socket.Receive (buffer);
1590 string statusLine = null;
1591 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1592 statusLine = sr.ReadLine ();
1595 StringWriter sw = new StringWriter ();
1596 if (statusLine.StartsWith ("POST /original/")) {
1597 sw.WriteLine ("HTTP/1.0 302 Found");
1598 EndPoint ep = socket.LocalEndPoint;
1599 sw.WriteLine ("Location: " + "http://" + ep.ToString () + "/moved/");
1602 } else if (statusLine.StartsWith ("GET /moved/")) {
1603 sw.WriteLine ("HTTP/1.0 200 OK");
1604 sw.WriteLine ("Content-Type: text/plain");
1605 sw.WriteLine ("Content-Length: 8");
1607 sw.Write ("LOOKS OK");
1610 sw.WriteLine ("HTTP/1.0 500 Too Lazy");
1615 return Encoding.UTF8.GetBytes (sw.ToString ());
1618 static byte [] InternalErrorHandler (Socket socket)
1620 byte [] buffer = new byte [4096];
1621 int bytesReceived = socket.Receive (buffer);
1622 while (bytesReceived > 0) {
1623 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1624 // after sending the headers
1626 if (socket.Available > 0) {
1627 bytesReceived = socket.Receive (buffer);
1632 StringWriter sw = new StringWriter ();
1633 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1634 sw.WriteLine ("Content-Length: 0");
1638 return Encoding.UTF8.GetBytes (sw.ToString ());
1641 static byte [] NoContentLengthHandler (Socket socket)
1643 StringWriter sw = new StringWriter ();
1644 sw.WriteLine ("HTTP/1.1 500 Too Lazy");
1648 return Encoding.UTF8.GetBytes (sw.ToString ());
1651 static byte [] NotModifiedSinceHandler (Socket socket)
1653 StringWriter sw = new StringWriter ();
1654 sw.WriteLine ("HTTP/1.1 304 Not Modified");
1655 sw.WriteLine ("Date: Fri, 06 Feb 2009 12:50:26 GMT");
1656 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");
1657 sw.WriteLine ("Not-Modified-Since: Sun, 08 Feb 2009 08:49:26 GMT");
1658 sw.WriteLine ("ETag: 898bbr2347056cc2e096afc66e104653");
1659 sw.WriteLine ("Connection: close");
1663 return Encoding.UTF8.GetBytes (sw.ToString ());
1666 static byte [] VerbEchoHandler (Socket socket)
1668 MemoryStream ms = new MemoryStream ();
1669 byte [] buffer = new byte [4096];
1670 int bytesReceived = socket.Receive (buffer);
1671 while (bytesReceived > 0) {
1672 ms.Write (buffer, 0, bytesReceived);
1673 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1674 // after sending the headers
1676 if (socket.Available > 0) {
1677 bytesReceived = socket.Receive (buffer);
1684 string statusLine = null;
1685 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1686 statusLine = sr.ReadLine ();
1689 string verb = "DEFAULT";
1690 if (statusLine != null) {
1691 string [] parts = statusLine.Split (' ');
1692 if (parts.Length > 0)
1696 StringWriter sw = new StringWriter ();
1697 sw.WriteLine ("HTTP/1.1 200 OK");
1698 sw.WriteLine ("Content-Type: text/plain");
1699 sw.WriteLine ("Content-Length: " + verb.Length);
1704 return Encoding.UTF8.GetBytes (sw.ToString ());
1707 static byte [] PostAnd401Handler (Socket socket)
1709 MemoryStream ms = new MemoryStream ();
1710 byte [] buffer = new byte [4096];
1711 int bytesReceived = socket.Receive (buffer);
1712 while (bytesReceived > 0) {
1713 ms.Write (buffer, 0, bytesReceived);
1714 // We don't check for Content-Length or anything else here, so we give the client a little time to write
1715 // after sending the headers
1717 if (socket.Available > 0) {
1718 bytesReceived = socket.Receive (buffer);
1725 string statusLine = null;
1726 bool have_auth = false;
1728 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
1730 while ((l = sr.ReadLine ()) != null) {
1731 if (statusLine == null) {
1733 } else if (l.StartsWith ("Authorization:")) {
1735 } else if (l.StartsWith ("Content-Length:")) {
1736 cl = Int32.Parse (l.Substring ("content-length: ".Length));
1741 StringWriter sw = new StringWriter ();
1743 sw.WriteLine ("HTTP/1.0 401 Invalid Credentials");
1744 sw.WriteLine ("WWW-Authenticate: basic Yeah");
1747 } else if (cl > 0 && statusLine.StartsWith ("POST ")) {
1748 sw.WriteLine ("HTTP/1.0 200 OK");
1749 sw.WriteLine ("Content-Type: text/plain");
1750 sw.WriteLine ("Content-Length: 8");
1752 sw.Write ("LOOKS OK");
1755 sw.WriteLine ("HTTP/1.0 500 test failed");
1756 sw.WriteLine ("Content-Length: 0");
1761 return Encoding.UTF8.GetBytes (sw.ToString ());
1764 public void NtlmAuthentication ()
1766 NtlmServer server = new NtlmServer ();
1769 string url = String.Format ("http://{0}:{1}/nothing.html", server.IPAddress, server.Port);
1770 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
1771 request.Timeout = 5000;
1772 request.Credentials = new NetworkCredential ("user", "password", "domain");
1773 HttpWebResponse resp = (HttpWebResponse) request.GetResponse ();
1775 using (StreamReader reader = new StreamReader (resp.GetResponseStream ())) {
1776 res = reader.ReadToEnd ();
1780 Assert.AreEqual ("OK", res);
1783 class NtlmServer : HttpServer {
1784 public string Where = "";
1785 protected override void Run ()
1787 Where = "before accept";
1788 Socket client = sock.Accept ();
1789 NetworkStream ns = new NetworkStream (client, false);
1790 StreamReader reader = new StreamReader (ns, Encoding.ASCII);
1792 Where = "first read";
1793 while ((line = reader.ReadLine ()) != null) {
1794 if (line.Trim () == String.Empty) {
1798 Where = "first write";
1799 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1800 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1801 "WWW-Authenticate: NTLM\r\n" +
1802 "Content-Length: 5\r\n\r\nWRONG");
1805 Where = "second read";
1806 while ((line = reader.ReadLine ()) != null) {
1807 if (line.Trim () == String.Empty) {
1811 Where = "second write";
1812 writer.Write ( "HTTP/1.1 401 Unauthorized\r\n" +
1813 "WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAADgAAAABggAC8GDhqIONH3sAAAAAAAAAAAAAAAA4AAAABQLODgAAAA8=\r\n" +
1814 "Content-Length: 5\r\n\r\nWRONG");
1817 Where = "third read";
1818 while ((line = reader.ReadLine ()) != null) {
1819 if (line.Trim () == String.Empty) {
1823 Where = "third write";
1824 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1825 "Keep-Alive: true\r\n" +
1826 "Content-Length: 2\r\n\r\nOK");
1828 Thread.Sleep (1000);
1835 class BadChunkedServer : HttpServer {
1836 protected override void Run ()
1838 Socket client = sock.Accept ();
1839 NetworkStream ns = new NetworkStream (client, true);
1840 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
1841 writer.Write ( "HTTP/1.1 200 OK\r\n" +
1842 "Transfer-Encoding: chunked\r\n" +
1843 "Connection: close\r\n" +
1844 "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
1846 // This body lacks a 'last-chunk' (see RFC 2616)
1847 writer.Write ("10\r\n1234567890123456\r\n");
1849 client.Shutdown (SocketShutdown.Send);
1850 Thread.Sleep (1000);
1855 class AcceptAllPolicy : ICertificatePolicy {
1856 public bool CheckValidationResult (ServicePoint sp, X509Certificate certificate, WebRequest request, int error)
1862 abstract class HttpServer
1864 protected Socket sock;
1865 protected Exception error;
1866 protected ManualResetEvent evt;
1868 public HttpServer ()
1870 sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
1871 sock.Bind (new IPEndPoint (IPAddress.Loopback, 0));
1875 public void Start ()
1877 evt = new ManualResetEvent (false);
1878 Thread th = new Thread (new ThreadStart (Run));
1888 public IPAddress IPAddress {
1889 get { return ((IPEndPoint) sock.LocalEndPoint).Address; }
1893 get { return ((IPEndPoint) sock.LocalEndPoint).Port; }
1896 public Exception Error {
1897 get { return error; }
1900 protected abstract void Run ();
1904 public void BeginGetRequestStream ()
1910 r.ContentLength = 0;
1911 r.BeginGetRequestStream ((a) =>
1913 using (Stream s = r.EndGetRequestStream (a)) { };
1922 public void BeginGetRequestStreamNoClose ()
1927 r.ContentLength = 1;
1928 r.BeginGetRequestStream ((a) =>
1930 r.EndGetRequestStream (a);
1939 public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
1945 r.ContentLength = 10;
1946 r.BeginGetRequestStream ((a) =>
1948 WebException ex = ExceptionAssert.Throws<WebException> (() =>
1950 using (Stream s = r.EndGetRequestStream (a)) {
1954 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1963 public void GetRequestStream2 ()
1969 r.ContentLength = data64KB.Length;
1970 using (Stream s = r.GetRequestStream ()) {
1971 s.Write (data64KB, 0, data64KB.Length);
1979 public void GetRequestStreamNotAllBytesWritten ()
1985 r.ContentLength = data64KB.Length;
1986 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ().Close ());
1987 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
1994 public void GetRequestStreamTimeout ()
2000 r.ContentLength = data64KB.Length;
2002 WebException ex = ExceptionAssert.Throws<WebException> (() => r.GetRequestStream ());
2003 Assert.IsTrue (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ConnectFailure);
2009 public void BeginWrite ()
2011 byte[] received = new byte[data64KB.Length];
2017 r.ContentLength = data64KB.Length;
2019 Stream s = r.GetRequestStream ();
2020 s.BeginWrite (data64KB, 0, data64KB.Length,
2025 r.GetResponse ().Close ();
2032 c.Request.InputStream.ReadAll (received, 0, received.Length);
2033 c.Response.StatusCode = 204;
2034 c.Response.Close ();
2037 Assert.AreEqual (data64KB, received);
2041 public void BeginWriteAfterAbort ()
2043 byte [] received = new byte [data64KB.Length];
2049 r.ContentLength = data64KB.Length;
2051 Stream s = r.GetRequestStream ();
2054 WebException ex = ExceptionAssert.Throws<WebException> (() => s.BeginWrite (data64KB, 0, data64KB.Length, null, null));
2055 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2061 //c.Request.InputStream.ReadAll (received, 0, received.Length);
2062 //c.Response.StatusCode = 204;
2063 //c.Response.Close();
2068 public void PrematureStreamCloseAborts ()
2070 byte [] received = new byte [data64KB.Length];
2076 r.ContentLength = data64KB.Length * 2;
2078 Stream s = r.GetRequestStream ();
2079 s.Write (data64KB, 0, data64KB.Length);
2081 WebException ex = ExceptionAssert.Throws<WebException>(() => s.Close());
2082 Assert.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled);
2088 c.Request.InputStream.ReadAll (received, 0, received.Length);
2089 // c.Response.StatusCode = 204;
2090 // c.Response.Close ();
2095 public void Write ()
2097 byte [] received = new byte [data64KB.Length];
2103 r.ContentLength = data64KB.Length;
2105 using (Stream s = r.GetRequestStream ()) {
2106 s.Write (data64KB, 0, data64KB.Length);
2109 r.GetResponse ().Close ();
2114 c.Request.InputStream.ReadAll (received, 0, received.Length);
2115 c.Response.StatusCode = 204;
2116 c.Response.Close ();
2119 Assert.AreEqual(data64KB, received);
2123 Invalid test: it does not work on linux.
2124 [pid 30973] send(9, "POST / HTTP/1.1\r\nContent-Length:"..., 89, 0) = 89
2126 [pid 30970] send(16, "HTTP/1.1 200 OK\r\nServer: Mono-HT"..., 133, 0) = 133
2128 [pid 30970] close(16) = 0
2130 [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
2132 [pid 30966] close(4) = 0
2135 The server sideis closed (FD 16) and the send on the client side (FD 9) succeeds.
2137 [Category("NotWorking")]
2138 public void WriteServerAborts ()
2140 ManualResetEvent abort = new ManualResetEvent (false);
2141 byte [] received = new byte [data64KB.Length];
2147 r.ContentLength = data64KB.Length;
2149 using (Stream s = r.GetRequestStream()) {
2152 IOException ex = ExceptionAssert.Throws<IOException> (() => s.Write(data64KB, 0, data64KB.Length));
2168 byte [] received = new byte [data64KB.Length];
2173 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2174 using (Stream s = x.GetResponseStream()) {
2175 s.ReadAll (received, 0, received.Length);
2182 c.Response.StatusCode = 200;
2183 c.Response.ContentLength64 = data64KB.Length;
2184 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2185 c.Response.OutputStream.Close ();
2186 c.Response.Close ();
2189 Assert.AreEqual (data64KB, received);
2193 public void ReadTimeout2 ()
2195 byte [] received = new byte [data64KB.Length];
2200 r.ReadWriteTimeout = 10;
2201 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2202 using (Stream s = x.GetResponseStream ()) {
2203 WebException ex = ExceptionAssert.Throws<WebException> (() => s.ReadAll (received, 0, received.Length));
2204 Assert.AreEqual (ex.Status, WebExceptionStatus.Timeout);
2211 c.Response.StatusCode = 200;
2212 c.Response.ContentLength64 = data64KB.Length;
2213 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length / 2);
2214 Thread.Sleep (1000);
2215 // c.Response.OutputStream.Write (data64KB, data64KB.Length / 2, data64KB.Length / 2);
2216 c.Response.OutputStream.Close ();
2217 c.Response.Close ();
2222 public void ReadServerAborted ()
2224 byte [] received = new byte [data64KB.Length];
2229 using (HttpWebResponse x = (HttpWebResponse) r.GetResponse ())
2230 using (Stream s = x.GetResponseStream ()) {
2231 Assert.AreEqual (1, s.ReadAll (received, 0, received.Length));
2238 c.Response.StatusCode = 200;
2239 c.Response.ContentLength64 = data64KB.Length;
2240 c.Response.OutputStream.Write (data64KB, 0, 1);
2241 c.Response.Abort ();
2246 public void BeginGetResponse2 ()
2248 byte [] received = new byte [data64KB.Length];
2253 r.BeginGetResponse ((a) =>
2255 using (HttpWebResponse x = (HttpWebResponse) r.EndGetResponse (a))
2256 using (Stream s = x.GetResponseStream ()) {
2257 s.ReadAll (received, 0, received.Length);
2265 c.Response.StatusCode = 200;
2266 c.Response.ContentLength64 = data64KB.Length;
2267 c.Response.OutputStream.Write (data64KB, 0, data64KB.Length);
2268 c.Response.OutputStream.Close ();
2269 c.Response.Close ();
2272 Assert.AreEqual (data64KB, received);
2276 public void BeginGetResponseAborts ()
2278 ManualResetEvent aborted = new ManualResetEvent(false);
2283 r.BeginGetResponse((a) =>
2285 WebException ex = ExceptionAssert.Throws<WebException> (() => r.EndGetResponse (a));
2286 Assert.AreEqual (ex.Status, WebExceptionStatus.RequestCanceled);
2296 // Thread.Sleep (100);
2297 // c.Response.StatusCode = 200;
2298 // c.Response.ContentLength64 = 0;
2299 // c.Response.Close ();
2305 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request)
2307 int port = NetworkHelpers.FindFreePort ();
2309 ManualResetEvent completed = new ManualResetEvent (false);
2310 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2311 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2313 request (client, completed);
2315 if (!completed.WaitOne (10000))
2316 Assert.Fail ("Test hung");
2319 void DoRequest (Action<HttpWebRequest, EventWaitHandle> request, Action<HttpListenerContext> processor)
2321 int port = NetworkHelpers.FindFreePort ();
2323 ManualResetEvent [] completed = new ManualResetEvent [2];
2324 completed [0] = new ManualResetEvent (false);
2325 completed [1] = new ManualResetEvent (false);
2327 using (ListenerScope scope = new ListenerScope (processor, port, completed [0])) {
2328 ManualResetEvent clientCompleted = new ManualResetEvent (false);
2329 Uri address = new Uri (string.Format ("http://localhost:{0}", port));
2330 HttpWebRequest client = (HttpWebRequest) WebRequest.Create (address);
2332 ThreadPool.QueueUserWorkItem ((o) => request (client, completed [1]));
2334 if (!WaitHandle.WaitAll (completed, 10000))
2335 Assert.Fail ("Test hung.");
2341 [ExpectedException (typeof (ArgumentNullException))]
2342 public void NullHost ()
2344 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2349 public void NoHost ()
2351 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2352 Assert.AreEqual (req.Host, "go-mono.com");
2356 [ExpectedException (typeof (ArgumentException))]
2357 public void EmptyHost ()
2359 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2364 public void HostAndPort ()
2366 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
2367 Assert.AreEqual ("go-mono.com", req.Host, "#01");
2368 req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
2369 Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
2373 public void PortRange ()
2375 for (int i = 0; i < 65536; i++) {
2378 string s = i.ToString ();
2379 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
2380 Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
2385 [ExpectedException (typeof (ArgumentException))]
2386 public void PortBelow ()
2388 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2389 req.Host = "go-mono.com:-1";
2393 [ExpectedException (typeof (ArgumentException))]
2394 public void PortAbove ()
2396 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2397 req.Host = "go-mono.com:65536";
2401 [ExpectedException (typeof (ArgumentException))]
2402 public void HostTooLong ()
2404 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2405 string s = new string ('a', 100);
2406 req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
2410 [Category ("NotWorking")] // #5490
2411 public void InvalidNamesThatWork ()
2413 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2417 req.Host = new string ('a', 64); // Should fail. Max. is 63.
2421 public void NoDate ()
2423 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2424 Assert.AreEqual (DateTime.MinValue, req.Date);
2428 public void UtcDate ()
2430 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2431 req.Date = DateTime.UtcNow;
2432 DateTime date = req.Date;
2433 Assert.AreEqual (DateTimeKind.Local, date.Kind);
2437 public void AddAndRemoveDate ()
2439 // Neil Armstrong set his foot on Moon
2440 var landing = new DateTime (1969, 7, 21, 2, 56, 0, DateTimeKind.Utc);
2441 Assert.AreEqual (621214377600000000, landing.Ticks);
2442 var unspecified = new DateTime (1969, 7, 21, 2, 56, 0);
2443 var local = landing.ToLocalTime ();
2445 var req = (HttpWebRequest)WebRequest.Create ("http://www.mono-project.com/");
2447 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2448 Assert.AreEqual (local.Ticks, req.Date.Ticks);
2449 Assert.AreEqual (local, req.Date);
2451 req.Date = unspecified;
2452 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2453 Assert.AreEqual (unspecified.Ticks, req.Date.Ticks);
2454 Assert.AreEqual (unspecified, req.Date);
2457 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2458 Assert.AreEqual (local.Ticks, req.Date.Ticks);
2459 Assert.AreEqual (local, req.Date);
2461 req.Date = DateTime.MinValue;
2462 Assert.AreEqual (DateTimeKind.Unspecified, DateTime.MinValue.Kind);
2463 Assert.AreEqual (DateTimeKind.Unspecified, req.Date.Kind);
2464 Assert.AreEqual (0, req.Date.Ticks);
2466 Assert.AreEqual (null, req.Headers.Get ("Date"));
2471 public void TestIPv6Host ()
2473 var address = "2001:0000:0000:0001:0001:0001:0157:0000";
2474 var address2 = '[' + address + ']';
2475 var uri = new Uri (string.Format ("http://{0}/test.css", address2));
2476 var hwr = (HttpWebRequest)WebRequest.Create (uri);
2478 hwr.Host = address2;
2479 Assert.AreEqual (address2, hwr.Host, "#1");
2484 [Category ("NotWorking")]
2485 public void TestIPv6Host2 ()
2487 var address = "2001:0000:0000:0001:0001:0001:0157:0000";
2488 var address2 = '[' + address + ']';
2489 var uri = new Uri (string.Format ("http://{0}/test.css", address2));
2490 var hwr = (HttpWebRequest)WebRequest.Create (uri);
2495 } catch (ArgumentException) {
2503 public void AllowReadStreamBuffering ()
2505 var hr = WebRequest.CreateHttp ("http://www.google.com");
2506 Assert.IsFalse (hr.AllowReadStreamBuffering, "#1");
2508 hr.AllowReadStreamBuffering = true;
2510 } catch (InvalidOperationException) {
2515 class ListenerScope : IDisposable {
2516 EventWaitHandle completed;
2517 public HttpListener listener;
2518 Action<HttpListenerContext> processor;
2520 public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
2522 this.processor = processor;
2523 this.completed = completed;
2525 this.listener = new HttpListener ();
2526 this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
2527 this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
2528 this.listener.Start ();
2530 this.listener.BeginGetContext (this.RequestHandler, null);
2533 void RequestHandler (IAsyncResult result)
2535 HttpListenerContext context = null;
2538 context = this.listener.EndGetContext (result);
2539 } catch (HttpListenerException ex) {
2540 // check if the thread has been aborted as in the case when we are shutting down.
2541 if (ex.ErrorCode == 995)
2543 } catch (ObjectDisposedException) {
2547 ThreadPool.QueueUserWorkItem ((o) =>
2550 this.processor (context);
2551 } catch (HttpListenerException) {
2555 this.completed.Set ();
2558 public void Dispose ()
2560 this.listener.Stop ();
2565 class SslHttpServer : HttpServer {
2566 X509Certificate _certificate;
2568 protected override void Run ()
2571 Socket client = sock.Accept ();
2572 NetworkStream ns = new NetworkStream (client, true);
2573 SslServerStream s = new SslServerStream (ns, Certificate, false, false);
2574 s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
2576 StreamReader reader = new StreamReader (s);
2577 StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
2580 string hello = "<html><body><h1>Hello World!</h1></body></html>";
2581 string answer = "HTTP/1.0 200\r\n" +
2582 "Connection: close\r\n" +
2583 "Content-Type: text/html\r\n" +
2584 "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
2585 "Content-Length: " + hello.Length + "\r\n" +
2590 line = reader.ReadLine ();
2591 } while (line != "" && line != null && line.Length > 0);
2593 // Now the content. We know it's 100 bytes.
2594 // This makes BeginRead in sslclientstream block.
2595 char [] cs = new char [100];
2596 reader.Read (cs, 0, 100);
2598 writer.Write (answer);
2600 if (evt.WaitOne (5000, false))
2601 error = new Exception ("Timeout when stopping the server");
2602 } catch (Exception e) {
2607 X509Certificate Certificate {
2609 if (_certificate == null)
2610 _certificate = new X509Certificate (CertData.Certificate);
2612 return _certificate;
2616 AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
2618 PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
2624 public readonly static byte [] Certificate = {
2625 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
2626 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
2627 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
2628 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
2629 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
2630 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
2631 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
2632 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
2633 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
2634 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
2635 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
2636 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
2637 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
2638 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
2639 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
2640 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
2641 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
2642 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
2643 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
2644 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
2645 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
2646 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
2647 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
2648 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
2649 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
2650 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
2651 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
2652 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
2656 public readonly static byte [] PrivateKey = {
2657 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
2658 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
2659 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
2660 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
2661 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
2662 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
2663 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
2664 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
2665 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
2666 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
2667 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
2668 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
2669 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
2670 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
2671 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
2672 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
2673 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
2674 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
2675 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
2676 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
2677 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
2678 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
2679 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
2680 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
2681 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
2682 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
2683 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
2684 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
2685 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
2686 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
2687 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
2688 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
2689 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
2690 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
2691 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
2692 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
2693 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
2694 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
2695 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
2701 public void CookieContainerTest ()
2703 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2704 string url = "http://" + ep.ToString ();
2706 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (CookieRequestHandler))) {
2709 CookieContainer container = new CookieContainer ();
2710 container.Add(new Uri (url), new Cookie ("foo", "bar"));
2711 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
2712 request.CookieContainer = container;
2713 WebHeaderCollection headers = request.Headers;
2714 headers.Add("Cookie", "foo=baz");
2715 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
2716 string responseString = null;
2717 using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
2718 responseString = reader.ReadToEnd ();
2721 Assert.AreEqual (1, response.Cookies.Count, "#01");
2722 Assert.AreEqual ("foo=bar", response.Headers.Get("Set-Cookie"), "#02");
2725 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (CookieRequestHandler))) {
2728 CookieContainer container = new CookieContainer ();
2729 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
2730 request.CookieContainer = container;
2731 WebHeaderCollection headers = request.Headers;
2732 headers.Add("Cookie", "foo=baz");
2733 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
2734 string responseString = null;
2735 using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
2736 responseString = reader.ReadToEnd ();
2739 Assert.AreEqual (0, response.Cookies.Count, "#03");
2740 Assert.AreEqual ("", response.Headers.Get("Set-Cookie"), "#04");
2744 internal static byte[] CookieRequestHandler (Socket socket)
2746 MemoryStream ms = new MemoryStream ();
2747 byte[] buffer = new byte[4096];
2748 int bytesReceived = socket.Receive (buffer);
2749 while (bytesReceived > 0) {
2750 ms.Write(buffer, 0, bytesReceived);
2751 // We don't check for Content-Length or anything else here, so we give the client a little time to write
2752 // after sending the headers
2754 if (socket.Available > 0) {
2755 bytesReceived = socket.Receive (buffer);
2762 string cookies = string.Empty;
2763 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
2765 while ((line = sr.ReadLine ()) != null) {
2766 if (line.StartsWith ("Cookie:")) {
2767 cookies = line.Substring ("cookie: ".Length);
2772 StringWriter sw = new StringWriter ();
2773 sw.WriteLine ("HTTP/1.1 200 OK");
2774 sw.WriteLine ("Content-Type: text/xml");
2775 sw.WriteLine ("Set-Cookie: " + cookies);
2776 sw.WriteLine ("Content-Length: " + cookies.Length.ToString (CultureInfo.InvariantCulture));
2781 return Encoding.UTF8.GetBytes (sw.ToString ());
2786 public class HttpRequestStreamTest
2789 public void BeginRead ()
2791 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2792 string url = "http://" + ep.ToString () + "/test/";
2794 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2797 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2798 req.Method = "POST";
2800 using (Stream rs = req.GetRequestStream ()) {
2801 byte [] buffer = new byte [10];
2803 rs.BeginRead (buffer, 0, buffer.Length, null, null);
2805 } catch (NotSupportedException ex) {
2806 // The stream does not support reading
2807 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2808 Assert.IsNull (ex.InnerException, "#3");
2809 Assert.IsNotNull (ex.Message, "#4");
2818 [Category("MobileNotWorking")]
2819 public void BeginWrite_Request_Aborted ()
2821 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2822 string url = "http://" + ep.ToString () + "/test/";
2824 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2827 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2828 req.Method = "POST";
2830 using (Stream rs = req.GetRequestStream ()) {
2833 rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
2835 } catch (WebException ex) {
2836 // The request was aborted: The request was canceled
2837 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2838 Assert.IsNull (ex.InnerException, "#3");
2839 Assert.IsNotNull (ex.Message, "#4");
2840 Assert.IsNull (ex.Response, "#5");
2841 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2848 public void CanRead ()
2850 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2851 string url = "http://" + ep.ToString () + "/test/";
2853 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2856 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2857 req.Method = "POST";
2859 Stream rs = req.GetRequestStream ();
2861 Assert.IsFalse (rs.CanRead, "#1");
2863 Assert.IsFalse (rs.CanRead, "#2");
2872 public void CanSeek ()
2874 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2875 string url = "http://" + ep.ToString () + "/test/";
2877 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2880 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2881 req.Method = "POST";
2883 Stream rs = req.GetRequestStream ();
2885 Assert.IsFalse (rs.CanSeek, "#1");
2887 Assert.IsFalse (rs.CanSeek, "#2");
2895 [Test] // bug #324182
2896 public void CanTimeout ()
2898 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2899 string url = "http://" + ep.ToString () + "/test/";
2901 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2904 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2905 req.Method = "POST";
2907 Stream rs = req.GetRequestStream ();
2909 Assert.IsTrue (rs.CanTimeout, "#1");
2911 Assert.IsTrue (rs.CanTimeout, "#2");
2920 public void CanWrite ()
2922 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2923 string url = "http://" + ep.ToString () + "/test/";
2925 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2928 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2929 req.Method = "POST";
2931 Stream rs = req.GetRequestStream ();
2933 Assert.IsTrue (rs.CanWrite, "#1");
2935 Assert.IsFalse (rs.CanWrite, "#2");
2946 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2947 string url = "http://" + ep.ToString () + "/test/";
2949 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2952 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2953 req.Method = "POST";
2955 using (Stream rs = req.GetRequestStream ()) {
2956 byte [] buffer = new byte [10];
2958 rs.Read (buffer, 0, buffer.Length);
2960 } catch (NotSupportedException ex) {
2961 // The stream does not support reading
2962 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2963 Assert.IsNull (ex.InnerException, "#3");
2964 Assert.IsNotNull (ex.Message, "#4");
2973 public void ReadByte ()
2975 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2976 string url = "http://" + ep.ToString () + "/test/";
2978 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2981 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2982 req.Method = "POST";
2984 using (Stream rs = req.GetRequestStream ()) {
2988 } catch (NotSupportedException ex) {
2989 // The stream does not support reading
2990 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2991 Assert.IsNull (ex.InnerException, "#3");
2992 Assert.IsNotNull (ex.Message, "#4");
3001 public void ReadTimeout ()
3003 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3004 string url = "http://" + ep.ToString () + "/test/";
3006 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3009 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3010 req.Method = "POST";
3012 Stream rs = req.GetRequestStream ();
3014 Assert.AreEqual (300000, rs.ReadTimeout, "#1");
3016 Assert.AreEqual (300000, rs.ReadTimeout, "#2");
3027 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3028 string url = "http://" + ep.ToString () + "/test/";
3030 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3033 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3034 req.Method = "POST";
3036 using (Stream rs = req.GetRequestStream ()) {
3038 rs.Seek (0, SeekOrigin.Current);
3040 } catch (NotSupportedException ex) {
3041 // This stream does not support seek operations
3042 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
3043 Assert.IsNull (ex.InnerException, "#3");
3044 Assert.IsNotNull (ex.Message, "#4");
3053 public void Write_Buffer_Null ()
3055 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3056 string url = "http://" + ep.ToString () + "/test/";
3058 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3061 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3062 req.Method = "POST";
3064 using (Stream rs = req.GetRequestStream ()) {
3066 rs.Write ((byte []) null, -1, -1);
3068 } catch (ArgumentNullException ex) {
3069 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3070 Assert.IsNull (ex.InnerException, "#3");
3071 Assert.IsNotNull (ex.Message, "#4");
3072 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3081 public void Write_Count_Negative ()
3083 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3084 string url = "http://" + ep.ToString () + "/test/";
3086 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3089 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3090 req.Method = "POST";
3092 using (Stream rs = req.GetRequestStream ()) {
3093 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3095 rs.Write (buffer, 1, -1);
3097 } catch (ArgumentOutOfRangeException ex) {
3098 // Specified argument was out of the range of valid values
3099 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3100 Assert.IsNull (ex.InnerException, "#A3");
3101 Assert.IsNotNull (ex.Message, "#A4");
3102 Assert.AreEqual ("size", ex.ParamName, "#A5");
3111 public void Write_Count_Overflow ()
3113 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3114 string url = "http://" + ep.ToString () + "/test/";
3116 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3119 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3120 req.Method = "POST";
3122 using (Stream rs = req.GetRequestStream ()) {
3123 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3125 rs.Write (buffer, buffer.Length - 2, 3);
3127 } catch (ArgumentOutOfRangeException ex) {
3128 // Specified argument was out of the range of valid values
3129 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3130 Assert.IsNull (ex.InnerException, "#3");
3131 Assert.IsNotNull (ex.Message, "#4");
3132 Assert.AreEqual ("size", ex.ParamName, "#5");
3141 public void Write_Offset_Negative ()
3143 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3144 string url = "http://" + ep.ToString () + "/test/";
3146 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3149 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3150 req.Method = "POST";
3152 using (Stream rs = req.GetRequestStream ()) {
3153 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3155 rs.Write (buffer, -1, 0);
3157 } catch (ArgumentOutOfRangeException ex) {
3158 // Specified argument was out of the range of valid values
3159 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3160 Assert.IsNull (ex.InnerException, "#3");
3161 Assert.IsNotNull (ex.Message, "#4");
3162 Assert.AreEqual ("offset", ex.ParamName, "#5");
3171 public void Write_Offset_Overflow ()
3173 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3174 string url = "http://" + ep.ToString () + "/test/";
3176 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3179 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3180 req.Method = "POST";
3182 using (Stream rs = req.GetRequestStream ()) {
3183 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3185 rs.Write (buffer, buffer.Length + 1, 0);
3187 } catch (ArgumentOutOfRangeException ex) {
3188 // Specified argument was out of the range of valid values
3189 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3190 Assert.IsNull (ex.InnerException, "#3");
3191 Assert.IsNotNull (ex.Message, "#4");
3192 Assert.AreEqual ("offset", ex.ParamName, "#5");
3201 public void Write_Request_Aborted ()
3203 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3204 string url = "http://" + ep.ToString () + "/test/";
3206 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3209 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3210 req.Method = "POST";
3212 using (Stream rs = req.GetRequestStream ()) {
3215 rs.Write (new byte [0], 0, 0);
3217 } catch (WebException ex) {
3218 // The request was aborted: The request was canceled
3219 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3220 Assert.IsNull (ex.InnerException, "#3");
3221 Assert.IsNotNull (ex.Message, "#4");
3222 Assert.IsNull (ex.Response, "#5");
3223 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3230 [Category ("NotWorking")]
3231 public void Write_Stream_Closed ()
3233 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3234 string url = "http://" + ep.ToString () + "/test/";
3236 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3239 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3240 req.Method = "POST";
3242 using (Stream rs = req.GetRequestStream ()) {
3245 rs.Write (new byte [0], 0, 0);
3247 } catch (WebException ex) {
3248 // The request was aborted: The connection was closed unexpectedly
3249 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3250 Assert.IsNull (ex.InnerException, "#3");
3251 Assert.IsNotNull (ex.Message, "#4");
3252 Assert.IsNull (ex.Response, "#5");
3253 Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
3260 public void WriteByte_Request_Aborted ()
3262 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3263 string url = "http://" + ep.ToString () + "/test/";
3265 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3268 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3269 req.Method = "POST";
3271 using (Stream rs = req.GetRequestStream ()) {
3274 rs.WriteByte (0x2a);
3276 } catch (WebException ex) {
3277 // The request was aborted: The request was canceled
3278 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3279 Assert.IsNull (ex.InnerException, "#3");
3280 Assert.IsNotNull (ex.Message, "#4");
3281 Assert.IsNull (ex.Response, "#5");
3282 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3289 public void WriteTimeout ()
3291 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3292 string url = "http://" + ep.ToString () + "/test/";
3294 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3297 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3298 req.Method = "POST";
3300 Stream rs = req.GetRequestStream ();
3302 Assert.AreEqual (300000, rs.WriteTimeout, "#1");
3304 Assert.AreEqual (300000, rs.WriteTimeout, "#2");
3315 // This test is supposed to fail prior to .NET 4.0
3316 public void Post_EmptyRequestStream ()
3318 var wr = HttpWebRequest.Create ("http://google.com");
3320 wr.GetRequestStream ();
3322 var gr = wr.BeginGetResponse (delegate { }, null);
3323 Assert.AreEqual (true, gr.AsyncWaitHandle.WaitOne (5000), "#1");
3328 static class StreamExtensions {
3329 public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
3333 while (totalRead < count) {
3334 int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
3338 totalRead += bytesRead;
3345 static class ExceptionAssert {
3347 /// Asserts that the function throws an exception.
3349 /// <param name="f">A function execute that is expected to raise an exception.</param>
3350 /// <typeparam name="T">The type of exception that is expected.</typeparam>
3351 /// <returns>The exception thrown.</returns>
3352 /// <exception cref="AssertFailedException">If the function does not throw an exception
3353 /// or throws a different exception.</exception>
3354 /// <example><![CDATA[
3355 /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
3356 /// myObject.myFunction(null); });
3358 public static T Throws<T> (Action f) where T : Exception {
3359 Exception actualException = null;
3363 } catch (Exception ex) {
3364 actualException = ex;
3367 if (actualException == null)
3368 throw new AssertionException (string.Format (
3369 "No exception thrown. Expected '{0}'",
3370 typeof (T).FullName));
3371 else if (typeof(T) != actualException.GetType())
3372 throw new AssertionException (string.Format (
3373 "Caught exception of type '{0}'. Expected '{1}':{2}",
3374 actualException.GetType().FullName,
3375 typeof (T).FullName,
3376 Environment.NewLine + actualException));
3378 return (T) actualException;