Exemplo n.º 1
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="stack">Owner SIP stack.</param>
        /// <param name="server">Registrar server URI. For example: sip:domain.com.</param>
        /// <param name="aor">Address of record. For example: [email protected].</param>
        /// <param name="contact">Contact URI.</param>
        /// <param name="expires">Gets after how many seconds reigisration expires.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>ua</b>,<b>server</b>,<b>transport</b>,<b>aor</b> or <b>contact</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments contains invalid value.</exception>
        internal SIP_UA_Registration(SIP_Stack stack,SIP_Uri server,string aor,AbsoluteUri contact,int expires)
        {
            if(stack == null){
                throw new ArgumentNullException("stack");
            }
            if(server == null){
                throw new ArgumentNullException("server");
            }
            if(aor == null){
                throw new ArgumentNullException("aor");
            }
            if(aor == string.Empty){
                throw new ArgumentException("Argument 'aor' value must be specified.");
            }
            if(contact == null){
                throw new ArgumentNullException("contact");
            }

            m_pStack          = stack;
            m_pServer         = server;
            m_AOR             = aor;
            m_pContact        = contact;
            m_RefreshInterval = expires;

            m_pContacts = new List<AbsoluteUri>();

            m_pTimer = new TimerEx((m_RefreshInterval - 15) * 1000);
            m_pTimer.AutoReset = false;
            m_pTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_pTimer_Elapsed);
            m_pTimer.Enabled = false;
        }
        public async Task AddLockToRootAndTryRefreshTest()
        {
            var lockResponse = await Client.LockAsync(
                "/",
                WebDavTimeoutHeaderValue.CreateInfiniteWebDavTimeout(),
                WebDavDepthHeaderValue.Infinity,
                new LockInfo()
            {
                LockScope = LockScope.CreateExclusiveLockScope(),
                LockType  = LockType.CreateWriteLockType(),
            })
            ;

            lockResponse.EnsureSuccessStatusCode();
            var prop = await WebDavResponseContentParser.ParsePropResponseContentAsync(lockResponse.Content);

            var lockToken = prop.LockDiscovery.ActiveLock.Single().LockToken;

            Assert.True(AbsoluteUri.TryParse(lockToken.Href, out var lockTokenUri));
            var refreshResponse = await Client.RefreshLockAsync(
                "/",
                WebDavTimeoutHeaderValue.CreateInfiniteWebDavTimeout(),
                new LockToken(lockTokenUri));

            refreshResponse.EnsureSuccessStatusCode();
            var refreshProp = await WebDavResponseContentParser.ParsePropResponseContentAsync(refreshResponse.Content);

            Assert.NotNull(refreshProp.LockDiscovery);
        }
