Example #1
0
        public void NetworkBinding_KnownPorts()
        {
            Map[] ports = new Map[] {
                new Map("HTTP", 80),
                new Map("SSL", 443),
                new Map("DNS", 53),
                new Map("SMTP", 25),
                new Map("POP3", 110),
                new Map("TELNET", 23),
                new Map("FTP", 21),
                new Map("FTPDATA", 20),
                new Map("SFTP", 22),
                new Map("RADIUS", 1812),
                new Map("AAA", 1645),
                new Map("ECHO", 7),
                new Map("DAYTIME", 13),
                new Map("TFTP", 69),
                new Map("SSH", 22),
                new Map("TIME", 37),
                new Map("NTP", 123),
                new Map("IMAP", 143),
                new Map("SNMP", 161),
                new Map("SNMTRAP", 162),
                new Map("LDAP", 389),
                new Map("LDAPS", 636),
                new Map("HTTP-HEARTBEAT", 9167),
                new Map("NETTRACE", 47743),
                new Map("LILLCOM", 4530)
            };

            foreach (Map map in ports)
            {
                Assert.AreEqual(map.Port, NetworkBinding.Parse("127.0.0.1:" + map.Name).Port);
            }
        }
Example #2
0
        public void NetworkBinding_Parse()
        {
            NetworkBinding binding;

            binding = NetworkBinding.Parse("0.0.0.0:0");
            Assert.AreEqual(IPAddress.Any, binding.Address);
            Assert.AreEqual(0, binding.Port);

            binding = NetworkBinding.Parse("1.2.3.4:5");
            Assert.AreEqual(IPAddress.Parse("1.2.3.4"), binding.Address);
            Assert.AreEqual(5, binding.Port);

            binding = NetworkBinding.Parse("localhost:7890");
            Assert.AreEqual("localhost", binding.Host);
            Assert.AreEqual(7890, binding.Port);
            Assert.AreEqual(IPAddress.Loopback, binding.Address);

            binding = NetworkBinding.Parse("Any:55");
            Assert.AreEqual(IPAddress.Any, binding.Address);
            Assert.AreEqual(55, binding.Port);
            Assert.IsFalse(binding.IsHost);

            binding = NetworkBinding.Parse("ANY");
            Assert.AreEqual(IPAddress.Any, binding.Address);
            Assert.AreEqual(0, binding.Port);
            Assert.IsFalse(binding.IsHost);
        }
Example #3
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 #4
0
        private NetworkBinding remoteEP;                    // The message source endpoint

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="isRequest"><c>true</c> if the message is a SIP request, false for a response</param>
        /// <param name="sipVersion">The SIP version string (or <c>null</c>).</param>
        internal SipMessage(bool isRequest, string sipVersion)
        {
            this.isRequest         = isRequest;
            this.sipVersion        = sipVersion == null ? "SIP/2.0" : sipVersion.ToUpper();
            this.headers           = new SipHeaderCollection();
            this.contents          = emptyPayload;
            this.sourceTransaction = null;
            this.sourceTransport   = null;
            this.remoteEP          = null;
        }
        private void TeamConfig_Click(object sender, RoutedEventArgs e)
        {
            TeamSettingsDialog teamSettings = new TeamSettingsDialog(settings);

            if (teamSettings.ShowDialog() == true)
            {
                settings = teamSettings.GetSettings();
                NetworkBinding.Refresh(settings.TeamNumber, settings.UsingDriverStation);
            }
        }
 private void SourcedSpinner_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.NewSource))
     {
         NetworkBinding.Update(spinner, DoubleUpDown.ValueProperty, e.NewSource);
     }
     else
     {
         NetworkBinding.Delete(spinner, DoubleUpDown.ValueProperty);
     }
 }
