Example #1
0
        public void HttpServer_SweepIdle()
        {
            HttpServer     server;
            HttpRequest    request;
            BlockArray     blocks;
            EnhancedSocket sock;

            server = new HttpServer(new IPEndPoint[] { new IPEndPoint(IPAddress.Any, ServerPort) }, new IHttpModule[] { new TestModule() }, 5, 100, int.MaxValue);
            server.Start();

            try
            {
                request             = new HttpRequest("GET", "/foo.htm", null);
                request["Response"] = "abcd";
                request["Close"]    = "yes";
                blocks = request.Serialize(4096);

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect("localhost", ServerPort);
                Thread.Sleep(100);
                Assert.AreEqual(1, server.ConnectionCount);
                Thread.Sleep(1000);
                server.SweepIdle(TimeSpan.FromMilliseconds(500));
                Assert.AreEqual(0, server.ConnectionCount);

                sock.Close();
            }
            finally
            {
                server.Stop();
            }
        }
Example #2
0
        public void HttpServer_MaxQuerySize()
        {
            HttpServer   server;
            HttpRequest  request;
            HttpResponse response;
            BlockArray   blocks;

            byte[]         buf;
            int            cb;
            EnhancedSocket sock;
            IAsyncResult   ar;

            server = new HttpServer(new IPEndPoint[] { new IPEndPoint(IPAddress.Any, ServerPort) }, new IHttpModule[] { new TestModule() }, 5, 100, 200);
            server.Start();

            try
            {
                request                   = new HttpRequest("PUT", "/foo.htm", null);
                request.Content           = new BlockArray(500);
                request["Response"]       = "abcd";
                request["Close"]          = "yes";
                request["Content-Length"] = request.Content.Size.ToString();
                blocks = request.Serialize(4096);

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect("localhost", ServerPort);
                Thread.Sleep(100);
                Assert.AreEqual(1, server.ConnectionCount);

                try
                {
                    ar = sock.BeginSendAll(blocks, SocketFlags.None, null, null);
                    sock.EndSendAll(ar);
                }
                catch
                {
                }

                response = new HttpResponse();
                response.BeginParse();

                buf = new byte[4096];
                cb  = sock.Receive(buf, buf.Length, SocketFlags.None);

                Assert.IsTrue(response.Parse(buf, cb));
                response.EndParse();

                Assert.AreEqual(HttpStatus.RequestEntityTooLarge, response.Status);
                sock.Close();
            }
            finally
            {
                server.Stop();
            }
        }
Example #3
0
        public void HttpServer_QueryResponse_Close()
        {
            HttpServer   server;
            HttpRequest  request;
            HttpResponse response;
            BlockArray   blocks;

            byte[]         buf;
            int            cb;
            EnhancedSocket sock;
            IAsyncResult   ar;

            server = new HttpServer(new IPEndPoint[] { new IPEndPoint(IPAddress.Any, ServerPort) }, new IHttpModule[] { new TestModule() }, 5, 100, int.MaxValue);
            server.Start();

            try
            {
                request          = new HttpRequest("GET", "/foo.htm", null);
                request.Content  = new BlockArray(Encoding.ASCII.GetBytes("abcd"));
                request["Close"] = "yes";
                blocks           = request.Serialize(4096);

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect("localhost", ServerPort);
                Thread.Sleep(100);
                Assert.AreEqual(1, server.ConnectionCount);

                ar = sock.BeginSendAll(blocks, SocketFlags.None, null, null);
                sock.EndSendAll(ar);

                response = new HttpResponse();
                response.BeginParse();

                buf = new byte[4096];
                cb  = sock.Receive(buf, buf.Length, SocketFlags.None);

                Assert.IsTrue(response.Parse(buf, cb));
                response.EndParse();

                CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("abcd"), response.Content.ToByteArray());

                buf = new byte[4096];
                cb  = sock.Receive(buf, buf.Length, SocketFlags.None);
                Assert.AreEqual(0, cb);

                sock.Close();
            }
            finally
            {
                server.Stop();
            }
        }