Exemplo n.º 3
0
        public static FileInfo Download(AbsoluteUri location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            FileInfo file = null;

            var request = WebRequest.Create((Uri)location);
            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
#if NET20
                            file = new FileInfo(StringExtensionMethods.FormatWith("{0}.json", AlphaDecimal.Random()));
                            FileInfoExtensionMethods.Create(file, reader.ReadToEnd());
#else
                            file = new FileInfo("{0}.json".FormatWith(AlphaDecimal.Random()));
                            file.Create(reader.ReadToEnd());
#endif
                        }
                    }
                }
            }

            return file;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets a <see cref="LockToken"/> from a <see cref="WebDavResponseMessage"/>.
        /// </summary>
        /// <param name="responseMessage">The <see cref="WebDavResponseMessage"/> whose <see cref="LockToken"/> should be retrieved.</param>
        /// <returns>The <see cref="LockToken"/> of the <see cref="WebDavResponseMessage"/> or null if the WebDavResponseMessage does not contain a lock token.</returns>
        public static async Task <LockToken> GetLockTokenFromWebDavResponseMessage(WebDavResponseMessage responseMessage)
        {
            // Try to get lock token from response header.
            if (responseMessage.Headers.TryGetValues(WebDavRequestHeader.LockToken, out IEnumerable <string> lockTokenHeaderValues))
            {
                // We assume only one Lock-Token header is sent, based on the spec: https://tools.ietf.org/html/rfc4918#section-9.10.1
                var lockTokenHeaderValue = lockTokenHeaderValues.FirstOrDefault();

                // Make sure the lockTokenHeaderValue is valid according to spec (https://tools.ietf.org/html/rfc4918#section-10.5).
                if (lockTokenHeaderValue != null && CodedUrl.TryParse(lockTokenHeaderValue, out var codedUrl))
                {
                    return(new LockToken(codedUrl.AbsoluteUri));
                }
            }

            // If lock token was not submitted by response header, it should be found in the response content.
            try
            {
                var prop = await WebDavResponseContentParser.ParsePropResponseContentAsync(responseMessage.Content);

                var href = prop.LockDiscovery.ActiveLock[0].LockToken.Href;

                if (AbsoluteUri.TryParse(href, out var absoluteUri))
                {
                    return(new LockToken(absoluteUri));
                }
            }
            catch (Exception)
            {
                return(null);
            }

            return(null);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Default incoming call constructor.
        /// </summary>
        /// <param name="ua">Owner UA.</param>
        /// <param name="invite">INVITE server transaction.</param>
        /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception>
        internal SIP_UA_Call(SIP_UA ua,SIP_ServerTransaction invite)
        {
            if(ua == null){
                throw new ArgumentNullException("ua");
            }
            if(invite == null){
                throw new ArgumentNullException("invite");
            }

            m_pUA = ua;
            m_pInitialInviteTransaction = invite;
            m_pLocalUri  = invite.Request.To.Address.Uri;
            m_pRemoteUri = invite.Request.From.Address.Uri;
            m_pInitialInviteTransaction.Canceled += new EventHandler(delegate(object sender,EventArgs e){
                // If transaction canceled, terminate call.
                SetState(SIP_UA_CallState.Terminated);
            });

            // Parse SDP if INVITE contains SDP.
            // RFC 3261 13.2.1. INVITE may be offerless, we must thne send offer and remote party sends sdp in ACK.
            if(invite.Request.ContentType != null && invite.Request.ContentType.ToLower().IndexOf("application/sdp") > -1){
                m_pRemoteSDP = SDP_Message.Parse(Encoding.UTF8.GetString(invite.Request.Data));
            }

            m_pTags = new Dictionary<string,object>();

            m_State = SIP_UA_CallState.WaitingToAccept;
        }
        public void op_Redirect_Uri_whenToRelativePreservingQuery()
        {
            AbsoluteUri expected = "http://www.example.net/destination?name=value";
            var         actual   = Config.ExeSection <RedirectionConfigurationSection>(GetType().Assembly).Redirect(new Uri("http://www.example.net/source?name=value"));

            Assert.Equal(expected, actual);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Default incoming call constructor.
        /// </summary>
        /// <param name="ua">Owner UA.</param>
        /// <param name="invite">INVITE server transaction.</param>
        /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception>
        internal SIP_UA_Call(SIP_UA ua, SIP_ServerTransaction invite)
        {
            if (ua == null)
            {
                throw new ArgumentNullException("ua");
            }
            if (invite == null)
            {
                throw new ArgumentNullException("invite");
            }

            m_pUA = ua;
            m_pInitialInviteTransaction = invite;
            m_pLocalUri  = invite.Request.To.Address.Uri;
            m_pRemoteUri = invite.Request.From.Address.Uri;
            m_pInitialInviteTransaction.Canceled += new EventHandler(delegate(object sender, EventArgs e){
                // If transaction canceled, terminate call.
                SetState(SIP_UA_CallState.Terminated);
            });

            // Parse SDP if INVITE contains SDP.
            // RFC 3261 13.2.1. INVITE may be offerless, we must thne send offer and remote party sends sdp in ACK.
            if (invite.Request.ContentType != null && invite.Request.ContentType.ToLower().IndexOf("application/sdp") > -1)
            {
                m_pRemoteSDP = SDP_Message.Parse(Encoding.UTF8.GetString(invite.Request.Data));
            }

            m_pTags = new Dictionary <string, object>();

            m_State = SIP_UA_CallState.WaitingToAccept;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Default outgoing call constructor.
        /// </summary>
        /// <param name="ua">Owner UA.</param>
        /// <param name="invite">INVITE request.</param>
        /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception>
        internal SIP_UA_Call(SIP_UA ua, SIP_Request invite)
        {
            if (ua == null)
            {
                throw new ArgumentNullException("ua");
            }
            if (invite == null)
            {
                throw new ArgumentNullException("invite");
            }
            if (invite.RequestLine.Method != SIP_Methods.INVITE)
            {
                throw new ArgumentException("Argument 'invite' is not INVITE request.");
            }

            m_pUA        = ua;
            m_pInvite    = invite;
            m_pLocalUri  = invite.From.Address.Uri;
            m_pRemoteUri = invite.To.Address.Uri;

            m_State = SIP_UA_CallState.WaitingForStart;

            m_pEarlyDialogs = new List <SIP_Dialog_Invite>();
            m_pTags         = new Dictionary <string, object>();
        }
Exemplo n.º 9
0
 public XmlNamespace(string prefix,
                     AbsoluteUri uri)
     : this()
 {
     Prefix = prefix;
     Uri    = uri;
 }
Exemplo n.º 10
0
        public string GetRightPart(UriPartial uriPartial)
        {
            string leftPart  = GetLeftPart(uriPartial);
            string rightPart = AbsoluteUri.Substring(leftPart.Length);

            return(rightPart);
        }
Exemplo n.º 11
0
 public override int GetHashCode()
 {
     return(AbsoluteUri?.GetHashCode() ?? 0
            ^ CollectionPropertyName?.GetHashCode() ?? 0
            ^ StartingIndex.GetHashCode()
            ^ Count.GetHashCode());
 }
Exemplo n.º 12
0
 public XmlNamespace(string prefix,
                     AbsoluteUri uri)
     : this()
 {
     Prefix = prefix;
     Uri = uri;
 }
        public void op_Redirect_Uri_whenToHost()
        {
            AbsoluteUri expected = "http://www.example.com/path?name=value";
            var         actual   = Config.ExeSection <RedirectionConfigurationSection>(GetType().Assembly).Redirect(new Uri("http://example.com/path?name=value"));

            Assert.Equal(expected, actual);
        }
Exemplo n.º 14
0
        public static TsvDataSheet Download(AbsoluteUri location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            TsvDataSheet tsv = null;

            var request = WebRequest.Create((Uri)location);

            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
#if NET20
                            var file = new FileInfo(StringExtensionMethods.FormatWith("{0}.tsv", AlphaDecimal.Random()));
                            FileInfoExtensionMethods.Create(file, reader.ReadToEnd());
#else
                            var file = new FileInfo("{0}.tsv".FormatWith(AlphaDecimal.Random()));
                            file.Create(reader.ReadToEnd());
#endif

                            tsv = new TsvDataSheet(file);
                        }
                    }
                }
            }

            return(tsv);
        }
