public void HttpRequestIsLocal()
        {
            var ips = new List <IPAddress> ();

            ips.Add(IPAddress.Loopback);
            foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (adapter.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }
                foreach (var ip in adapter.GetIPProperties().UnicastAddresses)
                {
                    ips.Add(ip.Address);
                }
            }

            foreach (var ip in ips)
            {
                if (ip.AddressFamily != AddressFamily.InterNetwork)
                {
                    continue;
                }

                HttpListener listener = NetworkHelpers.CreateAndStartHttpListener(
                    "http://" + ip + ":", out var port, "/HttpRequestIsLocal/");
                NetworkStream ns = HttpListener2Test.CreateNS(ip, port);
                HttpListener2Test.Send(ns, "GET /HttpRequestIsLocal/ HTTP/1.0\r\n\r\n");
                HttpListenerContext ctx     = listener.GetContext();
                HttpListenerRequest request = ctx.Request;
                Assert.AreEqual(true, request.IsLocal, "IP " + ip + " is not local");
                listener.Close();
            }
        }
        public void BindToAllInterfaces()
        {
            var h = NetworkHelpers.CreateAndStartHttpListener("http://*:", out var port, "/");
            var c = new TcpClient("localhost", port);

            h.Stop();
        }
Example #3
0
        public void AbortTwice()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://localhost:", out var port, "/hola/");

            listener.Abort();
            listener.Abort();
        }
        public void Test14()
        {
            _listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var port, "/test14/");
            MyNetworkStream ns = CreateNS(port);

            Send(ns, "POST /test14/ HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            HttpListenerContext c = _listener.GetContext();

            test14_request = c.Request;
            test_evt       = new ManualResetEvent(false);
            Thread thread = new Thread(ReadToEnd);

            thread.Start();
            if (test_evt.WaitOne(3000, false) == false)
            {
#if MONO_FEATURE_THREAD_ABORT
                thread.Abort();
#else
                thread.Interrupt();
#endif
                test_evt.Close();
                Assert.IsTrue(false, "Timed out");
            }
            test_evt.Close();
            c.Response.Close();
            ns.Close();
            Assert.AreEqual("123", read_to_end, "Did not get the expected input.");
        }
		public void ReceiveCookiesFromClient ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out sendCookiePort, "/SendCookie/");
			Thread clientThread = new Thread (new ThreadStart (SendCookie));
			clientThread.Start ();

			HttpListenerContext context = _listener.GetContext();
			HttpListenerRequest request = context.Request;

			Assert.AreEqual (3, request.Cookies.Count, "#1");
			foreach (Cookie c in request.Cookies) {
				if (c.Name == "Cookie1") {
					Assert.AreEqual ("Value1", c.Value, "#2");
					Assert.AreEqual ("\"/\"", c.Path, "#3");
					Assert.AreEqual (0, c.Port.Length, "#4");
					Assert.AreEqual (0, c.Domain.Length, "#5");
				} else if (c.Name == "CookieM") {
					Assert.AreEqual ("ValueM", c.Value, "#6");
					Assert.AreEqual ("\"/p2\"", c.Path, "#7");
					Assert.AreEqual ("\"99\"", c.Port, "#8");
					Assert.AreEqual ("\"test\"", c.Domain, "#9");
				} else if (c.Name == "Cookie2") {
					Assert.AreEqual ("Value2", c.Value, "#10");
					Assert.AreEqual ("\"/foo\"", c.Path, "#11");
					Assert.AreEqual (0, c.Port.Length, "#12");
					Assert.AreEqual (0, c.Domain.Length, "#13");
				} else
					Assert.Fail ("Invalid cookie name " + c.Name);
			}
		}
        public void TestNonChunkedAsync()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var port, "/");

            listener.BeginGetContext(callback, listener);

            HttpListener2Test.MyNetworkStream ns = HttpListener2Test.CreateNS(port);
            string message = "<script>\n" +
                             " <!-- register the blueprint for our show-headers service -->\n" +
                             " <action verb=\"POST\" path=\"/host/register\">\n" +
                             "    <blueprint>\n" +
                             "      <assembly>dream.tutorial.show-headers</assembly>\n" +
                             "      <class>MindTouch.Dream.Tutorial.ShowHeadersService</class>\n" +
                             "    </blueprint>\n" +
                             "  </action>\n" +
                             "\n" +
                             "  <!-- instantiate it -->\n" +
                             "  <action verb=\"POST\" path=\"/host/start\">\n" +
                             "    <config>\n" +
                             "      <path>show-headers</path>\n" +
                             "      <class>MindTouch.Dream.Tutorial.ShowHeadersService</class>\n" +
                             "    </config>\n" +
                             "  </action>\n" +
                             "</script>";
            string s = String.Format("POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: {0}\r\n\r\n{1}",
                                     message.Length, message);

            HttpListener2Test.Send(ns, s);
            bool   timedout;
            string response = HttpListener2Test.ReceiveWithTimeout(ns, 1024, 3000, out timedout);

            ns.Close();
            listener.Close();
            Assert.IsFalse(timedout);
        }
        public void Test16()
        {
            // 1 single write with headers + body (size > 8kB)
            _listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var port, "/test16/");
            MyNetworkStream ns = CreateNS(port);
            StringBuilder   sb = new StringBuilder();

            sb.Append("POST /test16/ HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Length: 8888\r\n\r\n");
            string eights = new string ('b', 8888);

            sb.Append(eights);
            string data = sb.ToString();

            Send(ns, data);
            HttpListenerContext c   = _listener.GetContext();
            HttpListenerRequest req = c.Request;

            using (StreamReader r = new StreamReader(req.InputStream)) {
                read_to_end = r.ReadToEnd();
            }
            Assert.AreEqual(read_to_end.Length, read_to_end.Length, "Wrong length");
            Assert.IsTrue(eights == read_to_end, "Wrong data");
            c.Response.Close();
            ns.Close();
        }
        public void Test_MultipleConnections()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var port, "/multiple/");

            // First one
            NetworkStream ns = HttpListener2Test.CreateNS(port);

            HttpListener2Test.Send(ns, "POST /multiple/ HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            HttpListenerContext ctx = listener.GetContext();

            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");
            ctx.Response.OutputStream.Close();
            string response = HttpListener2Test.Receive(ns, 1024);

            ns.Close();

            // Second one
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "POST /multiple/ HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            ctx = listener.GetContext();
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");
            ctx.Response.OutputStream.Close();
            response = HttpListener2Test.Receive(ns, 1024);
            ns.Close();

            listener.Close();
        }
        public void Test_HostInUri()
        {
            var wait  = new ManualResetEvent(false);
            var wait2 = new ManualResetEvent(false);
            var port  = 0;

            Thread t = new Thread(delegate(object a) {
                wait.WaitOne();

                NetworkStream ns = HttpListener2Test.CreateNS(port);
                HttpListener2Test.Send(ns, "GET http://www.example.com/ HTTP/1.1\r\nHost: www.example.com\r\nContent-Length: 3\r\n\r\n123456");

                wait2.WaitOne();
                ns.Close();
            });

            t.Start();

            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://*:", out port, "/");

            wait.Set();
            HttpListenerContext ctx = listener.GetContext();

            Assert.AreEqual("http://www.example.com:" + port + "/", ctx.Request.Url.ToString());
            Assert.AreEqual("http://www.example.com/", ctx.Request.RawUrl);
            wait2.Set();

            listener.Close();
        }
        public void BindToSingleInterface()
        {
            IPAddress [] machineAddress = null;

            try {
                machineAddress = Dns.GetHostAddresses(Dns.GetHostName());
            } catch (SocketException) {
                // The build hosts sometimes can not resolve the hostname
                Assert.Ignore("Hostname couldn't be resolved.");
            }

            IPAddress ma = null;;

            // Listen on the first IPV4 interface
            foreach (IPAddress a in machineAddress)
            {
                if (a.AddressFamily == AddressFamily.InterNetwork)
                {
                    ma = a;
                    break;
                }
            }
            var h = NetworkHelpers.CreateAndStartHttpListener("http://" + ma + ":", out var port, "/");

            try {
                var c = new TcpClient("localhost", port);
                Assert.Fail("The TcpClient should have failed to connect since HttpListener is not listening on localhost");
            } catch (SocketException) {
                // Pass
            }
            h.Stop();
        }