Example #7
0
        /// <summary>
        /// Constructs a SIP URI from the parameters passed.
        /// </summary>
        /// <param name="transportType">The transport type.</param>
        /// <param name="binding">The <see cref="NetworkBinding" />.</param>
        /// <remarks>
        /// Passing <paramref name="transportType"/> as <see cref="SipTransportType.TLS" />
        /// will result in a <i>secure</i> URI.  Passing <paramref name="transportType"/> as
        /// <see cref="SipTransportType.TCP" /> will return a URI with a <b>transport=tcp</b>
        /// parameter.
        /// </remarks>
        public SipUri(SipTransportType transportType, NetworkBinding binding)
        {
            this.isSecure = transportType == SipTransportType.TLS;
            this.host     = binding.IsHost ? binding.Host : binding.Address.ToString();
            this.port     = binding.Port;

            if (transportType == SipTransportType.TCP)
            {
                parameters.Add("transport", "tcp");
            }
        }
Example #8
0
        /// <summary>
        /// Constructs an instance from settings passed as explicit parameters.
        /// </summary>
        /// <param name="transportType">The desired <see cref="SipTransportType" />.</param>
        /// <param name="binding">The network binding to be associated with the transport.</param>
        /// <param name="bufferSize">Size of the transport socket's send and receive buffers (or 0 for a reasonable default).</param>
        public SipTransportSettings(SipTransportType transportType, NetworkBinding binding, int bufferSize)
        {
            this.TransportType = transportType;
            this.Binding       = binding;
            this.BaseTimers    = new SipBaseTimers();

            if (bufferSize > 0)
            {
                this.BufferSize = bufferSize;
            }
        }
 private void NumberDisplay_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.NewSource))
     {
         NetworkBinding.Update(display, TextBlock.TextProperty, e.NewSource, converter);
     }
     else
     {
         NetworkBinding.Delete(display, TextBlock.TextProperty);
     }
 }
 private void BoolIndicator_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.NewSource))
     {
         NetworkBinding.Update(this, ValueProperty, e.NewSource);
     }
     else
     {
         NetworkBinding.Delete(this, ValueProperty);
     }
 }
Example #11
0
        public void Extensions_XElement_ParseNetworkBinding()
        {
            XNamespace ns = XNamespace.None;
            XElement   element;

            element = new XElement(ns + "element");
            element.Add(new XElement(XNamespace.None + "test", "10.20.30.40:HTTP"));

            Assert.AreEqual(NetworkBinding.Any, element.ParseElement(ns + "foo", NetworkBinding.Any));
            Assert.AreEqual(NetworkBinding.Parse("10.20.30.40:HTTP"), element.ParseElement(ns + "test", NetworkBinding.Any));
        }
Example #12
0
 private void BoolSwitch_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.NewSource))
     {
         NetworkBinding.Update(s, ToggleSwitch.IsCheckedProperty, e.NewSource);
     }
     else
     {
         NetworkBinding.Delete(s, ToggleSwitch.IsCheckedProperty);
     }
 }
 private void SourcedSlider_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     if (!string.IsNullOrEmpty(e.NewSource))
     {
         NetworkBinding.Update(s, Slider.ValueProperty, e.NewSource);
     }
     else
     {
         NetworkBinding.Delete(s, Slider.ValueProperty);
     }
 }