Exemplo n.º 15
0
        public static HtmlDocument Download(AbsoluteUri location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            HtmlDocument html = null;

            var request = WebRequest.Create((Uri)location);
            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
#if NET20
                            var file = new FileInfo(StringExtensionMethods.FormatWith("{0}.html", AlphaDecimal.Random()));
                            FileInfoExtensionMethods.Create(file, reader.ReadToEnd());
#else
                            var file = new FileInfo("{0}.html".FormatWith(AlphaDecimal.Random()));
                            file.Create(reader.ReadToEnd());
#endif

                            html = new HtmlDocument();
                            html.Load(file.FullName);
                        }
                    }
                }
            }

            return html;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Parses SIP_Request from stream.
        /// </summary>
        /// <param name="stream">Stream what contains valid SIP request.</param>
        /// <returns>Returns parsed SIP_Request obeject.</returns>
        /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception>
        /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
        public static SIP_Request Parse(Stream stream)
        {
            /* Syntax:
             *  SIP-Method SIP-URI SIP-Version
             *  SIP-Message
             */

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

            // Parse Response-line
            StreamLineReader r = new StreamLineReader(stream);

            r.Encoding = "utf-8";
            string[] method_uri_version = r.ReadLineString().Split(' ');
            if (method_uri_version.Length != 3)
            {
                throw new Exception("Invalid SIP request data ! Method line doesn't contain: SIP-Method SIP-URI SIP-Version.");
            }
            SIP_Request retVal = new SIP_Request(method_uri_version[0]);

            retVal.RequestLine.Uri     = AbsoluteUri.Parse(method_uri_version[1]);
            retVal.RequestLine.Version = method_uri_version[2];

            // Parse SIP message
            retVal.InternalParse(stream);

            return(retVal);
        }
        public void ctor_AbsoluteUri_AbsoluteUri()
        {
            AbsoluteUri from = "http://example.com/";
            AbsoluteUri to   = "http://example.net/";

            Assert.NotNull(new RedirectionConfigurationElement <AbsoluteUri>(from, to));
        }
        public void op_Redirect_Uri_whenToRelativeDiscardQuery()
        {
            AbsoluteUri expected = "http://www.example.net/that?from=this";
            var         actual   = Config.ExeSection <RedirectionConfigurationSection>(GetType().Assembly).Redirect(new Uri("http://www.example.net/source?this=that"));

            Assert.Equal(expected, actual);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="stack">Owner SIP stack.</param>
        /// <param name="server">Registrar server URI. For example: sip:domain.com.</param>
        /// <param name="aor">Address of record. For example: [email protected].</param>
        /// <param name="contact">Contact URI.</param>
        /// <param name="expires">Gets after how many seconds reigisration expires.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>ua</b>,<b>server</b>,<b>transport</b>,<b>aor</b> or <b>contact</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments contains invalid value.</exception>
        internal SIP_UA_Registration(SIP_Stack stack, SIP_Uri server, string aor, AbsoluteUri contact, int expires)
        {
            if (stack == null)
            {
                throw new ArgumentNullException("stack");
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (aor == null)
            {
                throw new ArgumentNullException("aor");
            }
            if (aor == string.Empty)
            {
                throw new ArgumentException("Argument 'aor' value must be specified.");
            }
            if (contact == null)
            {
                throw new ArgumentNullException("contact");
            }

            m_pStack          = stack;
            m_pServer         = server;
            m_AOR             = aor;
            m_pContact        = contact;
            m_RefreshInterval = expires;

            m_pContacts = new List <AbsoluteUri>();

            m_pTimer = new TimerEx(m_pTimer_Elapsed, (m_RefreshInterval - 15) * 1000, false);
            m_pTimer.Stop();
        }
        /**m* SpringCardApplication/RtdWifiHandoverControl.GetContentEx
         *
         * SYNOPSIS
         *   public RtdHandoverSelector GetContentEx()
         *
         * DESCRIPTION
         *   Constructs a RtdHandoverSelector object, containing  a wifi handover, using the values of the different fields in the form
         *   and returns this object
         *
         **/
        public RtdHandoverSelector GetContentEx()
        {
            byte power_status = 0x01;

            switch (cbPowerState.SelectedIndex)
            {
            case 0:
                power_status = 0x01;
                break;

            case 1:
                power_status = 0x00;
                break;

            case 2:
                power_status = 0x02;
                break;

            case 3:
                power_status = 0x03;
                break;

            default:
                break;
            }


            string wifi_parameters = "";

            switch (cbKeyType.SelectedIndex)
            {
            case 0:
                wifi_parameters = "wifi://" + tbSSID.Text + "/open/";
                break;

            case 1:
                wifi_parameters = "wifi://" + tbSSID.Text + "/wep/" + tbKey.Text;
                break;

            case 2:
                wifi_parameters = "wifi://" + tbSSID.Text + "/wpa/" + tbKey.Text;
                break;

            default:
                break;
            }

            SaveString("Wifi.PowerState", cbPowerState.Text);
            SaveString("Wifi.SSID", tbSSID.Text);
            SaveString("Wifi.KeyType", cbKeyType.Text);
            SaveString("Wifi.Key", tbKey.Text);

            RtdAlternativeCarrier alternative_carrier  = new RtdAlternativeCarrier("0", power_status);
            AbsoluteUri           related_absolute_uri = new AbsoluteUri("0", wifi_parameters);

            RtdHandoverSelector HandoverSelector = new RtdHandoverSelector(alternative_carrier, related_absolute_uri);

            return(HandoverSelector);
        }
Exemplo n.º 21
0
        public void UT_AbsoluteUri_TryParse_FromAbsoluteUrl()
        {
            var url      = "http://127.0.0.1/";
            var isParsed = AbsoluteUri.TryParse(url, out var absoluteUri);

            Assert.IsTrue(isParsed);
            Assert.AreEqual(url, absoluteUri.ToString());
        }
Exemplo n.º 22
0
        IRecord <T> IRepository <T> .Select(AbsoluteUri urn)
        {
            var file = GetFile(urn);

            return(null == file
                       ? null
                       : RecordFile.Load(file).ToRecord <T>());
        }
Exemplo n.º 23
0
        bool IRepository <T> .Match(AbsoluteUri urn,
                                    EntityTag etag)
        {
            var file = GetFile(urn);

            return(null != file &&
                   string.Equals(etag, RecordFile.Load(file).ToRecord <T>().Etag, StringComparison.OrdinalIgnoreCase));
        }
Exemplo n.º 24
0
        AlphaDecimal? IRepository <T> .ToKey(AbsoluteUri urn)
        {
            var file = GetFile(urn);

            return(null == file
                       ? null
                       : RecordFile.Load(file).ToRecord <T>().Key);
        }
        AlphaDecimal? IRepository <T> .ToKey(AbsoluteUri urn)
        {
            var record = ToRecord(Select(urn));

            return(null == record
                       ? null
                       : record.Key);
        }
Exemplo n.º 26
0
        public void UT_AbsoluteUri_TryParse_FromRelativeUrl()
        {
            var url      = "/test";
            var isParsed = AbsoluteUri.TryParse(url, out var absoluteUri);

            Assert.IsFalse(isParsed);
            Assert.IsNull(absoluteUri);
        }
        private XmlNode Select(AbsoluteUri urn)
        {
            if (null == urn)
            {
                throw new ArgumentNullException("urn");
            }

            return(Xml.SelectSingleNode(FormatXPath(urn)));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="displayName">Display name.</param>
        /// <param name="uri">Uri.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception>
        public SIP_t_NameAddress(string displayName,AbsoluteUri uri)
        {
            if(uri == null){
                throw new ArgumentNullException("uri");
            }

            this.DisplayName = displayName;
            this.Uri         = uri;
        }
Exemplo n.º 29
0
        public void UT_AbsoluteUri_ToString_WithDecodedSegment()
        {
            var input    = "opaquelocktoken:dccce564-412e-11e1-b969-00059a3c7a00:%2fFolder Test%2fFile.xml";
            var isParsed = AbsoluteUri.TryParse(input, out AbsoluteUri uri);
            var actual   = uri.ToString();

            Assert.IsTrue(isParsed);
            Assert.AreEqual(input, actual);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="displayName">Display name.</param>
        /// <param name="uri">Uri.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception>
        public SIP_t_NameAddress(string displayName, AbsoluteUri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            DisplayName = displayName;
            Uri         = uri;
        }
Exemplo n.º 31
0
        bool IRepository <T> .Delete(AbsoluteUri urn)
        {
            var file = GetFile(urn);

            if (null == file)
            {
                return(false);
            }

            file.Delete();
            return(true);
        }
Exemplo n.º 32
0
        bool IRepository <T> .ModifiedSince(AbsoluteUri urn,
                                            DateTime value)
        {
            var record = Repository.Select(urn);

            if (null == record)
            {
                return(false);
            }

            return(record.Modified.HasValue && record.Modified.Value > value);
        }
        /// <summary>
        /// Parses "name-addr" or "addr-spec" from specified reader.
        /// </summary>
        /// <param name="reader">Reader from where to parse.</param>
        /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
        /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
        public void Parse(StringReader reader)
        {
            /* RFC 3261.
             *  name-addr =  [ display-name ] LAQUOT addr-spec RAQUOT
             *  addr-spec =  SIP-URI / SIPS-URI / absoluteURI
             */

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

            reader.ReadToFirstChar();

            // LAQUOT addr-spec RAQUOT
            if (reader.StartsWith("<"))
            {
                m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized());
            }
            else
            {
                // Read while we get "<","," or EOF.
                StringBuilder buf = new StringBuilder();
                while (true)
                {
                    buf.Append(reader.ReadToFirstChar());

                    string word = reader.ReadWord();
                    if (string.IsNullOrEmpty(word))
                    {
                        break;
                    }
                    else
                    {
                        buf.Append(word);
                    }
                }

                reader.ReadToFirstChar();

                // name-addr
                if (reader.StartsWith("<"))
                {
                    m_DisplayName = buf.ToString().Trim();
                    m_pUri        = AbsoluteUri.Parse(reader.ReadParenthesized());
                }
                // addr-spec
                else
                {
                    m_pUri = AbsoluteUri.Parse(buf.ToString());
                }
            }
        }
Exemplo n.º 34
0
        public void BeginRegister()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().Name, "不能执行注册操作。");
            }
            if (_regi != null)
            {
                _regi.Dispose();
            }

            string localSn   = _gateway.SipNumber;
            int    localPort = _gateway.Port;

            string remoteSn   = _platform.SipNumber;
            int    remotePort = _platform.Port;
            string remoteIP   = _platform.Ip;


            string user  = _platform.UserName;
            string pwd   = _platform.Password;
            string realm = _platform.Realm;

            SIP_Stack         stack = SipProxyWrapper.Instance.Stack;
            SIP_t_NameAddress from  = new SIP_t_NameAddress($"sip:{localSn}@{_localIp}:{localPort}");
            SIP_t_NameAddress to    = new SIP_t_NameAddress($"sip:{localSn}@{_localIp}:{localPort}");

            SIP_Uri server = new SIP_Uri()
            {
                Host = remoteIP,
                Port = remotePort,
                User = remoteSn
            };
            string              aor     = $"{localSn}@{_localIp}:{localPort}";
            AbsoluteUri         contact = AbsoluteUri.Parse($"sip:{localSn}@" + stack.BindInfo[0].EndPoint.ToString());
            SIP_UA_Registration regi    = stack.CreateRegistration(server, aor, contact, 7200);

            _regi = regi; //记录

            regi.Credential    = new NetworkCredential(user, pwd, realm);
            regi.Registered   += Regi_Registered;
            regi.StateChanged += Regi_StateChanged;

            if (_timerRegi == null)
            {
                _timerRegi = new Timer(timerRegi_Callback, null, 21000, Timeout.Infinite);
            }
            else
            {
                _timerRegi.Change(21000, Timeout.Infinite);
            }
            regi.BeginRegister(true);
        }
