Example #1
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);
            }
        }
Example #2
0
        /// <summary>
        /// Starts the DNS server using the settings passed.
        /// </summary>
        /// <param name="settings">The <see cref="DnsServerSettings" /> to be used to initialize the server.</param>
        /// <exception cref="InvalidOperationException">Thrown if the server has already started.</exception>
        public void Start(DnsServerSettings settings)
        {
            lock (syncLock)
            {
                if (sock != null)
                {
                    throw new InvalidOperationException("DNS server has already started.");
                }

                sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sock.IgnoreUdpConnectionReset = true;
                sock.ReceiveBufferSize        =
                    sock.ReceiveBufferSize    = 1024 * 1024;  // $todo(jeff.lill): Hardcoded
                sock.Bind(settings.NetworkBinding);

                remoteEP = new IPEndPoint(IPAddress.Any, 0);
                sock.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref remoteEP, onReceive, sock);
            }
        }
Example #3
0
        /// <summary>
        /// Attempts to start a listener on the endpoint specified.  Check for
        /// SocketExceptions.
        /// </summary>
        /// <param name="localEP">The TCP endpoint to listen on.</param>
        /// <param name="maxBackLog">
        /// The maximum number of socket connection attempts to queue.
        /// </param>
        /// <remarks>
        /// This method is not threadsafe.  The intention is that this method will be called
        /// one or more times on the application's startup thread and then not be called
        /// again.
        /// </remarks>
        public void Start(IPEndPoint localEP, int maxBackLog)
        {
            Listener       listener;
            EnhancedSocket sock;

            if (localEP.Port == 0)
            {
                throw new ArgumentException("Endpoint port cannot be 0.", "localEP");
            }

            if (listeners[localEP] != null)
            {
                throw new InvalidOperationException("Already listening on this port.");
            }

            sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.DisableHangTest = true;
            sock.Blocking        = true;
            sock.Bind(localEP);
            sock.Listen(maxBackLog);

            listener = new Listener(new Thread(new ThreadStart(ListenLoop)), localEP, sock);
            listeners.Add(localEP, listener);

            // Start the listening thread, passing in the socket.  Note that this
            // is the code that prevents the method from being threadsafe.

            sockParam   = sock;
            threadStart = new ManualResetEvent(false);

            listener.Thread.Start();

            threadStart.WaitOne();
            threadStart.Close();
            threadStart = null;
            sockParam   = null;
        }
Example #4
0
        /// <summary>
        /// Creates and starts a UDP broadcast server using the settings passed.
        /// </summary>
        /// <param name="settings">The server settings.</param>
        /// <param name="perfCounters">The application's performance counters (or <c>null</c>).</param>
        /// <param name="perfPrefix">The string to prefix any performance counter names (or <c>null</c>).</param>
        /// <remarks>
        /// <note>
        /// The <paramref name="perfCounters" /> parameter is type as <see cref="object" /> so that
        /// applications using this class will not be required to reference the <b>LillTel.Advanced</b>
        /// assembly.
        /// </note>
        /// </remarks>
        /// <exception cref="ArgumentException">Thrown if the settings passed are not valid.</exception>
        public UdpBroadcastServer(UdpBroadcastServerSettings settings, object perfCounters, string perfPrefix)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (settings.Servers == null || settings.Servers.Length == 0)
            {
                throw new ArgumentException("Invalid UDP broadcast server settings: At least one broadcast server endpoint is required.");
            }

            if (perfCounters != null && !(perfCounters is PerfCounterSet))
            {
                throw new ArgumentException("Only instances of type [PerfCounterSet] may be passed in the [perfCounters] parameter.", "perfCounters");
            }

            this.startTime    = DateTime.UtcNow;
            this.closePending = false;
            this.settings     = settings;
            this.perf         = new Perf(perfCounters as PerfCounterSet, perfPrefix);

            bool found = false;

            for (int i = 0; i < settings.Servers.Length; i++)
            {
                var binding = settings.Servers[i];

                if (binding == settings.NetworkBinding)
                {
                    found = true;

                    // I'm going to special case the situation where the network binding address is ANY.
                    // In this case, one of the server endpoints must also include an ANY entry and I'll
                    // fill out with the loop back addres (127.1.0.1).

                    if (binding.IsAnyAddress)
                    {
                        settings.Servers[i] = new NetworkBinding(IPAddress.Loopback, settings.Servers[i].Port);
                    }

                    break;
                }
            }

            if (!found)
            {
                if (!settings.NetworkBinding.IsAnyAddress)
                {
                    throw new ArgumentException("Invalid UDP broadcast server settings: The current server's network binding must also be present in the Servers[] bindings.");
                }
            }

            // Initialize the clients and servers state.

            clients = new Dictionary <IPEndPoint, ClientState>();
            servers = new Dictionary <IPEndPoint, ServerState>();

            // Open the socket and start receiving packets.

            socket = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.IgnoreUdpConnectionReset = true;
            socket.ReceiveBufferSize        = settings.SocketBufferSize;
            socket.SendBufferSize           = settings.SocketBufferSize;

            socket.Bind(settings.NetworkBinding);

            onReceive = new AsyncCallback(OnReceive);
            recvBuf   = new byte[TcpConst.MTU];

            rawRecvEP = new IPEndPoint(IPAddress.Any, 0);
            socket.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref rawRecvEP, onReceive, null);

            // Crank up a timer to send the ClientRegister messages to the server cluster.

            registerTimer = new PolledTimer(settings.ClusterKeepAliveInterval, true);
            registerTimer.FireNow();    // Make sure that we send registration messages immediately

            bkTimer = new GatedTimer(new TimerCallback(OnBkTask), null, TimeSpan.Zero, settings.BkTaskInterval);
        }