Example #14
0
        public void NetworkBinding_Basic()
        {
            NetworkBinding binding;

            binding = new NetworkBinding(IPAddress.Loopback, 55);
            Assert.IsFalse(binding.IsHost);
            Assert.IsNull(binding.Host);
            Assert.AreEqual(IPAddress.Loopback, binding.Address);
            Assert.AreEqual(55, binding.Port);
            Assert.AreEqual("127.0.0.1:55", binding.ToString());

            binding = new NetworkBinding("localhost", 55);
            Assert.IsTrue(binding.IsHost);
            Assert.IsNotNull(binding.Host);
            Assert.AreEqual(IPAddress.Loopback, binding.Address);
            Assert.AreEqual(55, binding.Port);
            Assert.AreEqual("localhost:55", binding.ToString());

            binding = new NetworkBinding("any", 55);
            Assert.AreEqual(IPAddress.Any, binding.Address);
            Assert.AreEqual(55, binding.Port);
            Assert.IsFalse(binding.IsHost);

            Assert.AreEqual(IPAddress.Any, NetworkBinding.Any.Address);
            Assert.AreEqual(0, NetworkBinding.Any.Port);
            Assert.IsNull(NetworkBinding.Any.Host);
            Assert.IsFalse(NetworkBinding.Any.IsHost);
            Assert.AreEqual("0.0.0.0:0", NetworkBinding.Any.ToString());

            Assert.AreNotEqual(NetworkBinding.Parse("1.2.3.4:5").GetHashCode(), NetworkBinding.Parse("2.3.4.5:6").GetHashCode());
            Assert.AreNotEqual(NetworkBinding.Parse("1.2.3.4:5").GetHashCode(), NetworkBinding.Parse("1.2.3.4:6").GetHashCode());
            Assert.AreNotEqual(NetworkBinding.Parse("1.2.3.4:5").GetHashCode(), NetworkBinding.Parse("2.3.4.5:5").GetHashCode());

            Assert.IsTrue(NetworkBinding.Parse("1.2.3.4:5").Equals(NetworkBinding.Parse("1.2.3.4:5")));
            Assert.IsFalse(NetworkBinding.Parse("1.2.3.4:5").Equals(NetworkBinding.Parse("1.2.3.4:6")));
            Assert.IsFalse(NetworkBinding.Parse("1.2.3.5:5").Equals(NetworkBinding.Parse("1.2.3.4:5")));
            Assert.IsFalse(NetworkBinding.Parse("localhost:0").Equals(NetworkBinding.Parse("0.0.0.0:0")));

            binding = new NetworkBinding(IPAddress.Loopback, 55);
            Assert.AreEqual("127.0.0.1", binding.HostOrAddress);
            Assert.IsFalse(binding.IsAny);

            binding = new NetworkBinding("www.lilltek.com", 55);
            Assert.AreEqual("www.lilltek.com", binding.HostOrAddress);
            Assert.IsFalse(binding.IsAny);

            binding = new NetworkBinding("www.lilltek.com", 0);
            Assert.IsTrue(binding.IsAny);

            binding = new NetworkBinding(IPAddress.Any, 55);
            Assert.IsTrue(binding.IsAny);
        }
Example #15
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="agent">The <see cref="ISipAgent" /> that owns this transaction.</param>
        /// <param name="id">The globally unique transaction ID.</param>
        /// <param name="transport">The <see cref="ISipTransport" /> to be used for this transaction.</param>
        /// <param name="ttd">(Time-to-die) The time (SYS) where the transaction should terminate itself regardless of its current state.</param>
        public SipServerTransaction(SipServerAgent agent, string id, ISipTransport transport, DateTime ttd)
            : base(agent, id, transport)
        {
            this.ttd       = ttd;
            this.agent     = (SipServerAgent)agent;
            this.transport = transport;
            this.isUdp     = !transport.IsStreaming;

            this.request             = null;
            this.remoteEP            = null;
            this.provisionalResponse = null;
            this.finalResponse       = null;
        }
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     //init network table and put test camera
     settings = SaveFileManager.LoadSettings();
     NetworkBinding.Initialize(settings.TeamNumber, Dispatcher, settings.UsingDriverStation);
     //NetworkTable.GetTable("").PutStringArray("CameraPublisher/Fake Camera 0/streams", new List<string>());
     treeUpdateTimer = new DispatcherTimer(DispatcherPriority.Background, Dispatcher)
     {
         Interval = TimeSpan.FromSeconds(0.1)
     };
     treeUpdateTimer.Tick += TreeUpdateTimer_Tick;
     treeUpdateTimer.Start();
 }
 private void PowerUpFieldCodeOnly_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     //this is what we need to do if we get a new network source
     if (string.IsNullOrWhiteSpace(e.NewSource))
     {
         //if the new source is bad, just unbind the old one
         NetworkBinding.Delete(this, PowerUpFieldCodeOnly.ScaleValuesProperty);
     }
     else
     {
         //otherwise create/update the binding using a converter
         NetworkBinding.Update(this, PowerUpFieldCodeOnly.ScaleValuesProperty, e.NewSource, dataConverter);
     }
 }