Exemplo n.º 35
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (null == reader)
            {
                throw new ArgumentNullException("reader");
            }

            Uri = reader.GetAttribute("uri");
            Credentials = new NetworkCredential(reader.GetAttribute("user"), reader.GetAttribute("password"));
            Passive = XmlConvert.ToBoolean(reader.GetAttribute("passive") ?? "true");
            Secure = XmlConvert.ToBoolean(reader.GetAttribute("secure") ?? "false");
        }
Exemplo n.º 36
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (null == reader)
            {
                throw new ArgumentNullException("reader");
            }

            Uri         = reader.GetAttribute("uri");
            Credentials = new NetworkCredential(reader.GetAttribute("user"), reader.GetAttribute("password"));
            Passive     = XmlConvert.ToBoolean(reader.GetAttribute("passive") ?? "true");
            Secure      = XmlConvert.ToBoolean(reader.GetAttribute("secure") ?? "false");
        }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="owner">Owner registration.</param>
        /// <param name="contactUri">Contact URI what can be used to contact the registration.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> or <b>contactUri</b> is null reference.</exception>
        internal SIP_RegistrationBinding(SIP_Registration owner,AbsoluteUri contactUri)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(contactUri == null){
                throw new ArgumentNullException("contactUri");
            }

            m_pRegistration = owner;
            m_ContactURI    = contactUri;
        }