Example #5
0
 public void ListenOn(IPEndPoint localEP)
 {
     sock.Bind(localEP);
     sock.Listen(100);
 }
Example #6
0
        public void HttpConnection_Receive_Fail()
        {
            EnhancedSocket sockListen = null;
            EnhancedSocket sockAccept = null;
            HttpConnection con;
            HttpRequest    request;
            HttpResponse   response;
            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);

                request = new HttpRequest("GET", "/foo.htm", null);
                request["Content-Length"] = request.Content.Size.ToString();

                ar = con.BeginQuery(request, DateTime.MaxValue, null, null);
                Thread.Sleep(100);

                sockAccept.Close();
                sockAccept = null;

                try
                {
                    response = con.EndQuery(ar);
                    Assert.Fail();
                }
                catch
                {
                }

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

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

                if (sockAccept != null)
                {
                    sockAccept.Close();
                }
            }
        }
Example #7
0
        /// <summary>
        /// Creates and starts a UDP broadcast client using the settings passed.
        /// </summary>
        /// <param name="settings">The client settings.</param>
        /// <exception cref="ArgumentException">Thrown if the settings passed are not valid.</exception>
        public UdpBroadcastClient(UdpBroadcastClientSettings settings)
        {
            this.settings = settings;

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (settings.Servers == null || settings.Servers.Length == 0)
            {
                throw new ArgumentException("Invalid UDP broadcast client settings: At least one broadcast server endpoint is required.");
            }

            this.servers = new List <IPEndPoint>();

            // $hack(jeff.lill)
            //
            // This is a bit of a hack to discover the source IP address to use for this instance.
            // If the configured NetworkBinding specifies a specific interface, then we'll use
            // this, otherwise we'll use the IPv4 address for the first active network adaptor we find.
            // In a perfect world, I'd send a packet to the broadcast servers and have it respond with
            // the UDP source address it sees that would discover the actual IP address.  This hack
            // should work 99% of the time though.

            if (!settings.NetworkBinding.Address.Equals(IPAddress.Any))
            {
                this.sourceAddress = settings.NetworkBinding.Address;
            }
            else
            {
                this.sourceAddress = NetHelper.GetActiveAdapter();
            }

            // Open the socket and start receiving packets.

            socket = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.IgnoreUdpConnectionReset = true;
            socket.ReceiveBufferSize        = settings.SocketBufferSize;
            socket.SendBufferSize           = settings.SocketBufferSize;

            socket.Bind(settings.NetworkBinding);

            onReceive = new AsyncCallback(OnReceive);
            recvBuf   = new byte[8192];

            rawRecvEP = new IPEndPoint(IPAddress.Any, 0);
            socket.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref rawRecvEP, onReceive, null);

            // Crank up the timers.

            keepAliveTimer = new PolledTimer(settings.KeepAliveInterval, false);
            keepAliveTimer.FireNow();

            serverResolveTimer = new PolledTimer(settings.ServerResolveInterval, false);
            serverResolveTimer.FireNow();

            bkTimer = new GatedTimer(new TimerCallback(OnBkTask), null, TimeSpan.Zero, settings.BkTaskInterval);

            // Sleep for a couple seconds to allow the server DNS lookups to complete.

            Thread.Sleep(2000);
        }
Example #8
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);
            }
        }