Example #18
0
        /// <summary>
        /// Returns the <see cref="ISipTransport" /> that will be used to
        /// deliver a <see cref="SipMessage" /> from a source <see cref="ISipAgent" />.
        /// </summary>
        /// <param name="agent">The source agent.</param>
        /// <param name="request">The <see cref="SipRequest" /> to be delivered.</param>
        /// <param name="remoteEP">Returns as the destination server's <see cref="NetworkBinding" />.</param>
        /// <returns>The <see cref="ISipTransport" /> that will be used for delivery (or <c>null</c>).</returns>
        /// <remarks>
        /// <note>
        /// <c>null</c> is a valid return value.  This indicates that there are
        /// no appropriate transports available to deliver this message.
        /// </note>
        /// </remarks>
        public ISipTransport SelectTransport(ISipAgent agent, SipRequest request, out NetworkBinding remoteEP)
        {
            SipTransportType transportType;
            SipUri           proxyUri;

            proxyUri = base.OutboundProxyUri;
            if (proxyUri != null)
            {
                // Select a transport to route the message to the outbound proxy.

                if (!SipHelper.TryGetRemoteBinding("<" + proxyUri + ">", out remoteEP, out transportType))
                {
                    return(null);
                }
            }
            else if (!SipHelper.TryGetRemoteBinding("<" + request.Uri + ">", out remoteEP, out transportType))
            {
                return(null);
            }

            // Select the first transport that looks decent.  If the desired transport
            // is not specified, then favor UDP since most of the world is compatible
            // with that.

            if (transportType == SipTransportType.UDP || transportType == SipTransportType.Unspecified)
            {
                foreach (ISipTransport transport in base.Transports)
                {
                    if (transport.TransportType == SipTransportType.UDP)
                    {
                        return(transport);
                    }
                }

                return(null);
            }

            // Otherwise match the transport.

            foreach (ISipTransport transport in base.Transports)
            {
                if (transport.TransportType == transportType)
                {
                    return(transport);
                }
            }

            return(null);
        }