Exemplo n.º 38
0
        private static FileInfo GetFile(AbsoluteUri urn)
        {
            if (null == urn)
            {
                throw new ArgumentNullException("urn");
            }

            var dir = new DirectoryInfo(urn.ToPath(FileRepositoryConfiguration.Directory()).FullName);

            return(dir.Exists
                       ? dir.GetFiles("*.record", SearchOption.TopDirectoryOnly).FirstOrDefault()
                       : null);
        }
Exemplo n.º 39
0
        public void op_Exists_AbsoluteUri()
        {
            var urn = new AbsoluteUri("urn://example.com/path");

            var mock = new Mock<IRepository<int>>();
            mock
                .Setup(x => x.Exists(urn))
                .Returns(true)
                .Verifiable();

            Assert.True(mock.Object.Exists(urn));

            mock.VerifyAll();
        }
Exemplo n.º 40
0
        public void ctor_SerializationInfo_StreamingContext()
        {
            var expected = new AbsoluteUri("http://example.com");
            AbsoluteUri actual;

            using (Stream stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, new AbsoluteUri("http://example.com"));
                stream.Position = 0;
                actual = (AbsoluteUri)formatter.Deserialize(stream);
            }

            Assert.Equal(expected, actual);
        }
Exemplo n.º 41
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="method">SIP method.</param>
        /// <param name="uri">Request URI.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>method</b> or <b>uri</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        public SIP_RequestLine(string method,AbsoluteUri uri)
        {
            if(method == null){
                throw new ArgumentNullException("method");
            }
            if(!SIP_Utils.IsToken(method)){
                throw new ArgumentException("Argument 'method' value must be token.");
            }
            if(uri == null){
                throw new ArgumentNullException("uri");
            }

            m_Method  = method.ToUpper();
            m_pUri    = uri;
            m_Version = "SIP/2.0";
        }
