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.");
2340 [ExpectedException (typeof (ArgumentNullException))]
2341 public void NullHost ()
2343 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2348 public void NoHost ()
2350 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2351 Assert.AreEqual (req.Host, "go-mono.com");
2355 [ExpectedException (typeof (ArgumentException))]
2356 public void EmptyHost ()
2358 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2363 public void HostAndPort ()
2365 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
2366 Assert.AreEqual ("go-mono.com", req.Host, "#01");
2367 req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:9000");
2368 Assert.AreEqual ("go-mono.com:9000", req.Host, "#02");
2372 public void PortRange ()
2374 for (int i = 0; i < 65536; i++) {
2377 string s = i.ToString ();
2378 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:" + s);
2379 Assert.AreEqual ("go-mono.com:" + s, req.Host, "#" + s);
2384 [ExpectedException (typeof (ArgumentException))]
2385 public void PortBelow ()
2387 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2388 req.Host = "go-mono.com:-1";
2392 [ExpectedException (typeof (ArgumentException))]
2393 public void PortAbove ()
2395 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2396 req.Host = "go-mono.com:65536";
2400 [ExpectedException (typeof (ArgumentException))]
2401 public void HostTooLong ()
2403 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2404 string s = new string ('a', 100);
2405 req.Host = s + "." + s + "." + s + "." + s + "." + s + "." + s; // Over 255 bytes
2409 [Category ("NotWorking")] // #5490
2410 public void InvalidNamesThatWork ()
2412 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2416 req.Host = new string ('a', 64); // Should fail. Max. is 63.
2420 public void NoDate ()
2422 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2423 Assert.AreEqual (DateTime.MinValue, req.Date);
2427 public void UtcDate ()
2429 HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
2430 req.Date = DateTime.UtcNow;
2431 DateTime date = req.Date;
2432 Assert.AreEqual (DateTimeKind.Local, date.Kind);
2436 public void AddAndRemoveDate ()
2438 // Neil Armstrong set his foot on Moon
2439 var landing = new DateTime (1969, 7, 21, 2, 56, 0, DateTimeKind.Utc);
2440 Assert.AreEqual (621214377600000000, landing.Ticks);
2441 var unspecified = new DateTime (1969, 7, 21, 2, 56, 0);
2442 var local = landing.ToLocalTime ();
2444 var req = (HttpWebRequest)WebRequest.Create ("http://www.mono-project.com/");
2446 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2447 Assert.AreEqual (local.Ticks, req.Date.Ticks);
2448 Assert.AreEqual (local, req.Date);
2450 req.Date = unspecified;
2451 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2452 Assert.AreEqual (unspecified.Ticks, req.Date.Ticks);
2453 Assert.AreEqual (unspecified, req.Date);
2456 Assert.AreEqual (DateTimeKind.Local, req.Date.Kind);
2457 Assert.AreEqual (local.Ticks, req.Date.Ticks);
2458 Assert.AreEqual (local, req.Date);
2460 req.Date = DateTime.MinValue;
2461 Assert.AreEqual (DateTimeKind.Unspecified, DateTime.MinValue.Kind);
2462 Assert.AreEqual (DateTimeKind.Unspecified, req.Date.Kind);
2463 Assert.AreEqual (0, req.Date.Ticks);
2465 Assert.AreEqual (null, req.Headers.Get ("Date"));
2470 public void TestIPv6Host ()
2472 var address = "2001:0000:0000:0001:0001:0001:0157:0000";
2473 var address2 = '[' + address + ']';
2474 var uri = new Uri (string.Format ("http://{0}/test.css", address2));
2475 var hwr = (HttpWebRequest)WebRequest.Create (uri);
2477 hwr.Host = address2;
2478 Assert.AreEqual (address2, hwr.Host, "#1");
2483 [Category ("NotWorking")]
2484 public void TestIPv6Host2 ()
2486 var address = "2001:0000:0000:0001:0001:0001:0157:0000";
2487 var address2 = '[' + address + ']';
2488 var uri = new Uri (string.Format ("http://{0}/test.css", address2));
2489 var hwr = (HttpWebRequest)WebRequest.Create (uri);
2494 } catch (ArgumentException) {
2501 public void AllowReadStreamBuffering ()
2503 var hr = WebRequest.CreateHttp ("http://www.google.com");
2504 Assert.IsFalse (hr.AllowReadStreamBuffering, "#1");
2506 hr.AllowReadStreamBuffering = true;
2508 } catch (InvalidOperationException) {
2513 class ListenerScope : IDisposable {
2514 EventWaitHandle completed;
2515 public HttpListener listener;
2516 Action<HttpListenerContext> processor;
2518 public ListenerScope (Action<HttpListenerContext> processor, int port, EventWaitHandle completed)
2520 this.processor = processor;
2521 this.completed = completed;
2523 this.listener = new HttpListener ();
2524 this.listener.Prefixes.Add (string.Format ("http://localhost:{0}/", port));
2525 this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
2526 this.listener.Start ();
2528 this.listener.BeginGetContext (this.RequestHandler, null);
2531 void RequestHandler (IAsyncResult result)
2533 HttpListenerContext context = null;
2536 context = this.listener.EndGetContext (result);
2537 } catch (HttpListenerException ex) {
2538 // check if the thread has been aborted as in the case when we are shutting down.
2539 if (ex.ErrorCode == 995)
2541 } catch (ObjectDisposedException) {
2545 ThreadPool.QueueUserWorkItem ((o) =>
2548 this.processor (context);
2549 } catch (HttpListenerException) {
2553 this.completed.Set ();
2556 public void Dispose ()
2558 this.listener.Stop ();
2563 class SslHttpServer : HttpServer {
2564 X509Certificate _certificate;
2566 protected override void Run ()
2569 Socket client = sock.Accept ();
2570 NetworkStream ns = new NetworkStream (client, true);
2571 SslServerStream s = new SslServerStream (ns, Certificate, false, false);
2572 s.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (GetPrivateKey);
2574 StreamReader reader = new StreamReader (s);
2575 StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
2578 string hello = "<html><body><h1>Hello World!</h1></body></html>";
2579 string answer = "HTTP/1.0 200\r\n" +
2580 "Connection: close\r\n" +
2581 "Content-Type: text/html\r\n" +
2582 "Content-Encoding: " + Encoding.ASCII.WebName + "\r\n" +
2583 "Content-Length: " + hello.Length + "\r\n" +
2588 line = reader.ReadLine ();
2589 } while (line != "" && line != null && line.Length > 0);
2591 // Now the content. We know it's 100 bytes.
2592 // This makes BeginRead in sslclientstream block.
2593 char [] cs = new char [100];
2594 reader.Read (cs, 0, 100);
2596 writer.Write (answer);
2598 if (evt.WaitOne (5000, false))
2599 error = new Exception ("Timeout when stopping the server");
2600 } catch (Exception e) {
2605 X509Certificate Certificate {
2607 if (_certificate == null)
2608 _certificate = new X509Certificate (CertData.Certificate);
2610 return _certificate;
2614 AsymmetricAlgorithm GetPrivateKey (X509Certificate certificate, string targetHost)
2616 PrivateKey key = new PrivateKey (CertData.PrivateKey, null);
2622 public readonly static byte [] Certificate = {
2623 48, 130, 1, 191, 48, 130, 1, 40, 160, 3, 2, 1, 2, 2, 16, 36,
2624 14, 97, 190, 146, 132, 208, 71, 175, 6, 87, 168, 185, 175, 55, 43, 48,
2625 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 48, 18,
2626 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103, 111, 110, 122, 97,
2627 108, 111, 48, 30, 23, 13, 48, 53, 48, 54, 50, 50, 49, 57, 51, 48,
2628 52, 54, 90, 23, 13, 51, 57, 49, 50, 51, 49, 50, 51, 53, 57, 53,
2629 57, 90, 48, 18, 49, 16, 48, 14, 6, 3, 85, 4, 3, 19, 7, 103,
2630 111, 110, 122, 97, 108, 111, 48, 129, 158, 48, 13, 6, 9, 42, 134, 72,
2631 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 140, 0, 48, 129, 136, 2,
2632 129, 129, 0, 138, 9, 38, 25, 166, 252, 59, 26, 39, 184, 128, 216, 38,
2633 73, 41, 86, 30, 228, 160, 205, 41, 135, 115, 223, 44, 62, 42, 198, 178,
2634 190, 81, 11, 25, 21, 216, 49, 179, 130, 246, 52, 97, 175, 212, 94, 157,
2635 231, 162, 66, 161, 103, 63, 204, 83, 141, 172, 119, 97, 225, 206, 98, 101,
2636 210, 106, 2, 206, 81, 90, 173, 47, 41, 199, 209, 241, 177, 177, 96, 207,
2637 254, 220, 190, 66, 180, 153, 0, 209, 14, 178, 69, 194, 3, 37, 116, 239,
2638 49, 23, 185, 245, 255, 126, 35, 85, 246, 56, 244, 107, 117, 24, 14, 57,
2639 9, 111, 147, 189, 220, 142, 57, 104, 153, 193, 205, 19, 14, 22, 157, 16,
2640 24, 80, 201, 2, 2, 0, 17, 163, 23, 48, 21, 48, 19, 6, 3, 85,
2641 29, 37, 4, 12, 48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1,
2642 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 4, 5, 0, 3,
2643 129, 129, 0, 64, 49, 57, 253, 218, 198, 229, 51, 189, 12, 154, 225, 183,
2644 160, 147, 90, 113, 172, 69, 122, 28, 77, 97, 215, 231, 194, 150, 29, 196,
2645 65, 95, 218, 99, 142, 111, 79, 205, 109, 76, 32, 92, 220, 76, 88, 53,
2646 237, 80, 11, 85, 44, 91, 21, 210, 12, 34, 223, 234, 18, 187, 136, 62,
2647 26, 240, 103, 180, 12, 226, 221, 250, 247, 129, 51, 23, 129, 165, 56, 67,
2648 43, 83, 244, 110, 207, 24, 253, 195, 16, 46, 80, 113, 80, 18, 2, 254,
2649 120, 147, 151, 164, 23, 210, 230, 100, 19, 197, 179, 28, 194, 48, 106, 159,
2650 155, 144, 37, 82, 44, 160, 40, 52, 146, 174, 77, 188, 160, 230, 75, 172,
2654 public readonly static byte [] PrivateKey = {
2655 30, 241, 181, 176, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
2656 0, 0, 0, 0, 84, 2, 0, 0, 7, 2, 0, 0, 0, 36, 0, 0,
2657 82, 83, 65, 50, 0, 4, 0, 0, 17, 0, 0, 0, 201, 80, 24, 16,
2658 157, 22, 14, 19, 205, 193, 153, 104, 57, 142, 220, 189, 147, 111, 9, 57,
2659 14, 24, 117, 107, 244, 56, 246, 85, 35, 126, 255, 245, 185, 23, 49, 239,
2660 116, 37, 3, 194, 69, 178, 14, 209, 0, 153, 180, 66, 190, 220, 254, 207,
2661 96, 177, 177, 241, 209, 199, 41, 47, 173, 90, 81, 206, 2, 106, 210, 101,
2662 98, 206, 225, 97, 119, 172, 141, 83, 204, 63, 103, 161, 66, 162, 231, 157,
2663 94, 212, 175, 97, 52, 246, 130, 179, 49, 216, 21, 25, 11, 81, 190, 178,
2664 198, 42, 62, 44, 223, 115, 135, 41, 205, 160, 228, 30, 86, 41, 73, 38,
2665 216, 128, 184, 39, 26, 59, 252, 166, 25, 38, 9, 138, 175, 88, 190, 223,
2666 27, 24, 224, 123, 190, 69, 164, 234, 129, 59, 108, 229, 248, 62, 187, 15,
2667 235, 147, 162, 83, 47, 123, 170, 190, 224, 31, 215, 110, 143, 31, 227, 216,
2668 85, 88, 154, 83, 207, 229, 41, 28, 237, 116, 181, 17, 37, 141, 224, 185,
2669 164, 144, 141, 233, 164, 138, 177, 241, 115, 181, 230, 150, 7, 92, 139, 141,
2670 113, 95, 57, 191, 211, 165, 217, 250, 197, 68, 164, 184, 168, 43, 48, 65,
2671 177, 237, 173, 144, 148, 221, 62, 189, 147, 63, 216, 188, 206, 103, 226, 171,
2672 32, 20, 230, 116, 144, 192, 1, 39, 202, 87, 74, 250, 6, 142, 188, 23,
2673 45, 4, 112, 191, 253, 67, 69, 70, 128, 143, 44, 234, 41, 96, 195, 82,
2674 202, 35, 158, 149, 240, 151, 23, 25, 166, 179, 85, 144, 58, 120, 149, 229,
2675 205, 34, 8, 110, 86, 119, 130, 210, 37, 173, 65, 71, 169, 67, 8, 51,
2676 20, 96, 51, 155, 3, 39, 85, 187, 40, 193, 57, 19, 99, 78, 173, 28,
2677 129, 154, 108, 175, 8, 138, 237, 71, 27, 148, 129, 35, 47, 57, 101, 237,
2678 168, 178, 227, 221, 212, 63, 124, 254, 253, 215, 183, 159, 49, 103, 74, 49,
2679 67, 160, 171, 72, 194, 215, 108, 251, 178, 18, 184, 100, 211, 105, 21, 186,
2680 39, 66, 218, 154, 72, 222, 90, 237, 179, 251, 51, 224, 212, 56, 251, 6,
2681 209, 151, 198, 176, 89, 110, 35, 141, 248, 237, 223, 68, 135, 206, 207, 169,
2682 254, 219, 243, 130, 71, 11, 94, 113, 233, 92, 63, 156, 169, 72, 215, 110,
2683 95, 94, 191, 50, 59, 89, 187, 59, 183, 99, 161, 146, 233, 245, 219, 80,
2684 87, 113, 251, 50, 144, 195, 158, 46, 189, 232, 119, 91, 75, 22, 6, 176,
2685 39, 206, 25, 196, 213, 195, 219, 24, 28, 103, 104, 36, 137, 128, 4, 119,
2686 163, 40, 126, 87, 18, 86, 128, 243, 213, 101, 2, 237, 78, 64, 160, 55,
2687 199, 93, 90, 126, 175, 199, 55, 89, 234, 190, 5, 16, 196, 88, 28, 208,
2688 28, 92, 32, 115, 204, 9, 202, 101, 15, 123, 43, 75, 90, 144, 95, 179,
2689 102, 249, 57, 150, 204, 99, 147, 203, 16, 63, 81, 244, 226, 237, 82, 204,
2690 20, 200, 140, 65, 83, 217, 161, 23, 123, 37, 115, 12, 100, 73, 70, 190,
2691 32, 235, 174, 140, 148, 157, 47, 238, 40, 208, 228, 80, 54, 187, 156, 252,
2692 253, 230, 231, 156, 138, 125, 96, 79, 3, 27, 143, 55, 146, 169, 165, 61,
2693 238, 60, 227, 77, 217, 93, 117, 122, 111, 46, 173, 113,
2699 public void CookieContainerTest ()
2701 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2702 string url = "http://" + ep.ToString ();
2704 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (CookieRequestHandler))) {
2707 CookieContainer container = new CookieContainer ();
2708 container.Add(new Uri (url), new Cookie ("foo", "bar"));
2709 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
2710 request.CookieContainer = container;
2711 WebHeaderCollection headers = request.Headers;
2712 headers.Add("Cookie", "foo=baz");
2713 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
2714 string responseString = null;
2715 using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
2716 responseString = reader.ReadToEnd ();
2719 Assert.AreEqual (1, response.Cookies.Count, "#01");
2720 Assert.AreEqual ("foo=bar", response.Headers.Get("Set-Cookie"), "#02");
2723 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (CookieRequestHandler))) {
2726 CookieContainer container = new CookieContainer ();
2727 HttpWebRequest request = (HttpWebRequest) WebRequest.Create (url);
2728 request.CookieContainer = container;
2729 WebHeaderCollection headers = request.Headers;
2730 headers.Add("Cookie", "foo=baz");
2731 HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
2732 string responseString = null;
2733 using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
2734 responseString = reader.ReadToEnd ();
2737 Assert.AreEqual (0, response.Cookies.Count, "#03");
2738 Assert.AreEqual ("", response.Headers.Get("Set-Cookie"), "#04");
2742 internal static byte[] CookieRequestHandler (Socket socket)
2744 MemoryStream ms = new MemoryStream ();
2745 byte[] buffer = new byte[4096];
2746 int bytesReceived = socket.Receive (buffer);
2747 while (bytesReceived > 0) {
2748 ms.Write(buffer, 0, bytesReceived);
2749 // We don't check for Content-Length or anything else here, so we give the client a little time to write
2750 // after sending the headers
2752 if (socket.Available > 0) {
2753 bytesReceived = socket.Receive (buffer);
2760 string cookies = string.Empty;
2761 using (StreamReader sr = new StreamReader (ms, Encoding.UTF8)) {
2763 while ((line = sr.ReadLine ()) != null) {
2764 if (line.StartsWith ("Cookie:")) {
2765 cookies = line.Substring ("cookie: ".Length);
2770 StringWriter sw = new StringWriter ();
2771 sw.WriteLine ("HTTP/1.1 200 OK");
2772 sw.WriteLine ("Content-Type: text/xml");
2773 sw.WriteLine ("Set-Cookie: " + cookies);
2774 sw.WriteLine ("Content-Length: " + cookies.Length.ToString (CultureInfo.InvariantCulture));
2779 return Encoding.UTF8.GetBytes (sw.ToString ());
2784 public class HttpRequestStreamTest
2787 public void BeginRead ()
2789 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2790 string url = "http://" + ep.ToString () + "/test/";
2792 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2795 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2796 req.Method = "POST";
2798 using (Stream rs = req.GetRequestStream ()) {
2799 byte [] buffer = new byte [10];
2801 rs.BeginRead (buffer, 0, buffer.Length, null, null);
2803 } catch (NotSupportedException ex) {
2804 // The stream does not support reading
2805 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2806 Assert.IsNull (ex.InnerException, "#3");
2807 Assert.IsNotNull (ex.Message, "#4");
2816 [Category("MobileNotWorking")]
2817 public void BeginWrite_Request_Aborted ()
2819 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2820 string url = "http://" + ep.ToString () + "/test/";
2822 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2825 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2826 req.Method = "POST";
2828 using (Stream rs = req.GetRequestStream ()) {
2831 rs.BeginWrite (new byte [] { 0x2a, 0x2f }, 0, 2, null, null);
2833 } catch (WebException ex) {
2834 // The request was aborted: The request was canceled
2835 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
2836 Assert.IsNull (ex.InnerException, "#3");
2837 Assert.IsNotNull (ex.Message, "#4");
2838 Assert.IsNull (ex.Response, "#5");
2839 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
2846 public void CanRead ()
2848 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2849 string url = "http://" + ep.ToString () + "/test/";
2851 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2854 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2855 req.Method = "POST";
2857 Stream rs = req.GetRequestStream ();
2859 Assert.IsFalse (rs.CanRead, "#1");
2861 Assert.IsFalse (rs.CanRead, "#2");
2870 public void CanSeek ()
2872 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2873 string url = "http://" + ep.ToString () + "/test/";
2875 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2878 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2879 req.Method = "POST";
2881 Stream rs = req.GetRequestStream ();
2883 Assert.IsFalse (rs.CanSeek, "#1");
2885 Assert.IsFalse (rs.CanSeek, "#2");
2893 [Test] // bug #324182
2894 public void CanTimeout ()
2896 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2897 string url = "http://" + ep.ToString () + "/test/";
2899 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2902 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2903 req.Method = "POST";
2905 Stream rs = req.GetRequestStream ();
2907 Assert.IsTrue (rs.CanTimeout, "#1");
2909 Assert.IsTrue (rs.CanTimeout, "#2");
2918 public void CanWrite ()
2920 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2921 string url = "http://" + ep.ToString () + "/test/";
2923 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2926 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2927 req.Method = "POST";
2929 Stream rs = req.GetRequestStream ();
2931 Assert.IsTrue (rs.CanWrite, "#1");
2933 Assert.IsFalse (rs.CanWrite, "#2");
2944 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2945 string url = "http://" + ep.ToString () + "/test/";
2947 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2950 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2951 req.Method = "POST";
2953 using (Stream rs = req.GetRequestStream ()) {
2954 byte [] buffer = new byte [10];
2956 rs.Read (buffer, 0, buffer.Length);
2958 } catch (NotSupportedException ex) {
2959 // The stream does not support reading
2960 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2961 Assert.IsNull (ex.InnerException, "#3");
2962 Assert.IsNotNull (ex.Message, "#4");
2971 public void ReadByte ()
2973 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
2974 string url = "http://" + ep.ToString () + "/test/";
2976 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
2979 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
2980 req.Method = "POST";
2982 using (Stream rs = req.GetRequestStream ()) {
2986 } catch (NotSupportedException ex) {
2987 // The stream does not support reading
2988 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
2989 Assert.IsNull (ex.InnerException, "#3");
2990 Assert.IsNotNull (ex.Message, "#4");
2999 public void ReadTimeout ()
3001 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
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 Stream rs = req.GetRequestStream ();
3012 Assert.AreEqual (300000, rs.ReadTimeout, "#1");
3014 Assert.AreEqual (300000, rs.ReadTimeout, "#2");
3025 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3026 string url = "http://" + ep.ToString () + "/test/";
3028 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3031 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3032 req.Method = "POST";
3034 using (Stream rs = req.GetRequestStream ()) {
3036 rs.Seek (0, SeekOrigin.Current);
3038 } catch (NotSupportedException ex) {
3039 // This stream does not support seek operations
3040 Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
3041 Assert.IsNull (ex.InnerException, "#3");
3042 Assert.IsNotNull (ex.Message, "#4");
3051 public void Write_Buffer_Null ()
3053 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3054 string url = "http://" + ep.ToString () + "/test/";
3056 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3059 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3060 req.Method = "POST";
3062 using (Stream rs = req.GetRequestStream ()) {
3064 rs.Write ((byte []) null, -1, -1);
3066 } catch (ArgumentNullException ex) {
3067 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3068 Assert.IsNull (ex.InnerException, "#3");
3069 Assert.IsNotNull (ex.Message, "#4");
3070 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3079 public void Write_Count_Negative ()
3081 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3082 string url = "http://" + ep.ToString () + "/test/";
3084 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3087 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3088 req.Method = "POST";
3090 using (Stream rs = req.GetRequestStream ()) {
3091 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3093 rs.Write (buffer, 1, -1);
3095 } catch (ArgumentOutOfRangeException ex) {
3096 // Specified argument was out of the range of valid values
3097 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3098 Assert.IsNull (ex.InnerException, "#A3");
3099 Assert.IsNotNull (ex.Message, "#A4");
3100 Assert.AreEqual ("size", ex.ParamName, "#A5");
3109 public void Write_Count_Overflow ()
3111 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3112 string url = "http://" + ep.ToString () + "/test/";
3114 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3117 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3118 req.Method = "POST";
3120 using (Stream rs = req.GetRequestStream ()) {
3121 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3123 rs.Write (buffer, buffer.Length - 2, 3);
3125 } catch (ArgumentOutOfRangeException ex) {
3126 // Specified argument was out of the range of valid values
3127 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3128 Assert.IsNull (ex.InnerException, "#3");
3129 Assert.IsNotNull (ex.Message, "#4");
3130 Assert.AreEqual ("size", ex.ParamName, "#5");
3139 public void Write_Offset_Negative ()
3141 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3142 string url = "http://" + ep.ToString () + "/test/";
3144 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3147 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3148 req.Method = "POST";
3150 using (Stream rs = req.GetRequestStream ()) {
3151 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3153 rs.Write (buffer, -1, 0);
3155 } catch (ArgumentOutOfRangeException ex) {
3156 // Specified argument was out of the range of valid values
3157 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3158 Assert.IsNull (ex.InnerException, "#3");
3159 Assert.IsNotNull (ex.Message, "#4");
3160 Assert.AreEqual ("offset", ex.ParamName, "#5");
3169 public void Write_Offset_Overflow ()
3171 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3172 string url = "http://" + ep.ToString () + "/test/";
3174 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3177 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3178 req.Method = "POST";
3180 using (Stream rs = req.GetRequestStream ()) {
3181 byte [] buffer = new byte [] { 0x2a, 0x2c, 0x1d, 0x00, 0x0f };
3183 rs.Write (buffer, buffer.Length + 1, 0);
3185 } catch (ArgumentOutOfRangeException ex) {
3186 // Specified argument was out of the range of valid values
3187 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
3188 Assert.IsNull (ex.InnerException, "#3");
3189 Assert.IsNotNull (ex.Message, "#4");
3190 Assert.AreEqual ("offset", ex.ParamName, "#5");
3199 public void Write_Request_Aborted ()
3201 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3202 string url = "http://" + ep.ToString () + "/test/";
3204 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3207 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3208 req.Method = "POST";
3210 using (Stream rs = req.GetRequestStream ()) {
3213 rs.Write (new byte [0], 0, 0);
3215 } catch (WebException ex) {
3216 // The request was aborted: The request was canceled
3217 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3218 Assert.IsNull (ex.InnerException, "#3");
3219 Assert.IsNotNull (ex.Message, "#4");
3220 Assert.IsNull (ex.Response, "#5");
3221 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3228 [Category ("NotWorking")]
3229 public void Write_Stream_Closed ()
3231 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3232 string url = "http://" + ep.ToString () + "/test/";
3234 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3237 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3238 req.Method = "POST";
3240 using (Stream rs = req.GetRequestStream ()) {
3243 rs.Write (new byte [0], 0, 0);
3245 } catch (WebException ex) {
3246 // The request was aborted: The connection was closed unexpectedly
3247 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3248 Assert.IsNull (ex.InnerException, "#3");
3249 Assert.IsNotNull (ex.Message, "#4");
3250 Assert.IsNull (ex.Response, "#5");
3251 Assert.AreEqual (WebExceptionStatus.ConnectionClosed, ex.Status, "#6");
3258 public void WriteByte_Request_Aborted ()
3260 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3261 string url = "http://" + ep.ToString () + "/test/";
3263 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3266 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3267 req.Method = "POST";
3269 using (Stream rs = req.GetRequestStream ()) {
3272 rs.WriteByte (0x2a);
3274 } catch (WebException ex) {
3275 // The request was aborted: The request was canceled
3276 Assert.AreEqual (typeof (WebException), ex.GetType (), "#2");
3277 Assert.IsNull (ex.InnerException, "#3");
3278 Assert.IsNotNull (ex.Message, "#4");
3279 Assert.IsNull (ex.Response, "#5");
3280 Assert.AreEqual (WebExceptionStatus.RequestCanceled, ex.Status, "#6");
3287 public void WriteTimeout ()
3289 IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
3290 string url = "http://" + ep.ToString () + "/test/";
3292 using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (HttpWebRequestTest.EchoRequestHandler))) {
3295 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
3296 req.Method = "POST";
3298 Stream rs = req.GetRequestStream ();
3300 Assert.AreEqual (300000, rs.WriteTimeout, "#1");
3302 Assert.AreEqual (300000, rs.WriteTimeout, "#2");
3312 // This test is supposed to fail prior to .NET 4.0
3313 public void Post_EmptyRequestStream ()
3315 var wr = HttpWebRequest.Create ("http://google.com");
3317 wr.GetRequestStream ();
3319 var gr = wr.BeginGetResponse (delegate { }, null);
3320 Assert.AreEqual (true, gr.AsyncWaitHandle.WaitOne (5000), "#1");
3324 static class StreamExtensions {
3325 public static int ReadAll(this Stream stream, byte[] buffer, int offset, int count)
3329 while (totalRead < count) {
3330 int bytesRead = stream.Read (buffer, offset + totalRead, count - totalRead);
3334 totalRead += bytesRead;
3341 static class ExceptionAssert {
3343 /// Asserts that the function throws an exception.
3345 /// <param name="f">A function execute that is expected to raise an exception.</param>
3346 /// <typeparam name="T">The type of exception that is expected.</typeparam>
3347 /// <returns>The exception thrown.</returns>
3348 /// <exception cref="AssertFailedException">If the function does not throw an exception
3349 /// or throws a different exception.</exception>
3350 /// <example><![CDATA[
3351 /// ExceptionAssert.Throws(typeof(ArgumentNullException), delegate {
3352 /// myObject.myFunction(null); });
3354 public static T Throws<T> (Action f) where T : Exception {
3355 Exception actualException = null;
3359 } catch (Exception ex) {
3360 actualException = ex;
3363 if (actualException == null)
3364 throw new AssertionException (string.Format (
3365 "No exception thrown. Expected '{0}'",
3366 typeof (T).FullName));
3367 else if (typeof(T) != actualException.GetType())
3368 throw new AssertionException (string.Format (
3369 "Caught exception of type '{0}'. Expected '{1}':{2}",
3370 actualException.GetType().FullName,
3371 typeof (T).FullName,
3372 Environment.NewLine + actualException));
3374 return (T) actualException;