Example #19
0
        /// <summary>
        /// Establishes a session with the authentication extension.
        /// </summary>
        /// <param name="args">The extension specific arguments (see the remarks).</param>
        /// <param name="query">Ignored for this extension.</param>
        /// <param name="perfCounters">The application's performance counter set (or <c>null</c>).</param>
        /// <param name="perfPrefix">The string to prefix any performance counter names (or <c>null</c>).</param>
        /// <remarks>
        /// <para>
        /// This extension recognises the following arguments:
        /// </para>
        /// <list type="table">
        ///     <item>
        ///         <term>Servers</term>
        ///         <description>
        ///         Specifies the list of RADIUS server network bindings specifying the
        ///         IP address or host name of the server as well as the port number
        ///         or well-known port name.  Each server binding is formatted as
        ///         described by <see cref="NetworkBinding.Parse" /> and the server
        ///         bindings are separated by commas.  This argument must be present.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>Secret</term>
        ///         <description>
        ///         The shared secret to be used to secure RADIUS packets delivered
        ///         between this client and the any of the RADIUS servers.  This
        ///         string may include any valid characters besides semi-colons.
        ///         This argument must be present.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>SocketBuffer</term>
        ///         <description>
        ///         Byte size of the client socket's send and receive buffers.  Default
        ///         value is 32K.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>NetworkBinding</term>
        ///         <description>
        ///         <para>
        ///         Specifies the IP address of the network card the client is
        ///         and port bindings.  Use an IP address of ANY to bind to
        ///         all network interfaces.  ANY is suitable for single homed machines.
        ///         Machines that are actually connected to multiple networks should
        ///         specify a specific network binding here to ensure that the NAS-IP-Address
        ///         of RADIUS authentication packets are initialized properly.
        ///         </para>
        ///         <para>
        ///         A specific port number may be selected or 0 can be specified,
        ///         indicating that the operating system should select a free port.
        ///         </para>
        ///         <para>
        ///         Default value is ANY:0.
        ///         </para>
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>PortCount</term>
        ///         <description>
        ///         The number of RADIUS client UDP ports to open.  Multiple ports may
        ///         be required under high authentication loads.  Default value is 4.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>RetryInterval</term>
        ///         <description>
        ///         Maximum time to wait for a response packet from a RADIUS before retransmitting
        ///         an authentication request.  Default is 5 seconds.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term></term>
        ///         <description>
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>BkTaskInterval</term>
        ///         <description>
        ///         The interval at which background tasks such as retransmitting
        ///         a request should be processed.  Default is 1 second.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>MaxTransmissions</term>
        ///         <description>
        ///         The maximum number of authentication transmission attempts before aborting
        ///         with an authentication with a timeout.  Default is 4.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>RealmFormat</term>
        ///         <description>
        ///         Specifies how user names are to be generated from the
        ///         <b>realm</b> and <b>account</b> components.  See
        ///         <see cref="RealmFormat" /> for more information.
        ///         The possible values are: <b>Slash</b> and <b>Email</b>.
        ///         Default is <b>Email</b>.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>MaxCacheTime</term>
        ///         <description>
        ///         Specifies the maximum time clients should retain authentication information.
        ///         This is expressed in the same format as timespans parsed by <see cref="Config.Parse(string,TimeSpan)" />.
        ///         This argument defaults to "5m".
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutCount</term>
        ///         <description>
        ///         Specifies the limiting failed authentication count.  Accounts
        ///         will be locked when the fail count reaches this number.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutThreshold</term>
        ///         <description>
        ///         The period of time that can elapse between failed authentication
        ///         attempts where the failed attempts will <b>not</b> be counted against the
        ///         <b>LockoutCount</b>.  Set this to <see cref="TimeSpan.Zero" />
        ///         to disable account lockout for the realm.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutTime</term>
        ///         <description>
        ///         The period of time an account will remain locked after being locked
        ///         out due to too many failed authentication attempts.
        ///         </description>
        ///     </item>
        /// </list>
        /// <note>
        /// All calls to <see cref="Open" /> must be matched with a call
        /// to <see cref="Close" /> or <see cref="Dispose" />.
        /// </note>
        /// </remarks>
        public void Open(ArgCollection args, string query, PerfCounterSet perfCounters, string perfPrefix)
        {
            RadiusClientSettings settings;

            string[] rawBindings;
            List <NetworkBinding> bindings;
            string secret;

            using (TimedLock.Lock(this))
            {
                if (IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is already open.");
                }

                perf = new Perf(perfCounters, perfPrefix);

                rawBindings = args.Get("servers", string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (rawBindings.Length == 0)
                {
                    throw new AuthenticationException("RADUIS authentication extension requires at least one server network binding.");
                }

                bindings = new List <NetworkBinding>(rawBindings.Length);
                for (int i = 0; i < rawBindings.Length; i++)
                {
                    bindings.Add(NetworkBinding.Parse(rawBindings[i]));
                }

                secret = args.Get("secret", (string)null);
                if (secret == null || secret.Length == 0)
                {
                    throw new AuthenticationException("RADIUS authentication extension requires a shared NAS secret.");
                }

                settings = new RadiusClientSettings(bindings.ToArray(), secret);
                settings.SocketBuffer     = args.Get("SocketBuffer", settings.SocketBuffer);
                settings.NetworkBinding   = args.Get("NetworkBinding", settings.NetworkBinding);
                settings.PortCount        = args.Get("PortCount", settings.PortCount);
                settings.RetryInterval    = args.Get("RetryInterval", settings.RetryInterval);
                settings.BkTaskInterval   = args.Get("BkTaskInterval", settings.BkTaskInterval);
                settings.MaxTransmissions = args.Get("settings.MaxTransmissions", settings.MaxTransmissions);
                settings.RealmFormat      = args.Get <RealmFormat>("RealmFormat", settings.RealmFormat);

                maxCacheTime = args.Get("MaxCacheTime", TimeSpan.FromMinutes(5));

                radiusClient.Open(settings);
            }
        }
Example #20
0
        public void NetworkBinding_DnsResolve()
        {
            NetworkBinding binding = NetworkBinding.Parse("badhost.UNIT.lilltek.com:55");
            IPAddress      address;

            try
            {
                address = binding.Address;
                Assert.Fail("Expected the DNS resolution to fail.  This test will fail if the current DNS server returns answers to a redirect site.  Many cable Internet providers do this.");
            }
            catch (Exception e)
            {
                Assert.IsInstanceOfType(e, typeof(SocketException));
            }
        }
Example #21
0
 private void SendableChooserControl_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.NewSource))
     {
         NetworkBinding.Update(this, "Options", e.NewSource + "/options");
         NetworkBinding.Update(this, "Default", e.NewSource + "/default");
         NetworkBinding.Update(options, ComboBox.SelectedItemProperty, e.NewSource + "/selected");
     }
     else
     {
         NetworkBinding.Delete(this, "Options");
         NetworkBinding.Delete(this, "Default");
         NetworkBinding.Delete(options, ComboBox.SelectedItemProperty);
     }
 }
 private void PowerUpField_SourceChanged(object sender, NetworkSourceChangedEventArgs e)
 {
     //To handle a source change, we should do a few things.
     //First, we need to check if the new source is valid or not
     if (string.IsNullOrWhiteSpace(e.NewSource))
     {
         //if the new source is bad, just unbind the old one
         NetworkBinding.Delete(this, PowerUpField.ScaleValuesProperty);
     }
     else
     {
         //otherwise create/update the binding using a converter
         NetworkBinding.Update(this, PowerUpField.ScaleValuesProperty, e.NewSource, dataConverter);
     }
 }