Exemplo n.º 42
0
        /// <summary>
        /// Gets matching binding. Returns null if no match.
        /// </summary>
        /// <param name="contactUri">URI to match.</param>
        /// <returns>Returns matching binding. Returns null if no match.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>contactUri</b> is null reference.</exception>
        public SIP_RegistrationBinding GetBinding(AbsoluteUri contactUri)
        {
            if(contactUri == null){
                throw new ArgumentNullException("contactUri");
            }

            lock(m_pLock){
                foreach(SIP_RegistrationBinding binding in m_pBindings){
                    if(contactUri.Equals(binding.ContactURI)){
                        return binding;
                    }
                }

                return null;
            }
        }
Exemplo n.º 43
0
        public static string Content(DateTime date,
                                     AbsoluteUri location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            return "<html>" +
                   "<head>" +
                   "<title>The information you requested has been found</title>" +
                   "<meta value=\"" + date.ToXmlString() + "\" />" +
                   "</head>" +
                   "<body>" +
                   "<h1>The information you requested has been found</h1>" +
                   "<p><a id=\"location\" href=\"" + location + "\">" + HttpUtility.HtmlEncode(location) + "</a></p>" +
                   "</body>" +
                   "</html>";
        }
Exemplo n.º 44
0
        /// <summary>
        /// Default incoming call constructor.
        /// </summary>
        /// <param name="ua">Owner UA.</param>
        /// <param name="invite">INVITE server transaction.</param>
        /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception>
        internal SIP_UA_Call(SIP_UA ua,SIP_ServerTransaction invite)
        {
            if(ua == null){
                throw new ArgumentNullException("ua");
            }
            if(invite == null){
                throw new ArgumentNullException("invite");
            }

            m_pUA = ua;
            m_pInitialInviteTransaction = invite;
            m_pLocalUri  = invite.Request.To.Address.Uri;
            m_pRemoteUri = invite.Request.From.Address.Uri;
            m_pInitialInviteTransaction.Canceled += new EventHandler(delegate(object sender,EventArgs e){
                // If transaction canceled, terminate call.
                SetState(SIP_UA_CallState.Terminated);
            });

            m_State = SIP_UA_CallState.WaitingToAccept;
        }
Exemplo n.º 45
0
        /// <summary>
        /// Default outgoing call constructor.
        /// </summary>
        /// <param name="ua">Owner UA.</param>
        /// <param name="invite">INVITE request.</param>
        /// <exception cref="ArgumentNullException">Is riased when <b>ua</b> or <b>invite</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception>
        internal SIP_UA_Call(SIP_UA ua,SIP_Request invite)
        {
            if(ua == null){
                throw new ArgumentNullException("ua");
            }
            if(invite == null){
                throw new ArgumentNullException("invite");
            }
            if(invite.RequestLine.Method != SIP_Methods.INVITE){
                throw new ArgumentException("Argument 'invite' is not INVITE request.");
            }

            m_pUA        = ua;
            m_pInvite    = invite;
            m_pLocalUri  = invite.From.Address.Uri;
            m_pRemoteUri = invite.To.Address.Uri;

            m_State = SIP_UA_CallState.WaitingForStart;

            m_pEarlyDialogs = new List<SIP_Dialog>();
        }
Exemplo n.º 46
0
        /// <summary>
        /// Converts URI to Request-URI by removing all not allowed Request-URI parameters from URI.
        /// </summary>
        /// <param name="uri">URI value.</param>
        /// <returns>Returns valid Request-URI value.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception>
        public static AbsoluteUri UriToRequestUri(AbsoluteUri uri)
        {   
            if(uri == null){
                throw new ArgumentNullException("uri");
            }

            if(uri is SIP_Uri){
                // RFC 3261 19.1.2.(Table)
                // We need to strip off "method-param" and "header" URI parameters".
                // Currently we do it for sip or sips uri, do we need todo it for others too ?

                SIP_Uri sUri = (SIP_Uri)uri;
                sUri.Parameters.Remove("method");
                sUri.Header = null;

                return sUri;
            }
            else{
                return uri;
            }      
        }
Exemplo n.º 47
0
        public HttpRequestLine(Token method,
                               AbsoluteUri requestUri,
                               HttpVersion version)
            : this()
        {
            if (null == method)
            {
                throw new ArgumentNullException("method");
            }

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

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

            Method = method;
            RequestUri = requestUri;
            Version = version;
        }
Exemplo n.º 48
0
        public void opEquality_AbsoluteUri_AbsoluteUri()
        {
            var obj = new AbsoluteUri("http://example.com/");
            var comparand = new AbsoluteUri("http://example.com/");

            Assert.True(obj == comparand);
        }
Exemplo n.º 49
0
        public void opEquality_AbsoluteUri_AbsoluteUriDiffers()
        {
            var obj = new AbsoluteUri("http://example.com/");
            var comparand = new AbsoluteUri("http://example.net/");

            Assert.False(obj == comparand);
        }