Example #11
0
        public void CloseTwice()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var port, "/hola/");

            listener.Close();
            listener.Close();
        }
		public void ClosePort ()
		{
			var h = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/");
			h.BeginGetContext (null, null);
			h.Stop ();
			TcpListener t = new TcpListener (IPAddress.Parse ("127.0.0.1"), port);
			t.Start ();
			t.Stop ();
		}
		public void Test2 ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test2/");
			NetworkStream ns = CreateNS (port);
			Send (ns, "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); // no prefix
			string response = Receive (ns, 512);
			ns.Close ();
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 400"));
		}
		public void Test5 ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test5/");
			NetworkStream ns = CreateNS (port);
			Send (ns, "POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: pepe\r\n\r\n"); // not implemented
			string response = Receive (ns, 512);
			ns.Close ();
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 501"));
		}
Example #15
0
        public void ConnectionReuse()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://localhost:", out var port, "/", out var uri);

            IPEndPoint expectedIpEndPoint = CreateListenerRequest(listener, uri);

            Assert.AreEqual(expectedIpEndPoint, CreateListenerRequest(listener, uri), "reuse1");
            Assert.AreEqual(expectedIpEndPoint, CreateListenerRequest(listener, uri), "reuse2");
        }
		public void Test4 ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test4/");
			NetworkStream ns = CreateNS (port);
			Send (ns, "POST /test4/ HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); // length required
			string response = Receive (ns, 512);
			ns.Close ();
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 411"));
		}
        public void SendCookiestoClient()
        {
            _listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out receiveCookiePort, "/ReceiveCookie/");
            Thread clientThread = new Thread(new ThreadStart(ReceiveCookie));

            clientThread.Start();

            HttpListenerContext  context  = _listener.GetContext();
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            Cookie cookie = new Cookie();

            cookie.Name    = "Name0";
            cookie.Value   = "Value0";
            cookie.Domain  = "blue";
            cookie.Path    = "/path/";
            cookie.Port    = "\"80\"";
            cookie.Version = 1;
            response.Cookies.Add(cookie);

            string responseString = "<HTML><BODY>----</BODY></HTML>";

            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Flush();
            response.Close();

            lock (_lock) {
                bool foundCookie = false;
                foreach (String str in cookieResponse.Split('\n'))
                {
                    if (!str.StartsWith("Set-Cookie"))
                    {
                        continue;
                    }
                    Dictionary <string, String> dic = new Dictionary <string, String>();
                    foreach (String p in str.Substring(str.IndexOf(":") + 1).Split(';'))
                    {
                        String[] parts = p.Split('=');
                        dic.Add(parts [0].Trim(), parts [1].Trim());
                    }
                    Assert.AreEqual("Value0", dic ["Name0"], "#1");
                    Assert.AreEqual("blue", dic ["Domain"], "#2");
                    Assert.AreEqual("\"/path/\"", dic ["Path"], "#3");
                    Assert.AreEqual("\"80\"", dic ["Port"], "#4");
                    Assert.AreEqual("1", dic ["Version"], "#5");
                    foundCookie = true;
                    break;
                }
                Assert.IsTrue(foundCookie, "#6");
            }
        }
		public void Test6 ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test6/");
			NetworkStream ns = CreateNS (port);
			 // not implemented! This is against the RFC. Should be a bad request/length required
			Send (ns, "POST /test6/ HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: identity\r\n\r\n");
			string response = Receive (ns, 512);
			ns.Close ();
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 501"));
		}
		public void Test13 ()
		{
			// 0.9
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test13/");
			MyNetworkStream ns = CreateNS (port);
			Send (ns, "GEt /test13/ HTTP/0.9\r\nHost: 127.0.0.1\r\n\r\n");
			ns.GetSocket ().Shutdown (SocketShutdown.Send);
			string input = Receive (ns, 512);
			ns.Close ();
			Assert.IsTrue(input.StartsWith ("HTTP/1.1 400"));
		}
		void EchoServer ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://*:", out echoServerPort, "/foobar/");
			echoServerStarted.Set ();

			manualReset = new ManualResetEvent (false);

			IAsyncResult result = _listener.BeginGetContext (
				new AsyncCallback (EchoCallback), _listener);
			manualReset.WaitOne ();
		}
		public void Test9 ()
		{
			// 1.0 + "Transfer-Encoding: chunked"
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test9/");
			NetworkStream ns = CreateNS (port);
			Send (ns, "POST /test9/ HTTP/1.0\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n3\r\n123\r\n0\r\n\r\n");
			bool timeout;
			string response = ReceiveWithTimeout (ns, 512, 1000, out timeout);
			ns.Close ();
			Assert.IsFalse (timeout);
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 411"));
		}
		public void Test_MultipleClosesOnOuputStreamAllowed ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/MultipleCloses/");
			NetworkStream ns = CreateNS (port);
			Send (ns, "GET /MultipleCloses/ HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");

			HttpListenerContext ctx = _listener.GetContext ();
			ctx.Response.OutputStream.Close ();
			ctx.Response.OutputStream.Close ();
			ctx.Response.OutputStream.Close ();
			ctx.Response.Close ();
		}
        public void HttpRequestIgnoreBadCookies()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener(
                "http://127.0.0.1:", out var port, "/HttpRequestIgnoreBadCookiesTest/");
            NetworkStream ns = HttpListener2Test.CreateNS(port);

            HttpListener2Test.Send(ns, "GET /HttpRequestIgnoreBadCookiesTest/?a=b HTTP/1.1\r\nHost: 127.0.0.1\r\nCookie: ELOQUA=GUID=5ca2346347357f4-f877-4eff-96aa-70fe0b677650; ELQSTATUS=OK; WRUID=609099666.123259461695; CommunityServer-UserCookie2101=lv=Thu, 26 Jul 2012 15:25:11 GMT&mra=Mon, 01 Oct 2012 17:40:05 GMT; PHPSESSID=1234dg3opfjb4qafp0oo645; __utma=9761706.1153317537.1357240270.1357240270.1357317902.2; __utmb=9761706.6.10.1357317902; __utmc=9761706; __utmz=9761706.1357240270.1.1.utmcsr=test.testdomain.com|utmccn=(referral)|utmcmd=referral|utmcct=/test/1234\r\n\r\n");
            HttpListenerContext ctx     = listener.GetContext();
            HttpListenerRequest request = ctx.Request;

            Assert.AreEqual("/HttpRequestIgnoreBadCookiesTest/?a=b", request.Url.PathAndQuery);
            listener.Close();
        }
		public void Test10 ()
		{
			// Same as Test9, but now we shutdown the socket for sending.
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test10/");
			MyNetworkStream ns = CreateNS (port);
			Send (ns, "POST /test10/ HTTP/1.0\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n3\r\n123\r\n0\r\n\r\n");
			ns.GetSocket ().Shutdown (SocketShutdown.Send);
			bool timeout;
			string response = ReceiveWithTimeout (ns, 512, 1000, out timeout);
			ns.Close ();
			Assert.IsFalse (timeout);
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 411"));
		}
		public void Test17 ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test17/");
			NetworkStream ns = CreateNS (port);
			Send (ns, "RANDOM /test17/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
			HttpListenerContext ctx = _listener.GetContext ();
			Send (ctx.Response.OutputStream, "%%%OK%%%");
			ctx.Response.Close ();
			string response = Receive (ns, 1024);
			ns.Close ();
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 200"));
			Assert.IsTrue(response.Contains ("Transfer-Encoding: chunked"));
		}