Example #23
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="agent">The <see cref="ISipAgent" /> that owns this transaction.</param>
        /// <param name="request">The <see cref="SipRequest" /> initiating the transaction.</param>
        /// <param name="id">The globally unique transaction ID.</param>
        /// <param name="transport">The <see cref="ISipTransport" /> to be used for this tranaaction.</param>
        /// <param name="remoteEP">The server side's <see cref="NetworkBinding" />.</param>
        public SipClientTransaction(SipClientAgent agent, SipRequest request, string id, ISipTransport transport, NetworkBinding remoteEP)
            : base(agent, id, transport)
        {
            if (request.Method == SipMethod.Ack)
            {
                throw new SipException("Client transactions cannot be initiated with an ACK request.");
            }

            this.agent      = (SipClientAgent)agent;
            this.transport  = transport;
            this.isUdp      = !transport.IsStreaming;
            this.request    = request;
            this.ackRequest = null;
            this.remoteEP   = remoteEP;
        }
Example #24
0
        public void RadiusClient_Interop_AD_IAS()
        {
            if (EnvironmentVars.Get("LT_TESTBIN") == null)
            {
                Assert.Inconclusive("[LT_TESTBIN] environment variable does not exist.");
            }

            if (EnvironmentVars.Get("LT_TEST_AD") == null)
            {
                Assert.Inconclusive("[LT_TEST_AD] environment variable does not exist.");
            }

            var ad = new ADTestSettings();

            if (ad.NasSecret == string.Empty)
            {
                Assert.Inconclusive("AD/IAS Testing is disabled");
                return;
            }

            // Verify that RADIUS client works against AD/IAS.  This requires that
            // the LT_TEST_AD environment variable be set properly as described
            // in the LillTek DevInstall.doc document.  The IAS server must also
            // be manually configured with the NAS shared secret for this client.

            RadiusClient         client         = new RadiusClient();
            NetworkBinding       serverEP       = new NetworkBinding(EnhancedDns.GetHostByName(ad.Servers[0]).AddressList.IPv4Only()[0], NetworkPort.RADIUS);
            RadiusClientSettings clientSettings = new RadiusClientSettings(serverEP, ad.NasSecret);

            clientSettings.RealmFormat = RealmFormat.Email;
            clientSettings.PortCount   = 1;

            try
            {
                client.Open(clientSettings);

                Assert.IsTrue(client.Authenticate(ad.Domain, ad.Account, ad.Password));

                Assert.IsFalse(client.Authenticate(ad.Domain + "x", ad.Account, ad.Password));
                Assert.IsFalse(client.Authenticate(ad.Domain, ad.Account + "x", ad.Password));
                Assert.IsFalse(client.Authenticate(ad.Domain, ad.Account, ad.Password + "x"));
            }
            finally
            {
                client.Close();
            }
        }