Exemplo n.º 50
0
        /// <summary>
        /// Initializes dialog.
        /// </summary>
        /// <param name="stack">Owner stack.</param>
        /// <param name="transaction">Owner transaction.</param>
        /// <param name="response">SIP response what caused dialog creation.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>transaction</b> or <b>response</b>.</exception>
        internal protected virtual void Init(SIP_Stack stack,SIP_Transaction transaction,SIP_Response response)
        {
            if(stack == null){
                throw new ArgumentNullException("stack");
            }
            if(transaction == null){
                throw new ArgumentNullException("transaction");
            }
            if(response == null){
                throw new ArgumentNullException("response");
            }

            m_pStack = stack;
                        
            #region UAS

            /* RFC 3261 12.1.1.
                The UAS then constructs the state of the dialog.  This state MUST be
                maintained for the duration of the dialog.

                If the request arrived over TLS, and the Request-URI contained a SIPS
                URI, the "secure" flag is set to TRUE.

                The route set MUST be set to the list of URIs in the Record-Route
                header field from the request, taken in order and preserving all URI
                parameters.  If no Record-Route header field is present in the
                request, the route set MUST be set to the empty set.  This route set,
                even if empty, overrides any pre-existing route set for future
                requests in this dialog.  The remote target MUST be set to the URI
                from the Contact header field of the request.

                The remote sequence number MUST be set to the value of the sequence
                number in the CSeq header field of the request.  The local sequence
                number MUST be empty.  The call identifier component of the dialog ID
                MUST be set to the value of the Call-ID in the request.  The local
                tag component of the dialog ID MUST be set to the tag in the To field
                in the response to the request (which always includes a tag), and the
                remote tag component of the dialog ID MUST be set to the tag from the
                From field in the request.  A UAS MUST be prepared to receive a
                request without a tag in the From field, in which case the tag is
                considered to have a value of null.

                    This is to maintain backwards compatibility with RFC 2543, which
                    did not mandate From tags.

                The remote URI MUST be set to the URI in the From field, and the
                local URI MUST be set to the URI in the To field.
            */

            if(transaction is SIP_ServerTransaction){
                m_IsSecure = ((SIP_Uri)transaction.Request.RequestLine.Uri).IsSecure;
                m_pRouteSet = (SIP_t_AddressParam[])Net_Utils.ReverseArray(transaction.Request.RecordRoute.GetAllValues());
                m_pRemoteTarget = (SIP_Uri)transaction.Request.Contact.GetTopMostValue().Address.Uri;
                m_RemoteSeqNo = transaction.Request.CSeq.SequenceNumber;
                m_LocalSeqNo = 0;
                m_CallID = transaction.Request.CallID;
                m_LocalTag = response.To.Tag;
                m_RemoteTag = transaction.Request.From.Tag;
                m_pRemoteUri = transaction.Request.From.Address.Uri;
                m_pLocalUri = transaction.Request.To.Address.Uri;
                m_pLocalContact = (SIP_Uri)response.Contact.GetTopMostValue().Address.Uri;

                List<string> allow = new List<string>();
                foreach(SIP_t_Method m in response.Allow.GetAllValues()){
                    allow.Add(m.Method);
                }
                m_pRemoteAllow = allow.ToArray();

                List<string> supported = new List<string>();
                foreach(SIP_t_OptionTag s in response.Supported.GetAllValues()){
                    supported.Add(s.OptionTag);
                }
                m_pRemoteSupported = supported.ToArray();
            }

            #endregion

            #region UAC

            /* RFC 3261 12.1.2.
                When a UAC receives a response that establishes a dialog, it
                constructs the state of the dialog.  This state MUST be maintained
                for the duration of the dialog.

                If the request was sent over TLS, and the Request-URI contained a
                SIPS URI, the "secure" flag is set to TRUE.

                The route set MUST be set to the list of URIs in the Record-Route
                header field from the response, taken in reverse order and preserving
                all URI parameters.  If no Record-Route header field is present in
                the response, the route set MUST be set to the empty set.  This route
                set, even if empty, overrides any pre-existing route set for future
                requests in this dialog.  The remote target MUST be set to the URI
                from the Contact header field of the response.

                The local sequence number MUST be set to the value of the sequence
                number in the CSeq header field of the request.  The remote sequence
                number MUST be empty (it is established when the remote UA sends a
                request within the dialog).  The call identifier component of the
                dialog ID MUST be set to the value of the Call-ID in the request.
                The local tag component of the dialog ID MUST be set to the tag in
                the From field in the request, and the remote tag component of the
                dialog ID MUST be set to the tag in the To field of the response.  A
                UAC MUST be prepared to receive a response without a tag in the To
                field, in which case the tag is considered to have a value of null.

                    This is to maintain backwards compatibility with RFC 2543, which
                    did not mandate To tags.

                The remote URI MUST be set to the URI in the To field, and the local
                URI MUST be set to the URI in the From field.
            */

            else{
                // TODO: Validate request or client transaction must do it ?

                m_IsSecure  = ((SIP_Uri)transaction.Request.RequestLine.Uri).IsSecure;
                m_pRouteSet = (SIP_t_AddressParam[])Net_Utils.ReverseArray(response.RecordRoute.GetAllValues());
                m_pRemoteTarget = (SIP_Uri)response.Contact.GetTopMostValue().Address.Uri;                
                m_LocalSeqNo = transaction.Request.CSeq.SequenceNumber;
                m_RemoteSeqNo = 0;
                m_CallID = transaction.Request.CallID;
                m_LocalTag = transaction.Request.From.Tag;
                m_RemoteTag = response.To.Tag;
                m_pRemoteUri = transaction.Request.To.Address.Uri;
                m_pLocalUri = transaction.Request.From.Address.Uri;
                m_pLocalContact = (SIP_Uri)transaction.Request.Contact.GetTopMostValue().Address.Uri;
                
                List<string> allow = new List<string>();
                foreach(SIP_t_Method m in response.Allow.GetAllValues()){
                    allow.Add(m.Method);
                }
                m_pRemoteAllow = allow.ToArray();

                List<string> supported = new List<string>();
                foreach(SIP_t_OptionTag s in response.Supported.GetAllValues()){
                    supported.Add(s.OptionTag);
                }
                m_pRemoteSupported = supported.ToArray();
            }

            #endregion            

            m_pFlow = transaction.Flow;
            AddTransaction(transaction);
        }