Example #26
0
        public void AbortWhileGet()
        {
            // "System.Net.HttpListener Exception : The I/O operation has been aborted
            // because of either a thread exit or an application request
            //   at System.Net.HttpListener.GetContext()
            //   at MonoTests.System.Net.HttpListenerTest.CloseWhileGet()

            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var _, "/abortwhileget/");
            RunMe        rm       = new RunMe(1000, new ThreadStart(listener.Abort), new object [0]);

            rm.Start();
            HttpListenerContext ctx = listener.GetContext();
        }
        public void HttpMethod()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener(
                "http://127.0.0.1:", out var port, "/HttpMethod/");
            NetworkStream ns = HttpListener2Test.CreateNS(port);

            HttpListener2Test.Send(ns, "pOsT /HttpMethod/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            HttpListenerContext ctx     = listener.GetContext();
            HttpListenerRequest request = ctx.Request;

            Assert.AreEqual("pOsT", request.HttpMethod);
            listener.Close();
        }
        public void HttpRequestUriIsNotDecoded()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener(
                "http://127.0.0.1:", out var port, "/RequestUriDecodeTest/");
            NetworkStream ns = HttpListener2Test.CreateNS(port);

            HttpListener2Test.Send(ns, "GET /RequestUriDecodeTest/?a=b&c=d%26e HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
            HttpListenerContext ctx     = listener.GetContext();
            HttpListenerRequest request = ctx.Request;

            Assert.AreEqual("/RequestUriDecodeTest/?a=b&c=d%26e", request.Url.PathAndQuery);
            listener.Close();
        }
		public void Test8 ()
		{
			_listener = NetworkHelpers.CreateAndStartHttpListener ("http://127.0.0.1:", out var port, "/test8/");
			NetworkStream ns = CreateNS (port);
			// Just like Test7, but 1.0
			Send (ns, "POST /test8/ HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
			HttpListenerContext ctx = _listener.GetContext ();
			Send (ctx.Response.OutputStream, "%%%OK%%%");
			ctx.Response.Close ();
			string response = Receive (ns, 512);
			ns.Close ();
			Assert.IsTrue(response.StartsWith ("HTTP/1.1 200"));
			Assert.IsTrue (-1 == response.IndexOf ("Transfer-Encoding: chunked"));
		}
Example #30
0
        public void AbortWhileBegin()
        {
            HttpListener listener = NetworkHelpers.CreateAndStartHttpListener("http://127.0.0.1:", out var _, "/abortwhilebegin/");
            CallMe       cm       = new CallMe();

            listener.BeginGetContext(cm.Callback, listener);
            listener.Abort();
            if (false == cm.Event.WaitOne(3000, false))
            {
                Assert.Fail("This should not time out.");
            }
            Assert.IsNotNull(cm.Error);
            Assert.AreEqual(typeof(ObjectDisposedException), cm.Error.GetType(), "Exception type");
            cm.Dispose();
        }