Example #25
0
        /// <summary>
        /// Constructs and starts the agent.
        /// </summary>
        /// <param name="smtpServer">The <see cref="NetworkBinding" /> for the relay SMTP server.</param>
        /// <param name="account">The relay server account.</param>
        /// <param name="password">The relay server password.</param>
        /// <param name="queueFolder">Path to the folder where email messages should be queued.</param>
        /// <param name="pollInterval">Interval at which the agent will poll the queue folder for messages waiting to be delivered.</param>
        /// <remarks>
        /// <para>
        /// This method initializes and starts the mail agent, creating the mail queue folder if it doesn't already exist.
        /// </para>
        /// <note>
        /// Pass a network binding with the host or port set to <b>Any</b> to disable email transmission.
        /// </note>
        /// </remarks>
        public MailAgent(NetworkBinding smtpServer, string account, string password, string queueFolder, TimeSpan pollInterval)
        {
            queueFolder = Path.GetFullPath(queueFolder);
            Helper.CreateFolderTree(queueFolder);

            this.smtpServer   = smtpServer;
            this.account      = account;
            this.password     = password;
            this.queueFolder  = queueFolder;
            this.pollInterval = pollInterval;

            smtp                = new SmtpClient(smtpServer.HostOrAddress, smtpServer.Port);
            smtp.Credentials    = new SmtpCredentials(account, password);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

            this.queueTimer = new GatedTimer(new TimerCallback(OnQueueTimer), null, pollInterval);
        }
Example #26
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>
        /// <exception cref="SipTransportException">Thrown if the remote endpoint rejected the message or timed out.</exception>
        public void Send(NetworkBinding remoteEP, SipMessage message)
        {
            if (disabled)
            {
                return;
            }

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

            try
            {
                sock.SendTo(message.ToArray(), remoteEP);
            }
            catch (SocketException e)
            {
                // $todo(jeff.lill):
                //
                // This is just copied from the TCP transport.  It probably
                // doesn't apply here.

                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;
                }
            }
        }
Example #27
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 #28
0
        public void NetworkBinding_Operators()
        {
            IPEndPoint     endPoint;
            NetworkBinding binding;

            endPoint = NetworkBinding.Parse("1.2.3.4:5");
            Assert.AreEqual(IPAddress.Parse("1.2.3.4"), endPoint.Address);
            Assert.AreEqual(5, endPoint.Port);

            endPoint = NetworkBinding.Parse("localhost:4001");
            Assert.AreEqual(IPAddress.Loopback, endPoint.Address);
            Assert.AreEqual(4001, endPoint.Port);

            binding = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 88);
            Assert.AreEqual(IPAddress.Parse("1.2.3.4"), binding.Address);
            Assert.AreEqual(88, binding.Port);
            Assert.IsFalse(binding.IsHost);

            Assert.IsTrue(NetworkBinding.Parse("1.2.3.4:5") == NetworkBinding.Parse("1.2.3.4:5"));
            Assert.IsFalse(NetworkBinding.Parse("1.2.3.4:5") != NetworkBinding.Parse("1.2.3.4:5"));
            Assert.IsTrue(NetworkBinding.Parse("1.2.3.4:5") != NetworkBinding.Parse("1.2.3.4:6"));
            Assert.IsTrue(NetworkBinding.Parse("1.2.3.5:5") != NetworkBinding.Parse("1.2.3.4:5"));
            Assert.IsFalse(NetworkBinding.Parse("1.2.3.4:5") == NetworkBinding.Parse("1.2.3.4:6"));
            Assert.IsFalse(NetworkBinding.Parse("1.2.3.5:5") == NetworkBinding.Parse("1.2.3.4:5"));
            Assert.IsTrue(NetworkBinding.Parse("localhost:55") == NetworkBinding.Parse("localhost:55"));
            Assert.IsFalse(NetworkBinding.Parse("localhost:55") != NetworkBinding.Parse("localhost:55"));
            Assert.IsFalse(NetworkBinding.Parse("localhostx:55") == NetworkBinding.Parse("localhost:55"));
            Assert.IsTrue(NetworkBinding.Parse("localhostx:55") != NetworkBinding.Parse("localhost:55"));
            Assert.IsFalse(NetworkBinding.Parse("localhost:55") == NetworkBinding.Parse("localhost:56"));
            Assert.IsTrue(NetworkBinding.Parse("localhost:55") != NetworkBinding.Parse("localhost:56"));

            Assert.IsTrue((NetworkBinding)null == (NetworkBinding)null);
            Assert.IsFalse((NetworkBinding)null == NetworkBinding.Parse("localhost:55"));
            Assert.IsFalse(NetworkBinding.Parse("localhost:55") == (NetworkBinding)null);

            Assert.IsFalse((NetworkBinding)null != (NetworkBinding)null);
            Assert.IsTrue((NetworkBinding)null != NetworkBinding.Parse("localhost:55"));
            Assert.IsTrue(NetworkBinding.Parse("localhost:55") != (NetworkBinding)null);

            Assert.IsNull((NetworkBinding)((IPEndPoint)null));
            Assert.IsNull((IPEndPoint)((NetworkBinding)null));
        }