Example #4
0
        public void SipTcpTransport_MultipleChunks()
        {
            // Transmit a message to a transport in several chunks to make
            // sure it can be reassembled properly.

            TestTransport  transport = new TestTransport();
            EnhancedSocket sock      = null;
            SipRequest     msg;
            SipRequest     recvMsg;

            byte[] buf;

            try
            {
                transport.Start(new NetworkBinding("127.0.0.1:5311"));

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect("127.0.0.1", 5311);
                sock.NoDelay = true;

                msg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg.AddHeader("Count", "0");
                msg.Contents = GetContents(25);

                buf = msg.ToArray();
                for (int i = 0; i < buf.Length; i++)
                {
                    sock.Send(buf, i, 1, SocketFlags.None);
                    Thread.Sleep(1);
                }

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("0", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg.Contents, recvMsg.Contents);
            }
            finally
            {
                if (sock != null)
                {
                    sock.Close();
                }

                transport.Stop();
            }
        }
Example #5
0
        public bool Connect(IPEndPoint endPoint)
        {
            EnhancedSocket sock       = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EnhancedSocket sockAccept = null;

            try
            {
                sock.Connect(endPoint);
                sockAccept = WaitForAccept();
                return(sockAccept != null);
            }
            catch
            {
                return(false);
            }
            finally
            {
                sock.Close();
                if (sockAccept != null)
                {
                    sockAccept.Close();
                }
            }
        }
Example #6
0
        /// <summary>
        /// Asynchronously transmits the message passed to the destination
        /// indicated by the <see paramref="remoteEP" /> parameter.
        /// </summary>
        /// <param name="remoteEP">The destination SIP endpoint's <see cref="NetworkBinding" />.</param>
        /// <param name="message">The <see cref="SipMessage" /> to be transmitted.</param>
        /// <remarks>
        /// Note that this method will go to some lengths to send the message
        /// down an existing connection to this endpoint.
        /// </remarks>
        /// <exception cref="SipTransportException">Thrown if the remote endpoint rejected the message or timed out.</exception>
        public void Send(NetworkBinding remoteEP, SipMessage message)
        {
            string         key = remoteEP.ToString();
            EnhancedSocket sock;
            Connection     con;

            using (TimedLock.Lock(this))
            {
                if (listener == null)
                {
                    throw new ObjectDisposedException("Transport is closed.");
                }

                if (disabled)
                {
                    return;
                }

                if ((traceMode & SipTraceMode.Send) != 0)
                {
                    SipHelper.Trace(string.Format("TCP: sending to {0}", remoteEP), message);
                }

                // Send the message down an existing connection to this
                // endpoint (if there is one).

                if (connections.TryGetValue(key, out con))
                {
                    con.Send(message);
                    return;
                }
            }

            // Otherwise establish a connection to the endpoint and transmit
            // the message.  Note that I'm establishing the connection outside
            // of the lock so processing on other connections can continue
            // while the connection is established.

            try
            {
                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect(remoteEP);
            }
            catch (SocketException e)
            {
                switch ((SocketError)e.ErrorCode)
                {
                case SocketError.ConnectionAborted:
                case SocketError.ConnectionRefused:
                case SocketError.ConnectionReset:
                case SocketError.HostDown:
                case SocketError.HostNotFound:
                case SocketError.HostUnreachable:

                    throw new SipTransportException(SipTransportException.ErrorType.Rejected, e.Message, e);

                case SocketError.TimedOut:

                    throw new SipTransportException(SipTransportException.ErrorType.Timeout, e.Message, e);

                default:

                    throw;
                }
            }

            using (TimedLock.Lock(this))
            {
                if (listener == null)
                {
                    // Transport must have been closed while we were outside of the lock.

                    sock.ShutdownAndClose();
                    throw new ObjectDisposedException("Transport is closed.");
                }

                if (connections.TryGetValue(key, out con))
                {
                    // Another connection to this endpoint must have been established
                    // while we were outside of the lock.  Close the new socket and
                    // use the existing connection.

                    sock.ShutdownAndClose();

                    con.Send(message);
                    return;
                }

                // Add the new connection to the collection and then
                // send the message.

                con = new Connection(this, sock, remoteEP);
                connections.Add(key, con);
                con.Send(message);
            }
        }