Exemplo n.º 51
0
        public void op_ToString()
        {
            const string expected = "http://example.com/";
            var actual = new AbsoluteUri(expected).ToString();

            Assert.Equal(expected, actual);
        }
Exemplo n.º 52
0
        public void op_GetHashCode()
        {
            var obj = new AbsoluteUri("http://example.com/");

            var expected = obj.ToString().GetHashCode();
            var actual = obj.GetHashCode();

            Assert.Equal(expected, actual);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public virtual void Dispose()
        {
            lock(m_pLock){
                if(this.State == SIP_DialogState.Disposed){
                    return;
                }

                SetState(SIP_DialogState.Disposed,true);
   
                this.RequestReceived = null;
                m_pStack             = null;
                m_CallID             = null;
                m_LocalTag           = null;
                m_RemoteTag          = null;
                m_pLocalUri          = null;
                m_pRemoteUri         = null;
                m_pLocalContact      = null;
                m_pRemoteTarget      = null;
                m_pRouteSet          = null;
                m_pFlow              = null;           
            }
        }
Exemplo n.º 54
0
        public void op_Equals_objectDiffer()
        {
            var obj = new AbsoluteUri("http://example.com/");
            var comparand = new AbsoluteUri("http://example.net/");

            Assert.False(obj.Equals(comparand as object));
        }
Exemplo n.º 55
0
        public void op_Equals_objectSame()
        {
            var obj = new AbsoluteUri("http://example.com/");

            Assert.True(obj.Equals(obj as object));
        }
Exemplo n.º 56
0
        public void op_Equals_AbsoluteUriUnequal()
        {
            var obj = new AbsoluteUri("http://example.com/");
            var comparand = new AbsoluteUri("http://example.net/");

            Assert.False(obj.Equals(comparand));
        }
Exemplo n.º 57
0
        public void op_Equals_AbsoluteUriSame()
        {
            var obj = new AbsoluteUri("http://example.com/");
            var comparand = obj;

            Assert.True(obj.Equals(comparand));
        }
Exemplo n.º 58
0
        /// <summary>
        /// Creates new registration.
        /// </summary>
        /// <param name="server">Registrar server URI. For example: sip:domain.com.</param>
        /// <param name="aor">Registration address of record. For example: [email protected].</param>
        /// <param name="contact">Contact URI.</param>
        /// <param name="expires">Gets after how many seconds reigisration expires.</param>
        /// <returns>Returns created registration.</returns>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception>
        /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>aor</b> or <b>contact</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        public SIP_UA_Registration CreateRegistration(SIP_Uri server,
                                                      string aor,
                                                      AbsoluteUri contact,
                                                      int expires)
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (aor == null)
            {
                throw new ArgumentNullException("aor");
            }
            if (aor == string.Empty)
            {
                throw new ArgumentException("Argument 'aor' value must be specified.");
            }
            if (contact == null)
            {
                throw new ArgumentNullException("contact");
            }

            lock (m_pRegistrations)
            {
                SIP_UA_Registration registration = new SIP_UA_Registration(this, server, aor, contact, expires);
                registration.Disposed += delegate
                                             {
                                                 if (!m_IsDisposed)
                                                 {
                                                     m_pRegistrations.Remove(registration);
                                                 }
                                             };
                m_pRegistrations.Add(registration);

                return registration;
            }
        }
Exemplo n.º 59
0
        /// <summary>
        /// Parses "name-addr" or "addr-spec" from specified reader.
        /// </summary>
        /// <param name="reader">Reader from where to parse.</param>
        /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
        /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
        public void Parse(StringReader reader)
        {
            /* RFC 3261.
                name-addr =  [ display-name ] LAQUOT addr-spec RAQUOT
                addr-spec =  SIP-URI / SIPS-URI / absoluteURI
            */

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

            reader.ReadToFirstChar();

            // LAQUOT addr-spec RAQUOT
            if (reader.StartsWith("<"))
            {
                m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized());
            }
            else
            {
                string word = reader.ReadWord();
                if (word == null)
                {
                    throw new SIP_ParseException("Invalid 'name-addr' or 'addr-spec' value !");
                }

                reader.ReadToFirstChar();

                // name-addr
                if (reader.StartsWith("<"))
                {
                    m_DisplayName = word;
                    m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized());
                }
                    // addr-spec
                else
                {
                    m_pUri = AbsoluteUri.Parse(word);
                }
            }
        }
Exemplo n.º 60
0
 public HttpRequestLine(Token method,
                        AbsoluteUri requestUri)
     : this(method, requestUri, HttpVersion.Latest)
 {
 }