Example #29
0
        /// <summary>
        /// Performs a deep copy of the internal properties of the message passed
        /// to this instance.
        /// </summary>
        /// <param name="message">The message to be copied.</param>
        internal void CopyFrom(SipMessage message)
        {
            this.isRequest         = message.isRequest;
            this.sipVersion        = message.sipVersion;
            this.sourceTransaction = null;
            this.sourceTransport   = message.sourceTransport;
            this.remoteEP          = message.remoteEP;

            this.contents = null;
            if (message.contents != null)
            {
                this.contents = new byte[message.contents.Length];
                Array.Copy(message.contents, this.contents, message.contents.Length);
            }

            foreach (SipHeader header in message.headers.Values)
            {
                this.headers.Add(header.Name, header.Clone());
            }
        }
Example #30
0
        /// <summary>
        /// Initiates an asynchronous operation to establish a connection with a remote endpoint.
        /// </summary>
        /// <param name="remoteBinding">Specifies the remote endpoint.</param>
        /// <param name="packet">The packet to be transmitted for UDP sockets, ignored for TCP.</param>
        /// <param name="callback">The delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application specific state.</param>
        /// <returns>
        /// An <see cref="IAsyncResult" /> instance to be used to track the progress of the
        /// operation and to eventually to be passed to the <see cref="EndConnect" /> method.
        /// </returns>
        /// <exception cref="InvalidOperationException">Thrown if the socket is already been connected.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="remoteBinding" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown for UDP sockets when <paramref name="packet" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">Thrown if <paramref name="packet" /> is empty.</exception>
        /// <remarks>
        /// <para>
        /// Due to quirks in how UDP sockets work in Silverlight and Windows Phone, a packet must be
        /// transmitted to remote endpoint as part of establishing a connection.  Use the <paramref name="packet" />
        /// parameter to pass the non-empty array of bytes to be transmitted.  This parameter is ignored
        /// for TCP connections.
        /// </para>
        /// <note>
        /// All successful calls to <see cref="BeginConnect" /> should be eventually matched with a call to <see cref="EndConnect" />.
        /// </note>
        /// </remarks>
        public IAsyncResult BeginConnect(NetworkBinding remoteBinding, byte[] packet, AsyncCallback callback, object state)
        {
            if (remoteBinding == null)
            {
                throw new ArgumentNullException("remoteBinding");
            }

            lock (syncLock)
            {
                this.remoteBinding = remoteBinding;

                if (isTcp)
                {
                    return(sock.BeginConnect(remoteBinding, callback, state));
                }
                else
                {
                    if (isUdpConnected)
                    {
                        throw new InvalidOperationException("Socket is already connected.");
                    }

                    const string packetError = "[LiteSocket] requires a valid [packet] when connecting a UDP socket.";

                    if (packet == null)
                    {
                        throw new ArgumentNullException("packet", packetError);
                    }

                    if (packet.Length == 0)
                    {
                        throw new ArgumentNullException("packet", packetError);
                    }

                    udpConnectPacket = packet;

                    return(Dns.BeginGetHostAddresses(remoteBinding.HostOrAddress, callback, state));
                }
            }
        }