Example #7
0
        private static int Reflector(string portArg)
        {
            try
            {
                NetReflector reflector;
                int          port;

                if (!int.TryParse(portArg, out port))
                {
                    Program.Error("Invalid network port.");
                    return(1);
                }

                Console.WriteLine();
                Console.WriteLine("Starting network reflector on port [{0}]", port);
                Console.WriteLine("Press [C] to close all connections and [X] to exit the test.");
                Console.WriteLine();

                reflector = new NetReflector(port);

                while (true)
                {
                    var ch = Console.ReadKey(true);

                    switch (ch.KeyChar)
                    {
                    case 'c':
                    case 'C':

                        reflector.CloseConnections();
                        break;

                    case 'x':
                    case 'X':

                        reflector.Stop();
                        return(0);

#if TEST
                    // UDP test code

                    case 'u':
                    case 'U':

                    {
                        var sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        var buf  = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                        var ep   = (EndPoint) new IPEndPoint(IPAddress.Any, 0);

                        sock.Bind();
                        sock.SendTo(buf, 0, buf.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, port));

                        for (int i = 0; i < buf.Length; i++)
                        {
                            buf[i] = 0;
                        }

                        sock.ReceiveFrom(buf, ref ep);
                        sock.Close();
                    }
                    break;

                    // TCP test code

                    case 't':
                    case 'T':

                    {
                        var sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                        sock.NoDelay = true;
                        sock.Connect(new IPEndPoint(IPAddress.Loopback, port));

                        for (int i = 0; i < 10; i++)
                        {
                            var buf = new byte[i + 1];

                            for (int j = 0; j < i + 1; j++)
                            {
                                buf[j] = (byte)j;
                            }

                            sock.Send(buf);

                            for (int j = 0; j < i + 1; j++)
                            {
                                buf[j] = 0;
                            }

                            var cbRecv = sock.Receive(buf);
                        }

                        sock.Close();
                    }
                    break;
#endif
                    }
                }
            }
            catch (Exception e)
            {
                Program.Error("Error ({0}): {1}", e.GetType().Name, e.Message);
                return(1);
            }
        }
Example #8
0
        public void SipTcpTransport_MultipleBuffered()
        {
            // Render two messages into a single buffer and transmit them
            // to a TCP transport in a single send.  This will result in
            // the two messages being processed out of the headerBuf which
            // is what we want to test here.

            TestTransport  transport = new TestTransport();
            EnhancedSocket sock = null;
            SipRequest     msg1, msg2;
            SipRequest     recvMsg;

            byte[] buf;
            int    cb;

            try
            {
                transport.Start(new NetworkBinding("127.0.0.1:5311"));

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect("127.0.0.1", 5311);

                msg1 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg1.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg1.AddHeader("Count", "0");
                msg1.Contents = GetContents(0);

                msg2 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg2.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg2.AddHeader("Count", "1");
                msg2.Contents = GetContents(0);

                buf = Helper.Concat(msg1.ToArray(), msg2.ToArray());
                cb  = sock.Send(buf);
                Assert.AreEqual(buf.Length, cb);

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg1[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("0", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg1.Contents, recvMsg.Contents);

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg2[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("1", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg2.Contents, recvMsg.Contents);

                // Try it again, this time with some data.

                msg1 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg1.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg1.AddHeader("Count", "0");
                msg1.Contents = GetContents(10);

                msg2 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg2.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg2.AddHeader("Count", "1");
                msg2.Contents = GetContents(20);

                buf = Helper.Concat(msg1.ToArray(), msg2.ToArray());
                cb  = sock.Send(buf);
                Assert.AreEqual(buf.Length, cb);

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg1[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("0", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg1.Contents, recvMsg.Contents);

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg2[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("1", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg2.Contents, recvMsg.Contents);

                // Try it one more time, this time adding a leading CRLF

                msg1 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg1.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg1.AddHeader("Count", "0");
                msg1.Contents = GetContents(10);

                msg2 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20);
                msg2.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint));
                msg2.AddHeader("Count", "1");
                msg2.Contents = GetContents(20);

                buf = Helper.Concat(new byte[] { 0x0D, 0x0A }, msg1.ToArray(), new byte[] { 0x0D, 0x0A }, msg2.ToArray());
                cb  = sock.Send(buf);
                Assert.AreEqual(buf.Length, cb);

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg1[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("0", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg1.Contents, recvMsg.Contents);

                recvMsg = (SipRequest)transport.Receive();
                Assert.AreEqual(SipMethod.Register, recvMsg.Method);
                Assert.AreEqual("sip:[email protected]", recvMsg.Uri);
                Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion);
                Assert.AreEqual(msg2[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText);
                Assert.AreEqual("1", recvMsg["Count"].FullText);
                CollectionAssert.AreEqual(msg2.Contents, recvMsg.Contents);
            }
            finally
            {
                if (sock != null)
                {
                    sock.Close();
                }

                transport.Stop();
            }
        }