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 EnhancedSocket_CreateDatagramPair()
        {
            for (int i = 0; i < 1000; i++)
            {
                EnhancedSocket sock0 = null;
                EnhancedSocket sock1 = null;
                int            port0, port1;

                try
                {
                    EnhancedSocket.CreateDatagramPair(IPAddress.Any, out sock0, out sock1);

                    port0 = ((IPEndPoint)sock0.LocalEndPoint).Port;
                    port1 = ((IPEndPoint)sock1.LocalEndPoint).Port;
                }
                finally
                {
                    if (sock0 != null)
                    {
                        sock0.Close();
                    }

                    if (sock1 != null)
                    {
                        sock1.Close();
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Called by the socket listener when an inbound socket is accepted.
        /// </summary>
        /// <param name="sock">The accepted socket.</param>
        /// <param name="endPoint">The endpoint the socket was accepted from.</param>
        private void OnAccept(EnhancedSocket sock, IPEndPoint endPoint)
        {
            var httpState = new HttpAsyncState();
            var recvBuf   = new byte[RecvBlockSize];

            using (TimedLock.Lock(syncLock))
            {
                if (connections.Count >= maxConnections)
                {
                    sock.AsyncSendClose(new HttpResponse(HttpStatus.ServiceUnavailable, "Server is too busy").Serialize(SendBlockSize));
                    return;
                }

                connections.Add(sock, sock);
            }

            httpState.FirstRequest = true;
            httpState.Request      = new HttpRequest();
            httpState.Socket       = sock;
            httpState.Buffer       = recvBuf;
            httpState.RecvSize     = 0;

            httpState.Request.BeginParse(((IPEndPoint)sock.LocalEndPoint).Port);
            sock.BeginReceive(recvBuf, 0, recvBuf.Length, SocketFlags.None, onRecv, httpState);
        }
Example #4
0
        public void HttpConnection_Query_Timeout()
        {
            EnhancedSocket sockListen = null;
            EnhancedSocket sockAccept = null;
            HttpConnection con;
            HttpRequest    request;
            HttpResponse   response;
            string         content;
            TimeSpan       orgTimeout;
            IAsyncResult   ar;

            orgTimeout = HttpStack.TimeoutSweepInterval;
            HttpStack.TimeoutSweepInterval = TimeSpan.FromMilliseconds(250);

            sockListen = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sockListen.Bind(new IPEndPoint(IPAddress.Any, ServerPort));
            sockListen.Listen(10);

            try
            {
                ar = sockListen.BeginAccept(null, null);

                con = new HttpConnection(HttpOption.None);
                con.Connect("http://localhost:" + ServerPort.ToString());

                sockAccept = sockListen.EndAccept(ar);

                content             = "Test: Timeout";
                request             = new HttpRequest("GET", "/foo.htm", null);
                request["Response"] = content;
                request["Close"]    = "no";

                try
                {
                    response = con.Query(request, SysTime.Now + TimeSpan.FromMilliseconds(250));
                    Thread.Sleep(1000);
                    Assert.Fail();
                }
                catch (TimeoutException)
                {
                }

                Assert.IsTrue(con.IsClosed);
                con.Close();
            }
            finally
            {
                HttpStack.TimeoutSweepInterval = orgTimeout;

                if (sockListen != null)
                {
                    sockListen.Close();
                }

                if (sockAccept != null)
                {
                    sockAccept.Close();
                }
            }
        }
Example #5
0
        private int cbRecv;                         // Bytes to receive

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="router">The associated message router.</param>
        public TcpChannel(MsgRouter router)
        {
            this.router        = router;
            this.sock          = null;
            this.routerEP      = null;
            this.remoteEP      = null;
            this.localEP       = null;
            this.connected     = false;
            this.initProcessed = false;
            this.lastAccess    = SysTime.Now;
            this.isUplink      = false;
            this.isDownlink    = false;
            this.isP2P         = false;

            this.sending   = false;
            this.sendMsg   = null;
            this.sendQueue = new PriorityQueue <Msg>();
            this.onSend    = new AsyncCallback(OnSend);
            this.sendBuf   = null;
            this.sendPos   = 0;
            this.cbSend    = 0;

            this.onReceive  = new AsyncCallback(OnReceive);
            this.recvHeader = false;
            this.recvBuf    = null;
            this.recvPos    = 0;
        }
Example #6
0
        /// <summary>
        /// Starts the transport.
        /// </summary>
        /// <param name="binding">The network binding the transport will use.</param>
        /// <param name="cbSocketBuffer">Size of the socket's send and receive buffers in bytes.</param>
        /// <param name="router">The <see cref="ISipMessageRouter" /> instance that will handle the routing of received messages.</param>
        /// <exception cref="SocketException">Thrown if there's a conflict with the requested and existing socket bindings.</exception>
        public void Start(NetworkBinding binding, int cbSocketBuffer, ISipMessageRouter router)
        {
            try
            {
                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sock.SendBufferSize           = cbSocketBuffer;
                sock.ReceiveBufferSize        = cbSocketBuffer;
                sock.IgnoreUdpConnectionReset = true;
                sock.Bind(binding);

                this.localEP   = (IPEndPoint)sock.LocalEndPoint;
                this.onRecv    = new AsyncCallback(OnReceive);
                this.recvBuf   = new byte[64 * 1024];
                this.recvEP    = new IPEndPoint(IPAddress.Any, 0);
                this.router    = router;
                this.traceMode = SipTraceMode.None;

                recvPending = true;
                sock.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref recvEP, onRecv, null);
            }
            catch
            {
                if (sock.IsOpen)
                {
                    sock.Close();
                }

                sock = null;
                throw;
            }
        }
Example #7
0
 /// <summary>
 /// Initates an asynchronous connection to the server whose network
 /// endpoint is specified.
 /// </summary>
 /// <param name="endPoint">The network endpoint.</param>
 /// <param name="callback">The delegate to call when the operation completes (or <c>null</c>).</param>
 /// <param name="state">Application state.</param>
 /// <returns>The async result used to track the operation.</returns>
 public IAsyncResult BeginConnect(IPEndPoint endPoint, AsyncCallback callback, object state)
 {
     using (TimedLock.Lock(this))
     {
         sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         return(sock.BeginConnect(endPoint, callback, state));
     }
 }
Example #8
0
            private void Reset()
            {
                cbTransfer     = 0;
                syncCompletion = false;
                asyncException = null;
                acceptSock     = null;

                asyncEvent.Reset();
            }
Example #9
0
            public ushort NextQID;                  // The next DNS query ID

            /// <summary>
            /// Constructor.
            /// </summary>
            /// <param name="socket">The real socket.</param>
            /// <param name="socketID">Index of the socket in the sockets array.</param>
            public DnsSocket(EnhancedSocket socket, ushort socketID)
            {
                this.Socket     = socket;
                this.SocketID   = socketID;
                this.RecvPacket = new byte[512];
                this.FromEP     = new IPEndPoint(IPAddress.Any, 0);
                this.NextQID    = (ushort)Helper.Rand();    // Initialize with a random number as a
                                                            // weak step towards avoiding DNS poisoning.
            }
Example #10
0
            public AsyncSocket(EnhancedSocket sock)
            {
                this.sock      = sock;
                this.onConnect = new AsyncCallback(OnConnect);
                this.onAccept  = new AsyncCallback(OnAccept);
                this.onSendBuf = new AsyncCallback(OnSendBuf);
                this.onRecvBuf = new AsyncCallback(OnRecvBuf);

                Reset();
            }
Example #11
0
        private System.Net.EndPoint recvEP;             // Receives the transmitting socket's endpoint

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="router">The associated message router.</param>
        public UdpChannel(MsgRouter router)
        {
            this.router          = router;
            this.isOpen          = false;
            this.sock            = null;
            this.port            = 0;
            this.recvEP          = new IPEndPoint(IPAddress.Any, 0);
            this.multicastInit   = false;
            this.broadcastClient = null;
        }
Example #12
0
            public NetReflector(int port)
            {
                // Initialize the UDP service.

                udpSock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                udpSock.Bind(new IPEndPoint(IPAddress.Any, port));

                udpRecvBuf   = new byte[bufSize];
                udpRemoteEP  = new IPEndPoint(IPAddress.Any, 0);
                onUdpReceive = new AsyncCallback(OnUdpReceive);
                udpSock.BeginReceiveFrom(udpRecvBuf, 0, udpRecvBuf.Length, SocketFlags.None, ref udpRemoteEP, onUdpReceive, null);

                // Initialize the TCP service.

                onTcpReceive   = new AsyncCallback(OnTcpReceive);
                tcpConnections = new List <EnhancedSocket>();

                listener = new SocketListener();
                listener.SocketAcceptEvent +=
                    (s, a) =>
                {
                    lock (syncLock)
                    {
                        try
                        {
                            var sock      = (EnhancedSocket)s;
                            var remoteEP  = (IPEndPoint)sock.RemoteEndPoint;
                            var prefix    = PadPrefix(string.Format("TCP[{0}:{1}]:", remoteEP.Address, remoteEP.Port));
                            var recvState = new TcpRecvState()
                            {
                                Socket = sock, Buffer = new byte[bufSize]
                            };

                            if (TcpConnected != null)
                            {
                                TcpConnected(this, new NetReflectorEventArgs()
                                {
                                    Endpoint = remoteEP
                                });
                            }

                            Debug.WriteLine(string.Format("{0} Connect", prefix));
                            tcpConnections.Add(sock);

                            sock.BeginReceive(recvState.Buffer, 0, recvState.Buffer.Length, SocketFlags.None, onTcpReceive, recvState);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(string.Format("*** {0}: {1}", e.GetType().Name, e.Message));
                        }
                    }
                };

                listener.Start(new IPEndPoint(IPAddress.Any, port), 100);
            }
Example #13
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 #14
0
        /// <summary>
        /// Initiates a network connection to the message router at the
        /// specified network endpoint and then initiates the transmission
        /// of the message once the connection is established.
        /// </summary>
        /// <param name="ep">The remote router's endpoint.</param>
        /// <param name="msg">The message to be sent (or <c>null</c>).</param>
        public void Connect(IPEndPoint ep, Msg msg)
        {
            using (TimedLock.Lock(router.SyncRoot))
            {
                Assertion.Test(sock == null);
                sock    = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                localEP = new ChannelEP(Transport.Tcp, router.NormalizeEP(router.TcpEP));

                sock.NoDelay           = !router.TcpDelay;
                sock.SendBufferSize    = router.TcpSockConfig.SendBufferSize;
                sock.ReceiveBufferSize = router.TcpSockConfig.ReceiveBufferSize;

                if (router.FragmentTcp)
                {
                    sock.SendMax    = 1;
                    sock.ReceiveMax = 1;
                }

                // Queue the channel initialization message and the message passed

                Msg initMsg;

                initMsg      = new TcpInitMsg(router.RouterEP, new MsgRouterInfo(router), isUplink, router.TcpEP.Port);
                initMsg._TTL = 1;

                Serialize(initMsg);
                Enqueue(initMsg);

                try
                {
                    SetLastAccess();
                    remoteEP = new ChannelEP(Transport.Tcp, router.NormalizeEP(ep));

                    if (msg != null)
                    {
                        msg._SetToChannel(remoteEP);
                        msg._SetFromChannel(localEP);
                        msg._Trace(router, 2, "TCP: Queue", null);

                        Serialize(msg);
                        Enqueue(msg);
                    }

                    router.Trace(2, "TCP: Outbound", "LocalEP=" + localEP.NetEP.ToString() + " remoteEP=" + remoteEP.NetEP.ToString(), null);
                    sock.BeginConnect(remoteEP.NetEP, new AsyncCallback(OnConnect), null);
                }
                catch (Exception e)
                {
                    router.Trace(string.Format(null, "TCP: Connect Failed [{0}]", ep), e);
                    router.OnTcpClose(this);
                    Close();
                }
            }
        }
Example #15
0
 /// <summary>
 /// Stops the DNS server if it is running.
 /// </summary>
 public void Stop()
 {
     lock (syncLock)
     {
         if (sock != null)
         {
             sock.Close();
             sock = null;
         }
     }
 }
Example #16
0
 private EnhancedSocket WaitForAccept()
 {
     try
     {
         wait.WaitOne();
         return(sockAccept);
     }
     finally
     {
         sockAccept = null;
     }
 }
Example #17
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 #18
0
            public void Close()
            {
                if (sock == null)
                {
                    return;
                }

                using (TimedLock.Lock(transport))
                {
                    sock.ShutdownAndClose();
                    sock = null;
                }
            }
Example #19
0
        private byte[] udpConnectPacket;                // Initial UDP connection packet or null

        /// <summary>
        /// Constructs an TCP or UDP socket based on the parameter passed.
        /// </summary>
        /// <param name="isTcp">Pass <c>true</c> for a TCP socket, <c>false</c> for a UDP socket.</param>
        private LiteSocket(bool isTcp)
        {
            this.isTcp = isTcp;

            if (isTcp)
            {
                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            else
            {
                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            }
        }
Example #20
0
 /// <summary>
 /// Constructs an HTTP connection.
 /// </summary>
 /// <param name="options">The connection options.</param>
 /// <param name="cbContentMax">Maximum allowed content size or <b>-1</b> to disable checking.</param>
 /// <param name="perfBytesRecv">Performance counter to receive updates about bytes received (or <c>null</c>).</param>
 /// <param name="perfBytesSent">Performance counter to receive updates about bytes sent (or <c>null</c>).</param>
 public HttpConnection(HttpOption options, int cbContentMax, PerfCounter perfBytesRecv, PerfCounter perfBytesSent)
 {
     this.id             = AllocID();
     this.cbContentMax   = cbContentMax;
     this.sock           = null;
     this.ipAddress      = IPAddress.Any;
     this.options        = options;
     this.timedOut       = false;
     this.onRequestSent  = new AsyncCallback(OnRequestSent);
     this.onResponseRecv = new AsyncCallback(OnResponseReceived);
     this.perfBytesRecv  = perfBytesRecv;
     this.perfBytesSent  = perfBytesSent;
 }
Example #21
0
        /// <summary>
        /// Called by the socket listener whenever a connection is accepted.
        /// </summary>
        /// <param name="sock">The new connection.</param>
        /// <param name="acceptEP">The remote endpoint.</param>
        private void OnAccept(EnhancedSocket sock, IPEndPoint acceptEP)
        {
            // $todo(jeff.lill): This is where I need to add source filtering.

            var remoteEP = (IPEndPoint)sock.RemoteEndPoint;

            using (TimedLock.Lock(this))
            {
                sock.SendBufferSize    = cbSocketBuffer;
                sock.ReceiveBufferSize = cbSocketBuffer;

                connections.Add(remoteEP.ToString(), new Connection(this, sock, remoteEP));
            }
        }
Example #22
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 #23
0
        /// <summary>
        /// Initates an asynchronous connection to the server whose host and
        /// port are specified by a URI.
        /// </summary>
        /// <param name="uri">The uri.</param>
        /// <param name="callback">The delegate to call when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application state.</param>
        /// <returns>The async result used to track the operation.</returns>
        public IAsyncResult BeginConnect(string uri, AsyncCallback callback, object state)
        {
            var u = new Uri(uri);

            using (TimedLock.Lock(this))
            {
                if (sock != null)
                {
                    throw new InvalidOperationException(AlreadyConnectedMsg);
                }

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                return(sock.BeginConnect(u.Host, u.Port, callback, state));
            }
        }
Example #24
0
            private SipMessage message;                         // The message we're receiving contents for

            public Connection(SipTcpTransport transport, EnhancedSocket sock, IPEndPoint remoteEP)
            {
                this.transport   = transport;
                this.sock        = sock;
                this.remoteEP    = remoteEP;
                this.sendQueue   = new Queue <SipMessage>();
                this.onSend      = new AsyncCallback(OnSend);
                this.onRecv      = new AsyncCallback(OnReceive);
                this.sendPending = false;

                this.headerBuf  = new byte[MaxHeaderSize];
                this.contentBuf = null;
                this.cbRecv     = 0;

                sock.BeginReceive(headerBuf, 0, headerBuf.Length, SocketFlags.None, onRecv, null);
            }
Example #25
0
 private void OnAccept(IAsyncResult ar)
 {
     try
     {
         syncCompletion = ar.CompletedSynchronously;
         acceptSock     = sock.EndAccept(ar);
     }
     catch (Exception e)
     {
         asyncException = e;
     }
     finally
     {
         asyncEvent.Set();
     }
 }
Example #26
0
        /// <summary>
        /// Simulates a UDP broadcast client failure by closing the instance without
        /// transmitting <b>Server.Unregister</b> messages.
        /// </summary>
        internal void CloseFail()
        {
            lock (syncLock)
            {
                if (socket != null)
                {
                    socket.Close();
                    socket = null;
                }

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }
            }
        }
Example #27
0
        public void EnhancedSocket_Async_ConnectToHost()
        {
            EnhancedSocket sock;
            IAsyncResult   ar;
            IPAddress      addr;

            sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ar   = sock.BeginConnect("www.google.com", 80, null, null);
            sock.EndConnect(ar);
            addr = ((IPEndPoint)sock.RemoteEndPoint).Address;
            sock.Close();

            sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ar   = sock.BeginConnect(addr.ToString(), 80, null, null);
            sock.EndConnect(ar);
            sock.Close();
        }
Example #28
0
        private void Init(SocketListener listener)
        {
            if (sockAccept != null)
            {
                sockAccept.Close();
                sockAccept = null;
            }

            if (wait != null)
            {
                wait.Close();
                wait = null;
            }

            wait = new AutoResetEvent(false);
            listener.SocketAcceptEvent += new SocketAcceptDelegate(OnAccept);
        }
Example #29
0
        /// <summary>
        /// Implements the listening thread.
        /// </summary>
        private void ListenLoop()
        {
            EnhancedSocket sockListen = sockParam;
            EnhancedSocket sockAccept;

            try
            {
                threadStart.Set();      // Indicate that we have the socket parameter

                // Loop forever or until we get an exception.  This thread is
                // terminated by closing the listening socket which will cause
                // Accept() to throw an exception.

                while (true)
                {
                    try
                    {
                        sockAccept = sockListen.Accept();
                        if (sockAccept == null)
                        {
                            return;
                        }

                        // Queue the accept so that further processing will happen
                        // on a pool thread, leaving this thread free to accept
                        // additional incoming connections.

                        ThreadPool.UnsafeQueueUserWorkItem(onAccept, new object[] { sockAccept, sockListen.LocalEndPoint });
                    }
                    catch
                    {
                        return;
                    }
                }
            }
            catch (SocketClosedException)
            {
                // Ignore these
            }
            catch (Exception e)
            {
                SysLog.LogException(e);
            }
        }
Example #30
0
        /// <summary>
        /// Opens a RADIUS client port using the <see cref="RadiusClientSettings" /> passed.
        /// </summary>
        /// <param name="settings">The client settings.</param>
        /// <remarks>
        /// <note>
        /// All successful calls to <see cref="Open" /> must eventually be matched
        /// with a call to <see cref="Close" /> so that system resources will be
        /// released promptly.
        /// </note>
        /// </remarks>
        public void Open(RadiusClientSettings settings)
        {
            using (TimedLock.Lock(this))
            {
                if (isOpen)
                {
                    throw new RadiusException("RADIUS client port is already open.");
                }

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sock.Bind(settings.NetworkBinding);
                this.sock.SendBufferSize    = settings.SocketBuffer;
                this.sock.ReceiveBufferSize = settings.SocketBuffer;

                isOpen           = true;
                networkBinding   = settings.NetworkBinding;
                servers          = settings.Servers;
                secret           = settings.Secret;
                retryInterval    = settings.RetryInterval;
                maxTransmissions = settings.MaxTransmissions;
                realmFormat      = settings.RealmFormat;

                nextID       = 0;
                serverPos    = 0;
                transactions = new AuthTransaction[256];
                recvBuf      = new byte[TcpConst.MTU];
                sourceEP     = new IPEndPoint(IPAddress.Any, 0);
                onReceive    = new AsyncCallback(OnReceive);

                if (networkBinding.Address.Equals(IPAddress.Any))
                {
                    nasIPAddress = NetHelper.GetActiveAdapter();
                }
                else
                {
                    nasIPAddress = networkBinding.Address;
                }

                // Initiate reception of the first RADIUS packet.

                sock.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref sourceEP, onReceive, null);
            }
        }