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