예제 #1
0
        private void timerAlive_Callback(object state)
        {
            //资源已释放,停止心跳。
            if (_disposed || !_registered)
            {
                return;
            }
            if (_aliveCount >= 3)
            {
                //重新注册。
                _registered = false;
                _alive      = false;
                _timerAlive.Change(Timeout.Infinite, Timeout.Infinite); //关闭心跳定时器。
                SipProxyWrapper.Instance.RTPManager.RemoveTargets(Platform.Ip);
                closeSender();
                BeginRegister();
                return;
            }

            try
            {
                Gateway   gw    = _gateway;
                Platform  pf    = _platform;
                SIP_Stack stack = SipProxyWrapper.Instance.Stack;

                KeepAlive ka = new KeepAlive()
                {
                    DeviceID = gw.SipNumber
                };
                string body = SerializeHelper.Instance.Serialize(ka);

                SIP_t_NameAddress from = new SIP_t_NameAddress($"sip:{gw.SipNumber}@{_localIp}:{gw.Port}");
                SIP_t_NameAddress to   = new SIP_t_NameAddress($"sip:{pf.SipNumber}@{pf.Ip}:{pf.Port}");

                SIP_Request message = stack.CreateRequest(SIP_Methods.MESSAGE, to, from);
                message.ContentType = "Application/MANSCDP+xml";
                message.Data        = MyEncoder.Encoder.GetBytes(body);

                closeSender();
                _sender = stack.CreateRequestSender(message);
                _sender.ResponseReceived += Send_ResponseReceived;
                _sender.Start();
            }
            catch (Exception e)
            {
                Common.Log.Logger.Default.Error($"心跳指令发送失败,平台:{Platform.Name}:{Platform.SipNumber}", e);
            }
            _aliveCount++;
        }
예제 #2
0
        /// <summary>
        /// Gets specified realm SIP proxy credentials. Returns null if none exists for specified realm.
        /// </summary>
        /// <param name="request">SIP reques.</param>
        /// <param name="realm">Realm(domain).</param>
        /// <returns>Returns specified realm credentials or null if none.</returns>
        public static SIP_t_Credentials GetCredentials(SIP_Request request, string realm)
        {
            foreach (SIP_SingleValueHF <SIP_t_Credentials> authorization in request.ProxyAuthorization.HeaderFields)
            {
                if (authorization.ValueX.Method.ToLower() == "digest")
                {
                    Auth_HttpDigest authDigest = new Auth_HttpDigest(authorization.ValueX.AuthData, request.RequestLine.Method);
                    if (authDigest.Realm.ToLower() == realm.ToLower())
                    {
                        return(authorization.ValueX);
                    }
                }
            }

            return(null);
        }
예제 #3
0
파일: SIPDump.cs 프로젝트: skrusty/SIPDump
 public static SIP_Message ParseSIPMessage(byte[] data)
 {
     try
     {
         return(SIP_Request.Parse(data));
     }
     catch
     {
         try
         {
             return(SIP_Response.Parse(data));
         }
         catch
         {
             return(null);
         }
     }
 }
예제 #4
0
        /// <summary>
        /// Creates call to <b>invite</b> specified recipient.
        /// </summary>
        /// <param name="invite">INVITE request.</param>
        /// <returns>Returns created call.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>invite</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception>
        public SIP_UA_Call CreateCall(SIP_Request invite)
        {
            if (invite == null)
            {
                throw new ArgumentNullException("invite");
            }
            if (invite.RequestLine.Method != SIP_Methods.INVITE)
            {
                throw new ArgumentException("Argument 'invite' is not INVITE request.");
            }

            lock (m_pLock){
                SIP_UA_Call call = new SIP_UA_Call(this, invite);
                call.StateChanged += new EventHandler(Call_StateChanged);
                m_pCalls.Add(call);

                return(call);
            }
        }
예제 #5
0
        public void ResponseToPlatform(Platform plat)
        {
            Gateway   gw      = InfoService.Instance.CurrentGateway;
            string    localIp = IPAddressHelper.GetLocalIp();
            SIP_Stack stack   = SipProxyWrapper.Instance.Stack;

            DeviceCatalogResp resp = createCatalogResp(gw, plat);
            string            body = SerializeHelper.Instance.Serialize(resp);

            SIP_t_NameAddress from = new SIP_t_NameAddress($"sip:{gw.SipNumber}@{localIp}:{gw.Port}");
            SIP_t_NameAddress to   = new SIP_t_NameAddress($"sip:{plat.SipNumber}@{plat.Ip}:{plat.Port}");

            SIP_Request message = stack.CreateRequest(SIP_Methods.MESSAGE, to, from);

            message.ContentType = "Application/MANSCDP+xml";
            message.Data        = MyEncoder.Encoder.GetBytes(body);
            SIP_RequestSender send = stack.CreateRequestSender(message);

            send.Start();
        }
예제 #6
0
        public void NotifyToPlatform(string platId)
        {
            Gateway   gw      = InfoService.Instance.CurrentGateway;
            Platform  pf      = InfoService.Instance.GetPlatform(platId);
            string    localIp = IPAddressHelper.GetLocalIp();
            SIP_Stack stack   = SipProxyWrapper.Instance.Stack;

            DeviceCatalogNotify dcd = createCatalog(gw, pf);
            string body             = SerializeHelper.Instance.Serialize(dcd);

            SIP_t_NameAddress from = new SIP_t_NameAddress($"sip:{gw.SipNumber}@{localIp}:{gw.Port}");
            SIP_t_NameAddress to   = new SIP_t_NameAddress($"sip:{pf.SipNumber}@{pf.Ip}:{pf.Port}");

            SIP_Request message = stack.CreateRequest(SIP_Methods.NOTIFY, to, from);

            message.ContentType = "Application/MANSCDP+xml";
            message.Data        = MyEncoder.Encoder.GetBytes(body);
            SIP_RequestSender send = stack.CreateRequestSender(message);

            send.Start();
        }
예제 #7
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="proxy">Owner SIP proxy server.</param>
        /// <param name="request">The request what is represented by this context.</param>
        /// <param name="flow">Data flow what received request.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>proxy</b>, <b>request</b> or <b>flow</b> is null reference.</exception>
        internal SIP_RequestContext(SIP_Proxy proxy, SIP_Request request, SIP_Flow flow)
        {
            if (proxy == null)
            {
                throw new ArgumentNullException("proxy");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (flow == null)
            {
                throw new ArgumentNullException("flow");
            }

            m_pProxy   = proxy;
            m_pRequest = request;
            m_pFlow    = flow;

            m_pTargets = new List <SIP_ProxyTarget>();
        }
예제 #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>();
        }
예제 #9
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>();
        }
예제 #10
0
        /// <summary>
        /// Creates call to <b>invite</b> specified recipient.
        /// </summary>
        /// <param name="invite">INVITE request.</param>
        /// <returns>Returns created call.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>invite</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception>
        public SIP_UA_Call CreateCall(SIP_Request invite)
        {
            if (invite == null)
            {
                throw new ArgumentNullException("invite");
            }
            if (invite.RequestLine.Method != SIP_Methods.INVITE)
            {
                throw new ArgumentException("Argument 'invite' is not INVITE request.");
            }

            lock (m_pLock)
            {
                SIP_UA_Call call = new SIP_UA_Call(this, invite);
                call.StateChanged += Call_StateChanged;
                m_pCalls.Add(call);

                return call;
            }
        }
예제 #11
0
        /// <summary>
        /// This method is called when new request is received.
        /// </summary>
        /// <param name="e">Request event arguments.</param>
        private void OnRequestReceived(SIP_RequestReceivedEventArgs e)
        {
            /* RFC 3261 16.12. ????????? Forward does all thse steps.
             *  1. The proxy will inspect the Request-URI.  If it indicates a
             *     resource owned by this proxy, the proxy will replace it with
             *     the results of running a location service.  Otherwise, the
             *     proxy will not change the Request-URI.
             *
             *  2. The proxy will inspect the URI in the topmost Route header
             *     field value.  If it indicates this proxy, the proxy removes it
             *     from the Route header field (this route node has been reached).
             *
             *  3. The proxy will forward the request to the resource indicated
             *     by the URI in the topmost Route header field value or in the
             *     Request-URI if no Route header field is present.  The proxy
             *     determines the address, port and transport to use when
             *     forwarding the request by applying the procedures in [4] to that URI.
             */

            SIP_Request request = e.Request;

            try
            {
                #region Registrar

                // Registrar
                if ((m_ProxyMode & SIP_ProxyMode.Registrar) != 0 &&
                    request.RequestLine.Method == SIP_Methods.REGISTER)
                {
                    m_pRegistrar.Register(e);
                }

                #endregion

                #region Presence

                /*
                 * // Presence
                 * else if((m_ProxyMode & SIP_ProxyMode.Presence) != 0 && (request.Method == "SUBSCRIBE" || request.Method == "NOTIFY")){
                 *
                 * }
                 */
                #endregion

                #region Statefull

                // Statefull
                else if ((m_ProxyMode & SIP_ProxyMode.Statefull) != 0)
                {
                    // Statefull proxy is transaction statefull proxy only,
                    // what don't create dialogs and keep dialog state.

                    /* RFC 3261 16.10.
                     *  StateFull proxy:
                     *          If a matching response context is found, the element MUST
                     *          immediately return a 200 (OK) response to the CANCEL request.
                     *
                     *          If a response context is not found, the element does not have any
                     *          knowledge of the request to apply the CANCEL to.  It MUST statelessly
                     *          forward the CANCEL request (it may have statelessly forwarded the
                     *          associated request previously).
                     */
                    if (e.Request.RequestLine.Method == SIP_Methods.CANCEL)
                    {
                        // Don't do server transaction before we get CANCEL matching transaction.
                        SIP_ServerTransaction trToCancel =
                            m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request);
                        if (trToCancel != null)
                        {
                            trToCancel.Cancel();
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(
                                                                 SIP_ResponseCodes.x200_Ok, request));
                        }
                        else
                        {
                            ForwardRequest(false, e);
                        }
                    }
                    // ACK never creates transaction, it's always passed directly to transport layer.
                    else if (e.Request.RequestLine.Method == SIP_Methods.ACK)
                    {
                        ForwardRequest(false, e);
                    }
                    else
                    {
                        ForwardRequest(true, e);
                    }
                }

                #endregion

                #region B2BUA

                // B2BUA
                else if ((m_ProxyMode & SIP_ProxyMode.B2BUA) != 0)
                {
                    m_pB2BUA.OnRequestReceived(e);
                }

                #endregion

                #region Stateless

                // Stateless
                else if ((m_ProxyMode & SIP_ProxyMode.Stateless) != 0)
                {
                    // Stateless proxy don't do transaction, just forwards all.
                    ForwardRequest(false, e);
                }

                #endregion

                #region Proxy won't accept command

                else
                {
                    e.ServerTransaction.SendResponse(
                        m_pStack.CreateResponse(SIP_ResponseCodes.x501_Not_Implemented, request));
                }

                #endregion
            }
            catch (Exception x)
            {
                try
                {
                    m_pStack.TransportLayer.SendResponse(
                        m_pStack.CreateResponse(
                            SIP_ResponseCodes.x500_Server_Internal_Error + ": " + x.Message, e.Request));
                }
                catch
                {
                    // Skip transport layer exception if send fails.
                }

                // Don't raise OnError for transport errors.
                if (!(x is SIP_TransportException))
                {
                    m_pStack.OnError(x);
                }
            }
        }
예제 #12
0
            /// <summary>
            /// Sends specified request to the specified data flow.
            /// </summary>
            /// <param name="flow">SIP data flow.</param>
            /// <param name="request">SIP request to send.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception>
            private void SendToFlow(SIP_Flow flow, SIP_Request request)
            {
                if (flow == null)
                {
                    throw new ArgumentNullException("flow");
                }
                if (request == null)
                {
                    throw new ArgumentNullException("request");
                }

                /* NAT traversal.
                    When we do record routing, store request sender flow info and request target flow info.
                    Now the tricky part, how proxy later which flow is target (because both sides can send requests).
                      Sender-flow will store from-tag to flow and target-flow will store flowID only (Because we don't know to-tag).
                      Later if request to-tag matches(incoming request), use that flow, otherwise(outgoing request) other flow.
                 
                    flowInfo: sender-flow "/" target-flow
                              sender-flow = from-tag ":" flowID
                              target-flow = flowID                        
                */
                if (m_AddRecordRoute && request.From.Tag != null)
                {
                    string flowInfo = request.From.Tag + ":" + m_pOwner.ServerTransaction.Flow.ID + "/" +
                                      flow.ID;
                    ((SIP_Uri) request.RecordRoute.GetTopMostValue().Address.Uri).Parameters.Add("flowInfo",
                                                                                                 flowInfo);
                }

                /* RFC 3261 16.6 Request Forwarding.
                        Common Steps 1 - 7 are done in target Init().
                                                  
                        8.  Add a Via header field value
                        9.  Add a Content-Length header field if necessary
                        10. Forward the new request
                        11. Set timer C
                */

                #region 8.  Add a Via header field value

                // Skip, Client transaction will add it.

                #endregion

                #region 9.  Add a Content-Length header field if necessary

                // Skip, our SIP_Message class is smart and do it when ever it's needed.

                #endregion

                #region 10. Forward the new request

                m_pTransaction = m_pOwner.Proxy.Stack.TransactionLayer.CreateClientTransaction(flow,
                                                                                               request,
                                                                                               true);
                m_pTransaction.ResponseReceived += ClientTransaction_ResponseReceived;
                m_pTransaction.TimedOut += ClientTransaction_TimedOut;
                m_pTransaction.TransportError += ClientTransaction_TransportError;
                m_pTransaction.Disposed += m_pTransaction_Disposed;

                // Start transaction processing.
                m_pTransaction.Start();

                #endregion

                #region 11. Set timer C

                /* 11. Set timer C
                    In order to handle the case where an INVITE request never
                    generates a final response, the TU uses a timer which is called
                    timer C.  Timer C MUST be set for each client transaction when
                    an INVITE request is proxied.  The timer MUST be larger than 3
                    minutes.  Section 16.7 bullet 2 discusses how this timer is
                    updated with provisional responses, and Section 16.8 discusses
                    processing when it fires.
                */
                if (request.RequestLine.Method == SIP_Methods.INVITE)
                {
                    m_pTimerC = new TimerEx();
                    m_pTimerC.AutoReset = false;
                    m_pTimerC.Interval = 3*60*1000;
                    m_pTimerC.Elapsed += m_pTimerC_Elapsed;
                }

                #endregion
            }
예제 #13
0
        /// <summary>
        /// Forwards specified request to target recipient.
        /// </summary>
        /// <param name="statefull">Specifies if request is sent statefully or statelessly.</param>
        /// <param name="e">Request event arguments.</param>
        /// <param name="addRecordRoute">If true Record-Route header field is added.</param>
        internal void ForwardRequest(bool statefull, SIP_RequestReceivedEventArgs e, bool addRecordRoute)
        {
            SIP_RequestContext requestContext = new SIP_RequestContext(this, e.Request, e.Flow);

            SIP_Request request = e.Request;
            SIP_Uri     route   = null;

            /* RFC 3261 16.
             *  1. Validate the request (Section 16.3)
             *      1. Reasonable Syntax
             *      2. URI scheme (NOTE: We do it later)
             *      3. Max-Forwards
             *      4. (Optional) Loop Detection
             *      5. Proxy-Require
             *      6. Proxy-Authorization
             *  2. Preprocess routing information (Section 16.4)
             *  3. Determine target(s) for the request (Section 16.5)
             *  x. Custom handling (non-RFC)
             *      1. Process custom request handlers.
             *      2. URI scheme
             *  4. Forward the request (Section 16.6)
             */

            #region 1. Validate the request (Section 16.3)

            // 1.1 Reasonable Syntax.
            //      SIP_Message parsing have done it.

            // 1.2 URI scheme check.
            //      We do it later.

            // 1.3 Max-Forwards.
            if (request.MaxForwards <= 0)
            {
                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x483_Too_Many_Hops, request));
                return;
            }

            // 1.4 (Optional) Loop Detection.
            //      Skip.

            // 1.5 Proxy-Require.
            //      TODO:

            // 1.6 Proxy-Authorization.

            /*  If an element requires credentials before forwarding a request,
             *  the request MUST be inspected as described in Section 22.3.  That
             *  section also defines what the element must do if the inspection
             *  fails.
             */

            // We need to auth all foreign calls.
            if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) || !this.OnIsLocalUri(((SIP_Uri)request.RequestLine.Uri).Host))
            {
                // If To: field is registrar AOR and request-URI is local registration contact, skip authentication.
                bool skipAuth = false;
                if (request.To.Address.IsSipOrSipsUri)
                {
                    SIP_Registration registration = m_pRegistrar.GetRegistration(((SIP_Uri)request.To.Address.Uri).Address);
                    if (registration != null)
                    {
                        if (registration.GetBinding(request.RequestLine.Uri) != null)
                        {
                            skipAuth = true;
                        }
                    }
                }

                if (!skipAuth)
                {
                    string userName = null;

                    // We need to pass-through ACK.
                    if (request.RequestLine.Method == SIP_Methods.ACK)
                    {
                    }
                    else if (!AuthenticateRequest(e, out userName))
                    {
                        return;
                    }

                    requestContext.SetUser(userName);
                }
            }

            #endregion

            #region 2. Preprocess routing information (Section 16.4).

            /*
             *  The proxy MUST inspect the Request-URI of the request.  If the
             *  Request-URI of the request contains a value this proxy previously
             *  placed into a Record-Route header field (see Section 16.6 item 4),
             *  the proxy MUST replace the Request-URI in the request with the last
             *  value from the Route header field, and remove that value from the
             *  Route header field.  The proxy MUST then proceed as if it received
             *  this modified request.
             *
             *      This will only happen when the element sending the request to the
             *      proxy (which may have been an endpoint) is a strict router.  This
             *      rewrite on receive is necessary to enable backwards compatibility
             *      with those elements.  It also allows elements following this
             *      specification to preserve the Request-URI through strict-routing
             *      proxies (see Section 12.2.1.1).
             *
             *      This requirement does not obligate a proxy to keep state in order
             *      to detect URIs it previously placed in Record-Route header fields.
             *      Instead, a proxy need only place enough information in those URIs
             *      to recognize them as values it provided when they later appear.
             *
             *  If the Request-URI contains a maddr parameter, the proxy MUST check
             *  to see if its value is in the set of addresses or domains the proxy
             *  is configured to be responsible for.  If the Request-URI has a maddr
             *  parameter with a value the proxy is responsible for, and the request
             *  was received using the port and transport indicated (explicitly or by
             *  default) in the Request-URI, the proxy MUST strip the maddr and any
             *  non-default port or transport parameter and continue processing as if
             *  those values had not been present in the request.
             *
             *      A request may arrive with a maddr matching the proxy, but on a
             *      port or transport different from that indicated in the URI.  Such
             *      a request needs to be forwarded to the proxy using the indicated
             *      port and transport.
             *
             *  If the first value in the Route header field indicates this proxy,
             *  the proxy MUST remove that value from the request.
             */

            // Strict route - handle it.
            if ((request.RequestLine.Uri is SIP_Uri) && IsRecordRoute(((SIP_Uri)request.RequestLine.Uri)) && request.Route.GetAllValues().Length > 0)
            {
                request.RequestLine.Uri = request.Route.GetAllValues()[request.Route.GetAllValues().Length - 1].Address.Uri;
                SIP_t_AddressParam[] routes = request.Route.GetAllValues();
                route = (SIP_Uri)routes[routes.Length - 1].Address.Uri;
                request.Route.RemoveLastValue();
            }

            // Check if Route header field indicates this proxy.
            if (request.Route.GetAllValues().Length > 0)
            {
                route = (SIP_Uri)request.Route.GetTopMostValue().Address.Uri;

                // We consider loose-route always ours, because otherwise this message never reach here.
                if (route.Param_Lr)
                {
                    request.Route.RemoveTopMostValue();
                }
                // It's our route, remove it.
                else if (IsLocalRoute(route))
                {
                    request.Route.RemoveTopMostValue();
                }
            }

            #endregion

            #region REGISTER request processing

            if (e.Request.RequestLine.Method == SIP_Methods.REGISTER)
            {
                SIP_Uri requestUri = (SIP_Uri)e.Request.RequestLine.Uri;

                // REGISTER is meant for us.
                if (this.OnIsLocalUri(requestUri.Host))
                {
                    if ((m_ProxyMode & SIP_ProxyMode.Registrar) != 0)
                    {
                        m_pRegistrar.Register(e);

                        return;
                    }
                    else
                    {
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x405_Method_Not_Allowed, e.Request));

                        return;
                    }
                }
                // Forward REGISTER.
                // else{
            }

            #endregion

            #region 3. Determine target(s) for the request (Section 16.5)

            /* 3. Determine target(s) for the request (Section 16.5)
             *      Next, the proxy calculates the target(s) of the request.  The set of
             *      targets will either be predetermined by the contents of the request
             *      or will be obtained from an abstract location service.  Each target
             *      in the set is represented as a URI.
             *
             *      If the domain of the Request-URI indicates a domain this element is
             *      not responsible for, the Request-URI MUST be placed into the target
             *      set as the only target, and the element MUST proceed to the task of
             *      Request Forwarding (Section 16.6).
             *
             *      If the target set for the request has not been predetermined as
             *      described above, this implies that the element is responsible for the
             *      domain in the Request-URI, and the element MAY use whatever mechanism
             *      it desires to determine where to send the request.  Any of these
             *      mechanisms can be modeled as accessing an abstract Location Service.
             *      This may consist of obtaining information from a location service
             *      created by a SIP Registrar, reading a database, consulting a presence
             *      server, utilizing other protocols, or simply performing an
             *      algorithmic substitution on the Request-URI.  When accessing the
             *      location service constructed by a registrar, the Request-URI MUST
             *      first be canonicalized as described in Section 10.3 before being used
             *      as an index.  The output of these mechanisms is used to construct the
             *      target set.
             */

            // Non-SIP
            // Foreign SIP
            // Local SIP

            if (e.Request.RequestLine.Uri is SIP_Uri)
            {
                SIP_Uri requestUri = (SIP_Uri)e.Request.RequestLine.Uri;

                // Proxy is not responsible for the domain in the Request-URI.
                if (!this.OnIsLocalUri(requestUri.Host))
                {
                    /* NAT traversal.
                     *  When we do record routing, store request sender flow info and request target flow info.
                     *  Now the tricky part, how proxy later which flow is target (because both sides can send requests).
                     *    Sender-flow will store from-tag to flow and target-flow will store flowID only (Because we don't know to-tag).
                     *    Later if request to-tag matches(incoming request), use that flow, otherwise(outgoing request) other flow.
                     *
                     *    flowInfo: sender-flow "/" target-flow
                     *        sender-flow = from-tag ":" flowID
                     *        target-flow = flowID
                     */

                    SIP_Flow targetFlow = null;
                    string   flowInfo   = (route != null && route.Parameters["flowInfo"] != null) ? route.Parameters["flowInfo"].Value : null;
                    if (flowInfo != null && request.To.Tag != null)
                    {
                        string flow1Tag = flowInfo.Substring(0, flowInfo.IndexOf(':'));
                        string flow1ID  = flowInfo.Substring(flowInfo.IndexOf(':') + 1, flowInfo.IndexOf('/') - flowInfo.IndexOf(':') - 1);
                        string flow2ID  = flowInfo.Substring(flowInfo.IndexOf('/') + 1);

                        if (flow1Tag == request.To.Tag)
                        {
                            targetFlow = m_pStack.TransportLayer.GetFlow(flow1ID);
                        }
                        else
                        {
                            ;
                            targetFlow = m_pStack.TransportLayer.GetFlow(flow2ID);
                        }
                    }

                    requestContext.Targets.Add(new SIP_ProxyTarget(requestUri, targetFlow));
                }
                // Proxy is responsible for the domain in the Request-URI.
                else
                {
                    // Try to get AOR from registrar.
                    SIP_Registration registration = m_pRegistrar.GetRegistration(requestUri.Address);

                    // We have AOR specified in request-URI in registrar server.
                    if (registration != null)
                    {
                        // Add all AOR SIP contacts to target set.
                        foreach (SIP_RegistrationBinding binding in registration.Bindings)
                        {
                            if (binding.ContactURI is SIP_Uri && binding.TTL > 0)
                            {
                                requestContext.Targets.Add(new SIP_ProxyTarget((SIP_Uri)binding.ContactURI, binding.Flow));
                            }
                        }
                    }
                    // We don't have AOR specified in request-URI in registrar server.
                    else
                    {
                        // If the Request-URI indicates a resource at this proxy that does not
                        // exist, the proxy MUST return a 404 (Not Found) response.
                        if (!this.OnAddressExists(requestUri.Address))
                        {
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x404_Not_Found, e.Request));
                            return;
                        }
                    }

                    // If the target set remains empty after applying all of the above, the proxy MUST return an error response,
                    // which SHOULD be the 480 (Temporarily Unavailable) response.
                    if (requestContext.Targets.Count == 0)
                    {
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x480_Temporarily_Unavailable, e.Request));
                        return;
                    }
                }
            }

            #endregion

            #region x. Custom handling

            // x.1 Process custom request handlers, if any.
            foreach (SIP_ProxyHandler handler in this.Handlers)
            {
                try{
                    SIP_ProxyHandler h = handler;

                    // Reusing existing handler not allowed, create new instance of handler.
                    if (!handler.IsReusable)
                    {
                        h = (SIP_ProxyHandler)System.Activator.CreateInstance(handler.GetType());
                    }

                    if (h.ProcessRequest(requestContext))
                    {
                        // Handler processed request, we are done.
                        return;
                    }
                }
                catch (Exception x) {
                    m_pStack.OnError(x);
                }
            }

            // x.2 URI scheme.
            //  If no targets and request-URI non-SIP, reject request because custom handlers should have been handled it.
            if (requestContext.Targets.Count == 0 && !SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()))
            {
                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x416_Unsupported_URI_Scheme, e.Request));
                return;
            }

            #endregion

            #region 4. Forward the request (Section 16.6)

            #region Statefull

            if (statefull)
            {
                SIP_ProxyContext proxyContext = this.CreateProxyContext(requestContext, e.ServerTransaction, request, addRecordRoute);
                proxyContext.Start();
            }

            #endregion

            #region Stateless

            else
            {
                /* RFC 3261 16.6 Request Forwarding.
                 * For each target, the proxy forwards the request following these steps:
                 *  1.  Make a copy of the received request
                 *  2.  Update the Request-URI
                 *  3.  Update the Max-Forwards header field
                 *  4.  Optionally add a Record-route header field value
                 *  5.  Optionally add additional header fields
                 *  6.  Postprocess routing information
                 *  7.  Determine the next-hop address, port, and transport
                 *  8.  Add a Via header field value
                 *  9.  Add a Content-Length header field if necessary
                 *  10. Forward the new request
                 */

                /* RFC 3261 16.11 Stateless Proxy.
                 *  o  A stateless proxy MUST choose one and only one target from the target set. This choice
                 *     MUST only rely on fields in the message and time-invariant properties of the server. In
                 *     particular, a retransmitted request MUST be forwarded to the same destination each time
                 *     it is processed. Furthermore, CANCEL and non-Routed ACK requests MUST generate the same
                 *     choice as their associated INVITE.
                 *
                 *  However, a stateless proxy cannot simply use a random number generator to compute
                 *  the first component of the branch ID, as described in Section 16.6 bullet 8.
                 *  This is because retransmissions of a request need to have the same value, and
                 *  a stateless proxy cannot tell a retransmission from the original request.
                 *
                 *  We just use: "z9hG4bK-" + md5(topmost branch)
                 */

                bool      isStrictRoute = false;
                SIP_Hop[] hops          = null;

                #region 1.  Make a copy of the received request

                SIP_Request forwardRequest = request.Copy();

                #endregion

                #region 2.  Update the Request-URI

                forwardRequest.RequestLine.Uri = requestContext.Targets[0].TargetUri;

                #endregion

                #region 3.  Update the Max-Forwards header field

                forwardRequest.MaxForwards--;

                #endregion

                #region 4.  Optionally add a Record-route header field value

                #endregion

                #region 5.  Optionally add additional header fields

                #endregion

                #region 6.  Postprocess routing information

                /* 6. Postprocess routing information.
                 *
                 *  If the copy contains a Route header field, the proxy MUST inspect the URI in its first value.
                 *  If that URI does not contain an lr parameter, the proxy MUST modify the copy as follows:
                 *      - The proxy MUST place the Request-URI into the Route header
                 *        field as the last value.
                 *
                 *      - The proxy MUST then place the first Route header field value
                 *        into the Request-URI and remove that value from the Route header field.
                 */
                if (forwardRequest.Route.GetAllValues().Length > 0 && !forwardRequest.Route.GetTopMostValue().Parameters.Contains("lr"))
                {
                    forwardRequest.Route.Add(forwardRequest.RequestLine.Uri.ToString());

                    forwardRequest.RequestLine.Uri = SIP_Utils.UriToRequestUri(forwardRequest.Route.GetTopMostValue().Address.Uri);
                    forwardRequest.Route.RemoveTopMostValue();

                    isStrictRoute = true;
                }

                #endregion

                #region 7.  Determine the next-hop address, port, and transport

                /* 7. Determine the next-hop address, port, and transport.
                 *    The proxy MAY have a local policy to send the request to a
                 *    specific IP address, port, and transport, independent of the
                 *    values of the Route and Request-URI.  Such a policy MUST NOT be
                 *    used if the proxy is not certain that the IP address, port, and
                 *    transport correspond to a server that is a loose router.
                 *    However, this mechanism for sending the request through a
                 *    specific next hop is NOT RECOMMENDED; instead a Route header
                 *    field should be used for that purpose as described above.
                 *
                 *    In the absence of such an overriding mechanism, the proxy
                 *    applies the procedures listed in [4] as follows to determine
                 *    where to send the request.  If the proxy has reformatted the
                 *    request to send to a strict-routing element as described in
                 *    step 6 above, the proxy MUST apply those procedures to the
                 *    Request-URI of the request.  Otherwise, the proxy MUST apply
                 *    the procedures to the first value in the Route header field, if
                 *    present, else the Request-URI.  The procedures will produce an
                 *    ordered set of (address, port, transport) tuples.
                 *    Independently of which URI is being used as input to the
                 *    procedures of [4], if the Request-URI specifies a SIPS
                 *    resource, the proxy MUST follow the procedures of [4] as if the
                 *    input URI were a SIPS URI.
                 *
                 *    As described in [4], the proxy MUST attempt to deliver the
                 *    message to the first tuple in that set, and proceed through the
                 *    set in order until the delivery attempt succeeds.
                 *
                 *    For each tuple attempted, the proxy MUST format the message as
                 *    appropriate for the tuple and send the request using a new
                 *    client transaction as detailed in steps 8 through 10.
                 *
                 *    Since each attempt uses a new client transaction, it represents
                 *    a new branch.  Thus, the branch parameter provided with the Via
                 *    header field inserted in step 8 MUST be different for each
                 *    attempt.
                 *
                 *    If the client transaction reports failure to send the request
                 *    or a timeout from its state machine, the proxy continues to the
                 *    next address in that ordered set.  If the ordered set is
                 *    exhausted, the request cannot be forwarded to this element in
                 *    the target set.  The proxy does not need to place anything in
                 *    the response context, but otherwise acts as if this element of
                 *    the target set returned a 408 (Request Timeout) final response.
                 */
                SIP_Uri uri = null;
                if (isStrictRoute)
                {
                    uri = (SIP_Uri)forwardRequest.RequestLine.Uri;
                }
                else if (forwardRequest.Route.GetTopMostValue() != null)
                {
                    uri = (SIP_Uri)forwardRequest.Route.GetTopMostValue().Address.Uri;
                }
                else
                {
                    uri = (SIP_Uri)forwardRequest.RequestLine.Uri;
                }

                hops = m_pStack.GetHops(uri, forwardRequest.ToByteData().Length, ((SIP_Uri)forwardRequest.RequestLine.Uri).IsSecure);

                if (hops.Length == 0)
                {
                    if (forwardRequest.RequestLine.Method != SIP_Methods.ACK)
                    {
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x503_Service_Unavailable + ": No hop(s) for target.", forwardRequest));
                    }

                    return;
                }

                #endregion

                #region 8.  Add a Via header field value

                forwardRequest.Via.AddToTop("SIP/2.0/transport-tl-addign sentBy-tl-assign-it;branch=z9hG4bK-" + Net_Utils.ComputeMd5(request.Via.GetTopMostValue().Branch, true));

                // Add 'flowID' what received request, you should use the same flow to send response back.
                // For more info see RFC 3261 18.2.2.
                forwardRequest.Via.GetTopMostValue().Parameters.Add("flowID", request.Flow.ID);

                #endregion

                #region 9.  Add a Content-Length header field if necessary

                // Skip, our SIP_Message class is smart and do it when ever it's needed.

                #endregion

                #region 10. Forward the new request

                try{
                    try{
                        if (requestContext.Targets[0].Flow != null)
                        {
                            m_pStack.TransportLayer.SendRequest(requestContext.Targets[0].Flow, request);

                            return;
                        }
                    }
                    catch {
                        m_pStack.TransportLayer.SendRequest(request, null, hops[0]);
                    }
                }
                catch (SIP_TransportException x) {
                    string dummy = x.Message;

                    if (forwardRequest.RequestLine.Method != SIP_Methods.ACK)
                    {
                        /* RFC 3261 16.9 Handling Transport Errors
                         *  If the transport layer notifies a proxy of an error when it tries to
                         *  forward a request (see Section 18.4), the proxy MUST behave as if the
                         *  forwarded request received a 503 (Service Unavailable) response.
                         */
                        e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x503_Service_Unavailable + ": Transport error.", forwardRequest));
                    }
                }

                #endregion
            }

            #endregion

            #endregion
        }
예제 #14
0
        internal SIP_ProxyContext CreateProxyContext(SIP_RequestContext requestContext, SIP_ServerTransaction transaction, SIP_Request request, bool addRecordRoute)
        {
            // Create proxy context that will be responsible for forwarding request.
            SIP_ProxyContext proxyContext = new SIP_ProxyContext(
                this,
                transaction,
                request,
                addRecordRoute,
                m_ForkingMode,
                (this.ProxyMode & SIP_ProxyMode.B2BUA) != 0,
                false,
                false,
                requestContext.Targets.ToArray()
                );

            m_pProxyContexts.Add(proxyContext);

            return(proxyContext);
        }
예제 #15
0
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                lock (m_pLock)
                {
                    if (m_IsDisposed)
                    {
                        return;
                    }
                    m_IsDisposed = true;

                    m_pOwner.TargetHandler_Disposed(this);

                    m_pOwner = null;
                    m_pRequest = null;
                    m_pTargetUri = null;
                    m_pHops = null;
                    if (m_pTransaction != null)
                    {
                        m_pTransaction.Dispose();
                        m_pTransaction = null;
                    }
                    if (m_pTimerC != null)
                    {
                        m_pTimerC.Dispose();
                        m_pTimerC = null;
                    }
                }
            }
예제 #16
0
        public void Handler(Packet packet)
        {
            var udpPacket = UdpPacket.GetEncapsulated(packet);

            // if it's not udp , udpPacket will be null and we don't handle it.
            if (udpPacket != null)
            {
                try
                {
                    // signalling packet
                    SIP_Message msg = ParseSIPMessage(udpPacket.PayloadData);
                    if (msg != null && msg.CallID != null)
                    {
                        SDP_Message sdp = null;
                        Console.WriteLine("SIP capture");
                        try
                        {
                            sdp = SDP_Message.Parse(System.Text.Encoding.Default.GetString(msg.Data));
                        }
                        catch { }

                        if (msg is SIP_Request && msg.CallID != null)
                        {
                            SIP_Request r = (SIP_Request)msg;
                            //already containsKey
                            if (!Call.SIPSessions.ContainsKey(r.CallID))
                            {
                                if (r.RequestLine.Method == "INVITE")
                                {
                                    Call.SIPSessions.Add(r.CallID, new Call(r.CallID));
                                    Call.SIPSessions[r.CallID].CallerIP = ((IpPacket)udpPacket.ParentPacket).SourceAddress;
                                    Call.SIPSessions[r.CallID].CalleeIP = ((IpPacket)udpPacket.ParentPacket).DestinationAddress;
                                }
                                else
                                {
                                    return;     // Ignore this conversation
                                }
                            }

                            // if this is an invite, do we have an audio rtp port defined?
                            if (r.RequestLine.Method == "INVITE")
                            {
                                if (sdp != null)
                                {
                                    foreach (var a in sdp.MediaDescriptions)
                                    {
                                        Console.Out.WriteLine(r.CallID + " - Got RTP Media Port: " + ((IpPacket)udpPacket.ParentPacket).SourceAddress + ":" + a.Port.ToString());
                                        if (Call.SIPSessions[r.CallID].CallerIP.ToString() == ((IpPacket)udpPacket.ParentPacket).SourceAddress.ToString())
                                        {
                                            Call.SIPSessions[r.CallID].CallerRTPPort = a.Port;
                                        }
                                        else
                                        {
                                            Call.SIPSessions[r.CallID].CalleeRTPPort = a.Port;
                                        }
                                        a.MediaFormats.GetType();

                                        break; // First description is about audio . Second is about viedo and we don't need it, so break.
                                    }
                                }
                            }

                            if (r.RequestLine.Method == "BYE")
                            {
                                if (Call.SIPSessions.ContainsKey(r.CallID))
                                {
                                    // Log bye was recevied
                                    Call.SIPSessions[r.CallID].SeenBYE = true;

                                    // Now indicate who hung up
                                    Call.SIPSessions[r.CallID].WhoHungUp = ((IpPacket)udpPacket.ParentPacket).SourceAddress == Call.SIPSessions[r.CallID].CallerIP ?
                                                                           Call.CallDirection.Caller : Call.CallDirection.Callee;
                                }
                                else
                                {
                                    Console.WriteLine("Unknown CallID: " + r.CallID);
                                }
                            }
                        }//    if (msg is SIP_Request && msg.CallID != null)
                        else if (msg is SIP_Response && msg.CallID != null)
                        {
                            SIP_Response r = (SIP_Response)msg;

                            if (r.StatusCode != 183 && r.StatusCode != 100 && r.StatusCode != 200)
                            {
                                Call.SIPSessions[r.CallID].isEnd = true;
                            }

                            if (sdp != null)
                            {
                                foreach (var a in sdp.MediaDescriptions)
                                {
                                    Console.Out.WriteLine(r.CallID + " - Got RTP Media Port: " + ((IpPacket)udpPacket.ParentPacket).SourceAddress + ":" + a.Port.ToString());
                                    if (Call.SIPSessions[r.CallID].CallerIP.ToString() == ((IpPacket)udpPacket.ParentPacket).SourceAddress.ToString())
                                    {
                                        Call.SIPSessions[r.CallID].CallerRTPPort = a.Port;
                                    }
                                    else
                                    {
                                        Call.SIPSessions[r.CallID].CalleeRTPPort = a.Port;
                                    }

                                    break; // First description is about audio . Second is about viedo and we don't need it, so break.
                                }
                            }

                            if (Call.SIPSessions.ContainsKey(r.CallID))
                            {
                                if (r.StatusCodeType == SIP_StatusCodeType.Success && Call.SIPSessions[r.CallID].SeenBYE)
                                {
                                    Call.SIPSessions[r.CallID].Confirmed = true;
                                    Call.SIPSessions[r.CallID].isEnd     = true;
                                }
                            }
                        }

                        // Add packet to history
                        if (Call.SIPSessions.ContainsKey(msg.CallID))
                        {
                            Call.SIPSessions[msg.CallID].WritePacket(packet, Call.PacketType.SIPDialog);
                            // Check to see is this call has been terminated
                            if (Call.SIPSessions[msg.CallID].Confirmed)
                            {
                                // Close off the call now last data has been written
                                Console.WriteLine("Call Ended: " + msg.CallID);

                                // Close off the call
                                Call.SIPSessions[msg.CallID].CloseCall();

                                StringBuilder file        = new StringBuilder(Directory.GetCurrentDirectory() + "//" + Call.SIPSessions[msg.CallID].SIPPacketFilePathAndName);
                                StringBuilder StoragePath = new StringBuilder(Directory.GetCurrentDirectory() + "//" + Call.SIPSessions[msg.CallID].SIPPacketFilePath);
                                pacp_to_wav(file, StoragePath);
                            }

                            if (Call.SIPSessions[msg.CallID].isEnd == true)
                            {
                                Call.SIPSessions.Remove(msg.CallID);
                            }
                        }
                    }
                    else
                    {
                        Call c = Call.GetCallByRTPPort(udpPacket.SourcePort);
                        if (c != null)
                        {
                            c.WritePacket(packet, Call.PacketType.RTP);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
        /// <summary>
        /// Handles REGISTER method.
        /// </summary>
        /// <param name="request">SIP REGISTER request.</param>
        public void Register(SIP_Request request)
        {
            /* RFC 3261 10.3 Processing REGISTER Requests.
                1. The registrar inspects the Request-URI to determine whether it
                    has access to bindings for the domain identified in the Request-URI.

                2. To guarantee that the registrar supports any necessary extensions,
                   the registrar MUST process the Require header field.

                3. A registrar SHOULD authenticate the UAC.

                4. The registrar SHOULD determine if the authenticated user is
                   authorized to modify registrations for this address-of-record.

                5. The registrar extracts the address-of-record from the To header
                   field of the request.  If the address-of-record is not valid
                   for the domain in the Request-URI, the registrar MUST send a
                   404 (Not Found) response and skip the remaining steps.

                6. The registrar checks whether the request contains the Contact
                   header field.  If not, it skips to the last step.  If the
                   Contact header field is present, the registrar checks if there
                   is one Contact field value that contains the special value "*"
                   and an Expires field.  If the request has additional Contact
                   fields or an expiration time other than zero, the request is
                   invalid, and the server MUST return a 400 (Invalid Request).

                7. The registrar now processes each contact address in the Contact
                   eader field in turn.

                   If Expire paremeter specified, check that it isnt smaller than server minimum
                   allowed expire value. If smaller return error 423 (Interval Too Brief) and add
                   header field Min-Expires. If no expire parameter, user server default value.

                8. The registrar returns a 200 (OK) response.  The response MUST contain Contact
                   header field values enumerating all current bindings. Each Contact value MUST
                   feature an "expires" parameter indicating its expiration interval chosen by the
                   registrar. The response SHOULD include a Date header field.

            */

            SocketEx socket = request.Socket;

            // 3. -------------------------------------------------------------------------
            // User didn't supplied credentials.
            if(request.Authorization.Count == 0){
                SIP_Response notAuthenticatedResponse = request.CreateResponse(SIP_ResponseCodes.Unauthorized);
                notAuthenticatedResponse.WWWAuthenticate.Add("digest realm=\"\",qop=\"auth\",nonce=\"" + m_pProxy.Stack.DigestNonceManager.CreateNonce() + "\",opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"");

                // Send response
                m_pProxy.Stack.TransportLayer.SendResponse(socket,notAuthenticatedResponse);
                return;
            }

            // Check that client supplied supported authentication method.
            string authenticationData = "";
            // digest
            if(request.Authorization.GetFirst().ValueX.Method.ToLower() == "digest"){
                authenticationData = request.Authorization.GetFirst().ValueX.AuthData;
            }
            // Not supported authentication.
            else{
                m_pProxy.Stack.TransportLayer.SendResponse(socket,request.CreateResponse(SIP_ResponseCodes.Not_Implemented + " authentication method"));
                return;
            }

            Auth_HttpDigest auth = new Auth_HttpDigest(authenticationData,request.Method);
            // Check nonce validity
            if(!m_pProxy.Stack.DigestNonceManager.NonceExists(auth.Nonce)){
                SIP_Response notAuthenticatedResponse = request.CreateResponse(SIP_ResponseCodes.Unauthorized);
                notAuthenticatedResponse.WWWAuthenticate.Add("digest realm=\"\",qop=\"auth\",nonce=\"" + m_pProxy.Stack.DigestNonceManager.CreateNonce() + "\",opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"");

                // Send response
                m_pProxy.Stack.TransportLayer.SendResponse(socket,notAuthenticatedResponse);
                return;
            }
            // Valid nonce, consume it so that nonce can't be used any more.
            else{
                m_pProxy.Stack.DigestNonceManager.RemoveNonce(auth.Nonce);
            }

            SIP_ServerProxyCore.AuthenticateEventArgs eArgs = m_pProxy.OnAuthenticate(auth);
            // Authenticate failed.
            if(!eArgs.Authenticated){
                SIP_Response notAuthenticatedResponse = request.CreateResponse(SIP_ResponseCodes.Unauthorized);
                notAuthenticatedResponse.WWWAuthenticate.Add("digest realm=\"\",qop=\"auth\",nonce=\"" + m_pProxy.Stack.DigestNonceManager.CreateNonce() + "\",opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"");

                // Send response
                m_pProxy.Stack.TransportLayer.SendResponse(socket,notAuthenticatedResponse);
                return;
            }
            //----------------------------------------------------------------------------

            // 5. Get TO:.
            string registrationName = SipUtils.ParseAddress(request.To.ToStringValue()).ToLower();

            // 4. Check if user can register specified address.
            // User is not allowed to register specified address.
            if(!m_pProxy.OnCanRegister(auth.UserName,registrationName)){
                m_pProxy.Stack.TransportLayer.SendResponse(socket,request.CreateResponse(SIP_ResponseCodes.Forbidden));
                return;
            }

            //--- 6. And 7. --------------------------------------------------------
            SIP_t_ContactParam[] contacts = request.Contact.GetAllValues();
            if(request.Header.Contains("Contact:")){
                SIP_t_ContactParam starContact = null;
                foreach(SIP_t_ContactParam contact in contacts){
                    // We have STAR contact, store it.
                    if(starContact == null && contact.IsStarContact){
                        starContact = contact;
                    }

                    //--- Handle minimum expires time --------------------------------------------
                    // Get contact expires time, if not specified, get header expires time.
                    int expires = contact.Expires;
                    if(expires < 1){
                        expires = request.Expires;
                    }
                    // We don't check that for STAR contact and if contact expires parameter = 0.
                    if(!contact.IsStarContact && contact.Expires != 0 && expires < m_pProxy.Stack.MinimumExpireTime){
                        // RFC 3261 20.23 must add Min-Expires
                        SIP_Response sipExpiresResponse = request.CreateResponse(SIP_ResponseCodes.Interval_Too_Brief);

                        // The response SHOULD include a Date header field.
                        sipExpiresResponse.Header.Add("Date:",DateTime.Now.ToString("r"));

                        // Send response
                        m_pProxy.Stack.TransportLayer.SendResponse(socket,sipExpiresResponse);
                        return;
                    }
                    //---------------------------------------------------------------------------
                }

                // We have STAR contact. Check that STAR contact meets all RFC rules.
                if(starContact != null){
                    // We may have only 1 STAR Contact and expires must be 0.
                    if(contacts.Length > 1 || starContact.Expires != 0){
                        m_pProxy.Stack.TransportLayer.SendResponse(socket,request.CreateResponse(SIP_ResponseCodes.Bad_Request + ". Invalid STAR Contact: combination or parameter. For more info see RFC 3261 10.3.6."));
                        return;
                    }
                    // We have valid STAR Contact:.
                    //else{
                    //}
                }
            }

            // Add or get SIP registration
            SIP_Registration registration = null;
            lock(m_pRegistrations){
                if(!m_pRegistrations.Contains(registrationName)){
                    // Add SIP registration.
                    registration = new SIP_Registration(auth.UserName,registrationName);
                    m_pRegistrations.Add(registration);
                }
                // Update SIP registration contacts
                else{
                    registration = m_pRegistrations[registrationName];
                }
            }

            // Update registration contacts
            registration.UpdateContacts(contacts,request.Expires);
            //--------------------------------------------------------------------

            // 8. --- Make and send SIP respone ----------------------------------
            SIP_Response sipResponse = request.CreateResponse(SIP_ResponseCodes.Ok);

            // The response SHOULD include a Date header field.
            sipResponse.Date = DateTime.Now;

            // List Registered Contacts
            sipResponse.Header.RemoveAll("Contact:");
            foreach(SIP_RegistrationContact contact in registration.Contacts){
                sipResponse.Header.Add("Contact:",contact.Contact.ToStringValue());
            }

            // Add Authentication-Info:, then client knows next nonce.
            sipResponse.AuthenticationInfo.Add("qop=\"auth\",nextnonce=\"" + m_pProxy.Stack.DigestNonceManager.CreateNonce() + "\"");

            // Send response
            m_pProxy.Stack.TransportLayer.SendResponse(socket,sipResponse);
            //-----------------------------------------------------------------------
        }
예제 #18
0
            /// <summary>
            /// Checks if specified ACK request matches this 2xx response retransmission.
            /// </summary>
            /// <param name="ackRequest">ACK request.</param>
            /// <returns>Returns true if ACK matches, othwerwise false.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>ackRequest</b> is null reference value.</exception>
            public bool MatchAck(SIP_Request ackRequest)
            {
                if(ackRequest == null){
                    throw new ArgumentNullException("ackRequest");
                }

                if(ackRequest.CSeq.SequenceNumber == m_pResponse.CSeq.SequenceNumber){
                    return true;
                }
                else{
                    return false;
                }
            }
예제 #19
0
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                lock(m_pLock){
                    if(m_IsDisposed){
                        return;
                    }
                    m_IsDisposed = true;

                    m_pDialog.m_pUacInvite2xxRetransmitWaits.Remove(this);

                    m_pDialog = null;
                    m_pInvite = null;
                    if(m_pTimer != null){
                        m_pTimer.Dispose();
                        m_pTimer = null;
                    }
                }
            }
예제 #20
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="dialog">Owner INVITE dialog.</param>
            /// <param name="invite">INVITE request which 2xx retransmission to wait.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>dialog</b> or <b>invite</b> is null reference.</exception>
            public UacInvite2xxRetransmissionWaiter(SIP_Dialog_Invite dialog,SIP_Request invite)
            {
                if(dialog == null){
                    throw new ArgumentNullException("dialog");
                }
                if(invite == null){
                    throw new ArgumentNullException("invite");
                }

                m_pDialog = dialog;
                m_pInvite = invite;

                /* RFC 3261 13.2.2.4.
                    The UAC core considers the INVITE transaction completed 64*T1 seconds
                    after the reception of the first 2xx response.
                */
                m_pTimer = new TimerEx(64 * SIP_TimerConstants.T1,false);
                m_pTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_pTimer_Elapsed);
                m_pTimer.Enabled = true;
            }
예제 #21
0
        /// <summary>
        /// Handles REGISTER method.
        /// </summary>
        /// <param name="e">Request event arguments.</param>
        internal void Register(SIP_RequestReceivedEventArgs e)
        {
            /* RFC 3261 10.3 Processing REGISTER Requests.
             *  1. The registrar inspects the Request-URI to determine whether it
             *     has access to bindings for the domain identified in the
             *     Request-URI.  If not, and if the server also acts as a proxy
             *     server, the server SHOULD forward the request to the addressed
             *     domain, following the general behavior for proxying messages
             *     described in Section 16.
             *
             *  2. To guarantee that the registrar supports any necessary extensions,
             *     the registrar MUST process the Require header field.
             *
             *  3. A registrar SHOULD authenticate the UAC.
             *
             *  4. The registrar SHOULD determine if the authenticated user is
             *     authorized to modify registrations for this address-of-record.
             *     For example, a registrar might consult an authorization
             *     database that maps user names to a list of addresses-of-record
             *     for which that user has authorization to modify bindings.  If
             *     the authenticated user is not authorized to modify bindings,
             *     the registrar MUST return a 403 (Forbidden) and skip the
             *     remaining steps.
             *
             *  5. The registrar extracts the address-of-record from the To header
             *     field of the request.  If the address-of-record is not valid
             *     for the domain in the Request-URI, the registrar MUST send a
             *     404 (Not Found) response and skip the remaining steps.  The URI
             *     MUST then be converted to a canonical form.  To do that, all
             *     URI parameters MUST be removed (including the user-param), and
             *     any escaped characters MUST be converted to their unescaped
             *     form.  The result serves as an index into the list of bindings.
             *
             *  6. The registrar checks whether the request contains the Contact
             *     header field.  If not, it skips to the last step.  If the
             *     Contact header field is present, the registrar checks if there
             *     is one Contact field value that contains the special value "*"
             *     and an Expires field.  If the request has additional Contact
             *     fields or an expiration time other than zero, the request is
             *     invalid, and the server MUST return a 400 (Invalid Request) and
             *     skip the remaining steps.  If not, the registrar checks whether
             *     the Call-ID agrees with the value stored for each binding.  If
             *     not, it MUST remove the binding.  If it does agree, it MUST
             *     remove the binding only if the CSeq in the request is higher
             *     than the value stored for that binding.  Otherwise, the update
             *     MUST be aborted and the request fails.
             *
             *  7. The registrar now processes each contact address in the Contact
             *     header field in turn.  For each address, it determines the
             *     expiration interval as follows:
             *
             *       -  If the field value has an "expires" parameter, that value
             *          MUST be taken as the requested expiration.
             *
             *       -  If there is no such parameter, but the request has an
             *          Expires header field, that value MUST be taken as the requested expiration.
             *
             *       -  If there is neither, a locally-configured default value MUST
             *          be taken as the requested expiration.
             *
             *     The registrar MAY choose an expiration less than the requested
             *     expiration interval.  If and only if the requested expiration
             *     interval is greater than zero AND smaller than one hour AND
             *     less than a registrar-configured minimum, the registrar MAY
             *     reject the registration with a response of 423 (Interval Too
             *     Brief).  This response MUST contain a Min-Expires header field
             *     that states the minimum expiration interval the registrar is
             *     willing to honor.  It then skips the remaining steps.
             *
             *     For each address, the registrar then searches the list of
             *     current bindings using the URI comparison rules.  If the
             *     binding does not exist, it is tentatively added.  If the
             *     binding does exist, the registrar checks the Call-ID value.  If
             *     the Call-ID value in the existing binding differs from the
             *     Call-ID value in the request, the binding MUST be removed if
             *     the expiration time is zero and updated otherwise.  If they are
             *     the same, the registrar compares the CSeq value.  If the value
             *     is higher than that of the existing binding, it MUST update or
             *     remove the binding as above.  If not, the update MUST be
             *     aborted and the request fails.
             *
             *     This algorithm ensures that out-of-order requests from the same
             *     UA are ignored.
             *
             *     Each binding record records the Call-ID and CSeq values from
             *     the request.
             *
             *     The binding updates MUST be committed (that is, made visible to
             *     the proxy or redirect server) if and only if all binding
             *     updates and additions succeed.  If any one of them fails (for
             *     example, because the back-end database commit failed), the
             *     request MUST fail with a 500 (Server Error) response and all
             *     tentative binding updates MUST be removed.
             *
             *  8. The registrar returns a 200 (OK) response.  The response MUST
             *     contain Contact header field values enumerating all current
             *     bindings.  Each Contact value MUST feature an "expires"
             *     parameter indicating its expiration interval chosen by the
             *     registrar.  The response SHOULD include a Date header field.
             */

            SIP_ServerTransaction transaction = e.ServerTransaction;
            SIP_Request           request     = e.Request;
            SIP_Uri to       = null;
            string  userName = "";

            // Probably we need to do validate in SIP stack.

            #region Validate request

            if (SIP_Utils.IsSipOrSipsUri(request.To.Address.Uri.ToString()))
            {
                to = (SIP_Uri)request.To.Address.Uri;
            }
            else
            {
                transaction.SendResponse(
                    m_pStack.CreateResponse(
                        SIP_ResponseCodes.x400_Bad_Request + ": To: value must be SIP or SIPS URI.", request));
                return;
            }

            #endregion

            #region 1. Check if we are responsible for Request-URI domain

            // if(m_pProxy.OnIsLocalUri(e.Request.Uri)){
            // }
            // TODO:

            #endregion

            #region 2. Check that all required extentions supported

            #endregion

            #region 3. Authenticate request

            if (!m_pProxy.AuthenticateRequest(e, out userName))
            {
                return;
            }

            #endregion

            #region 4. Check if user user is authorized to modify registrations

            // We do this in next step(5.).

            #endregion

            #region 5. Check if address of record exists

            if (!m_pProxy.OnAddressExists(to.Address))
            {
                transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x404_Not_Found, request));
                return;
            }
            else if (!OnCanRegister(userName, to.Address))
            {
                transaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x403_Forbidden, request));
                return;
            }

            #endregion

            #region 6. Process * Contact if exists

            // Check if we have star contact.
            SIP_t_ContactParam starContact = null;
            foreach (SIP_t_ContactParam c in request.Contact.GetAllValues())
            {
                if (c.IsStarContact)
                {
                    starContact = c;
                    break;
                }
            }

            // We have star contact.
            if (starContact != null)
            {
                if (request.Contact.GetAllValues().Length > 1)
                {
                    transaction.SendResponse(
                        m_pStack.CreateResponse(
                            SIP_ResponseCodes.x400_Bad_Request +
                            ": RFC 3261 10.3.6 -> If star(*) present, only 1 contact allowed.",
                            request));
                    return;
                }
                else if (starContact.Expires != 0)
                {
                    transaction.SendResponse(
                        m_pStack.CreateResponse(
                            SIP_ResponseCodes.x400_Bad_Request +
                            ": RFC 3261 10.3.6 -> star(*) contact parameter 'expires' value must be always '0'.",
                            request));
                    return;
                }

                // Remove bindings.
                SIP_Registration reg = m_pRegistrations[to.Address];
                if (reg != null)
                {
                    foreach (SIP_RegistrationBinding b in reg.Bindings)
                    {
                        if (request.CallID != b.CallID || request.CSeq.SequenceNumber > b.CSeqNo)
                        {
                            b.Remove();
                        }
                    }
                }
            }

            #endregion

            #region 7. Process Contact values

            if (starContact == null)
            {
                SIP_Registration reg = m_pRegistrations[to.Address];
                if (reg == null)
                {
                    reg = new SIP_Registration(userName, to.Address);
                    m_pRegistrations.Add(reg);
                }

                // We may do updates in batch only.
                // We just validate all values then do update(this ensures that update doesn't fail).

                // Check expires and CSeq.
                foreach (SIP_t_ContactParam c in request.Contact.GetAllValues())
                {
                    if (c.Expires == -1)
                    {
                        c.Expires = request.Expires;
                    }
                    if (c.Expires == -1)
                    {
                        c.Expires = m_pProxy.Stack.MinimumExpireTime;
                    }
                    // We must accept 0 values - means remove contact.
                    if (c.Expires != 0 && c.Expires < m_pProxy.Stack.MinimumExpireTime)
                    {
                        SIP_Response resp = m_pStack.CreateResponse(
                            SIP_ResponseCodes.x423_Interval_Too_Brief, request);
                        resp.MinExpires = m_pProxy.Stack.MinimumExpireTime;
                        transaction.SendResponse(resp);
                        return;
                    }

                    SIP_RegistrationBinding currentBinding = reg.GetBinding(c.Address.Uri);
                    if (currentBinding != null && currentBinding.CallID == request.CallID &&
                        request.CSeq.SequenceNumber < currentBinding.CSeqNo)
                    {
                        transaction.SendResponse(
                            m_pStack.CreateResponse(
                                SIP_ResponseCodes.x400_Bad_Request + ": CSeq value out of order.", request));
                        return;
                    }
                }

                // Do binding updates.
                reg.AddOrUpdateBindings(e.ServerTransaction.Flow,
                                        request.CallID,
                                        request.CSeq.SequenceNumber,
                                        request.Contact.GetAllValues());
            }

            #endregion

            #region 8. Create 200 OK response and return all current bindings

            SIP_Response response = m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, request);
            response.Date = DateTime.Now;
            SIP_Registration registration = m_pRegistrations[to.Address];
            if (registration != null)
            {
                foreach (SIP_RegistrationBinding b in registration.Bindings)
                {
                    // Don't list expired bindings what wait to be disposed.
                    if (b.TTL > 1)
                    {
                        response.Header.Add("Contact:", b.ToContactValue());
                    }
                }
            }
            // Add Authentication-Info:, then client knows next nonce.
            response.AuthenticationInfo.Add("qop=\"auth\",nextnonce=\"" +
                                            m_pStack.DigestNonceManager.CreateNonce() + "\"");
            transaction.SendResponse(response);

            #endregion
        }
예제 #22
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="proxy">Owner proxy.</param>
        /// <param name="transaction">Server transaction what is used to send SIP responses back to caller.</param>
        /// <param name="request">Request to forward.</param>
        /// <param name="addRecordRoute">If true, Record-Route header field will be added.</param>
        /// <param name="forkingMode">Specifies how proxy context must handle forking.</param>
        /// <param name="isB2BUA">Specifies if proxy context is in B2BUA or just transaction satefull mode.</param>
        /// <param name="noCancel">Specifies if proxy should not send Cancel to forked requests.</param>
        /// <param name="noRecurse">Specifies what proxy server does when it gets 3xx response. If true proxy will forward
        /// request to new specified address if false, proxy will return 3xx response to caller.</param>
        /// <param name="targets">Possible remote targets. NOTE: These values must be in priority order !</param>
        /// <param name="credentials">Target set credentials.</param>
        /// <exception cref="ArgumentNullException">Is raised when any of the reference type prameters is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        internal SIP_ProxyContext(SIP_ProxyCore proxy,
                                  SIP_ServerTransaction transaction,
                                  SIP_Request request,
                                  bool addRecordRoute,
                                  SIP_ForkingMode forkingMode,
                                  bool isB2BUA,
                                  bool noCancel,
                                  bool noRecurse,
                                  SIP_ProxyTarget[] targets,
                                  NetworkCredential[] credentials)
        {
            if (proxy == null)
            {
                throw new ArgumentNullException("proxy");
            }
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (targets == null)
            {
                throw new ArgumentNullException("targets");
            }
            if (targets.Length == 0)
            {
                throw new ArgumentException("Argumnet 'targets' must contain at least 1 value.");
            }

            m_pProxy = proxy;

            m_pServerTransaction = transaction;
            m_pServerTransaction.Canceled += m_pServerTransaction_Canceled;
            m_pServerTransaction.Disposed += m_pServerTransaction_Disposed;

            m_pRequest = request;
            m_AddRecordRoute = addRecordRoute;
            m_ForkingMode = forkingMode;
            m_IsB2BUA = isB2BUA;
            m_NoCancel = noCancel;
            m_NoRecurse = noRecurse;

            m_pTargetsHandlers = new List<TargetHandler>();
            m_pResponses = new List<SIP_Response>();
            m_ID = Guid.NewGuid().ToString();
            m_CreateTime = DateTime.Now;

            // Queue targets up, higest to lowest.
            m_pTargets = new Queue<TargetHandler>();
            foreach (SIP_ProxyTarget target in targets)
            {
                m_pTargets.Enqueue(new TargetHandler(this,
                                                     target.Flow,
                                                     target.TargetUri,
                                                     m_AddRecordRoute,
                                                     false));
            }

            m_pCredentials = new List<NetworkCredential>();
            m_pCredentials.AddRange(credentials);

            /*  RFC 3841 9.1.
                The Request-Disposition header field specifies caller preferences for
                how a server should process a request.
              
                Override SIP proxy default value.
            */
            foreach (SIP_t_Directive directive in request.RequestDisposition.GetAllValues())
            {
                if (directive.Directive == SIP_t_Directive.DirectiveType.NoFork)
                {
                    m_ForkingMode = SIP_ForkingMode.None;
                }
                else if (directive.Directive == SIP_t_Directive.DirectiveType.Parallel)
                {
                    m_ForkingMode = SIP_ForkingMode.Parallel;
                }
                else if (directive.Directive == SIP_t_Directive.DirectiveType.Sequential)
                {
                    m_ForkingMode = SIP_ForkingMode.Sequential;
                }
                else if (directive.Directive == SIP_t_Directive.DirectiveType.NoCancel)
                {
                    m_NoCancel = true;
                }
                else if (directive.Directive == SIP_t_Directive.DirectiveType.NoRecurse)
                {
                    m_NoRecurse = true;
                }
            }

            m_pProxy.Stack.Logger.AddText("ProxyContext(id='" + m_ID + "') created.");
        }
예제 #23
0
        /// <summary>
        /// This method is called when new request is received.
        /// </summary>
        /// <param name="e">Request event arguments.</param>
        internal void OnRequestReceived(SIP_RequestReceivedEventArgs e)
        {
            SIP_Request request = e.Request;

            if (request.RequestLine.Method == SIP_Methods.CANCEL)
            {
                /* RFC 3261 9.2.
                 *  If the UAS did not find a matching transaction for the CANCEL
                 *  according to the procedure above, it SHOULD respond to the CANCEL
                 *  with a 481 (Call Leg/Transaction Does Not Exist).
                 *
                 *  Regardless of the method of the original request, as long as the
                 *  CANCEL matched an existing transaction, the UAS answers the CANCEL
                 *  request itself with a 200 (OK) response.
                 */

                SIP_ServerTransaction trToCancel = m_pProxy.Stack.TransactionLayer.MatchCancelToTransaction(e.Request);
                if (trToCancel != null)
                {
                    trToCancel.Cancel();
                    //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x200_Ok));
                }
                else
                {
                    //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist));
                }
            }
            // We never should ge BYE here, because transport layer must match it to dialog.
            else if (request.RequestLine.Method == SIP_Methods.BYE)
            {
                /* RFC 3261 15.1.2.
                 *  If the BYE does not match an existing dialog, the UAS core SHOULD generate a 481
                 *  (Call/Transaction Does Not Exist) response and pass that to the server transaction.
                 */
                //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist));
            }
            // We never should ge ACK here, because transport layer must match it to dialog.
            else if (request.RequestLine.Method == SIP_Methods.ACK)
            {
                // ACK is response less request, so we may not return error to it.
            }
            // B2BUA must respond to OPTIONS request, not to forward it.
            else if (request.RequestLine.Method == SIP_Methods.OPTIONS)      /*
                                                                              * SIP_Response response = e.Request.CreateResponse(SIP_ResponseCodes.x200_Ok);
                                                                              * // Add Allow to non ACK response.
                                                                              * if(e.Request.RequestLine.Method != SIP_Methods.ACK){
                                                                              * response.Allow.Add("INVITE,ACK,OPTIONS,CANCEL,BYE,PRACK,MESSAGE,UPDATE");
                                                                              * }
                                                                              * // Add Supported to 2xx non ACK response.
                                                                              * if(response.StatusCodeType == SIP_StatusCodeType.Success && e.Request.RequestLine.Method != SIP_Methods.ACK){
                                                                              * response.Supported.Add("100rel,timer");
                                                                              * }
                                                                              * e.ServerTransaction.SendResponse(response);*/
            {
            }
            // We never should get PRACK here, because transport layer must match it to dialog.
            else if (request.RequestLine.Method == SIP_Methods.PRACK)
            {
                //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist));
            }
            // We never should get UPDATE here, because transport layer must match it to dialog.
            else if (request.RequestLine.Method == SIP_Methods.UPDATE)
            {
                //e.ServerTransaction.SendResponse(request.CreateResponse(SIP_ResponseCodes.x481_Call_Transaction_Does_Not_Exist));
            }
            else
            {
                /* draft-marjou-sipping-b2bua-00 4.1.3.
                 *  When the UAS of the B2BUA receives an upstream SIP request, its
                 *  associated UAC generates a new downstream SIP request with its new
                 *  Via, Max-Forwards, Call-Id, CSeq, and Contact header fields. Route
                 *  header fields of the upstream request are copied in the downstream
                 *  request, except the first Route header if it is under the
                 *  responsibility of the B2BUA.  Record-Route header fields of the
                 *  upstream request are not copied in the new downstream request, as
                 *  Record-Route is only meaningful for the upstream dialog.  The UAC
                 *  SHOULD copy other header fields and body from the upstream request
                 *  into this downstream request before sending it.
                 */

                SIP_Request b2buaRequest = e.Request.Copy();
                b2buaRequest.Via.RemoveAll();
                b2buaRequest.MaxForwards         = 70;
                b2buaRequest.CallID              = SIP_t_CallID.CreateCallID().CallID;
                b2buaRequest.CSeq.SequenceNumber = 1;
                b2buaRequest.Contact.RemoveAll();
                // b2buaRequest.Contact.Add(m_pProxy.CreateContact(b2buaRequest.To.Address).ToStringValue());
                if (b2buaRequest.Route.Count > 0 && m_pProxy.IsLocalRoute(SIP_Uri.Parse(b2buaRequest.Route.GetTopMostValue().Address.Uri.ToString())))
                {
                    b2buaRequest.Route.RemoveTopMostValue();
                }
                b2buaRequest.RecordRoute.RemoveAll();

                // Remove our Authorization header if it's there.
                foreach (SIP_SingleValueHF <SIP_t_Credentials> header in b2buaRequest.ProxyAuthorization.HeaderFields)
                {
                    try{
                        Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData, b2buaRequest.RequestLine.Method);
                        if (m_pProxy.Stack.Realm == digest.Realm)
                        {
                            b2buaRequest.ProxyAuthorization.Remove(header);
                        }
                    }
                    catch {
                        // We don't care errors here. This can happen if remote server xxx auth method here and
                        // we don't know how to parse it, so we leave it as is.
                    }
                }

                //--- Add/replace default fields. ------------------------------------------
                b2buaRequest.Allow.RemoveAll();
                b2buaRequest.Supported.RemoveAll();
                // Accept to non ACK,BYE request.
                if (request.RequestLine.Method != SIP_Methods.ACK && request.RequestLine.Method != SIP_Methods.BYE)
                {
                    b2buaRequest.Allow.Add("INVITE,ACK,OPTIONS,CANCEL,BYE,PRACK");
                }
                // Supported to non ACK request.
                if (request.RequestLine.Method != SIP_Methods.ACK)
                {
                    b2buaRequest.Supported.Add("100rel,timer");
                }
                // Remove Require: header.
                b2buaRequest.Require.RemoveAll();

                // RFC 4028 7.4. For re-INVITE and UPDATE we need to add Session-Expires and Min-SE: headers.
                if (request.RequestLine.Method == SIP_Methods.INVITE || request.RequestLine.Method == SIP_Methods.UPDATE)
                {
                    b2buaRequest.SessionExpires = new SIP_t_SessionExpires(m_pProxy.Stack.SessionExpries, "uac");
                    b2buaRequest.MinSE          = new SIP_t_MinSE(m_pProxy.Stack.MinimumSessionExpries);
                }

                // Forward request.
                //m_pProxy.ForwardRequest(true,e,b2buaRequest,false);
            }
        }
예제 #24
0
파일: SIPDump.cs 프로젝트: skrusty/SIPDump
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len  = e.Packet.Data.Length;

            var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packet);

            if (udpPacket != null)
            {
                try
                {
                    // signalling packet
                    SIP_Message msg = ParseSIPMessage(udpPacket.PayloadData);
                    if (msg != null && msg.CallID != null)
                    {
                        SDP_Message sdp = null;

                        try
                        {
                            sdp = SDP_Message.Parse(System.Text.ASCIIEncoding.Default.GetString(msg.Data));
                        }
                        catch { }

                        if (msg is SIP_Request && msg.CallID != null)
                        {
                            SIP_Request r = (SIP_Request)msg;

                            if (!Call.Calls.ContainsKey(r.CallID))
                            {
                                if (r.RequestLine.Method == "INVITE")
                                {
                                    Call.Calls.Add(r.CallID, new Call(r.CallID));
                                    Call.Calls[r.CallID].CallerIP = ((IpPacket)udpPacket.ParentPacket).SourceAddress;
                                    Call.Calls[r.CallID].CalleeIP = ((IpPacket)udpPacket.ParentPacket).DestinationAddress;
                                }
                                else
                                {
                                    return;     // Ignore this conversation
                                }
                            }

                            // if this is an invite, do we have an audio rtp port defined?
                            if (r.RequestLine.Method == "INVITE")
                            {
                                if (sdp != null)
                                {
                                    foreach (var a in sdp.MediaDescriptions)
                                    {
                                        Console.Out.WriteLine(r.CallID + " - Got RTP Media Port: " + ((IpPacket)udpPacket.ParentPacket).SourceAddress + ":" + a.Port.ToString());
                                        if (Call.Calls[r.CallID].CallerIP.ToString() == ((IpPacket)udpPacket.ParentPacket).SourceAddress.ToString())
                                        {
                                            Call.Calls[r.CallID].CallerRTPPort = a.Port;
                                        }
                                        else
                                        {
                                            Call.Calls[r.CallID].CalleeRTPPort = a.Port;
                                        }
                                    }
                                }
                            }

                            if (r.RequestLine.Method == "BYE")
                            {
                                if (Call.Calls.ContainsKey(r.CallID))
                                {
                                    // Log bye was recevied
                                    Call.Calls[r.CallID].SeenBYE = true;

                                    // Now indicate who hung up
                                    Call.Calls[r.CallID].WhoHungUp = ((IpPacket)udpPacket.ParentPacket).SourceAddress == Call.Calls[r.CallID].CallerIP ?
                                                                     Call.CallDirection.Caller : Call.CallDirection.Callee;
                                }
                                else
                                {
                                    Console.WriteLine("Unknown CallID: " + r.CallID);
                                }
                            }
                        }
                        else if (msg is SIP_Response && msg.CallID != null)
                        {
                            SIP_Response r = (SIP_Response)msg;

                            if (sdp != null)
                            {
                                foreach (var a in sdp.MediaDescriptions)
                                {
                                    Console.Out.WriteLine(r.CallID + " - Got RTP Media Port: " + ((IpPacket)udpPacket.ParentPacket).SourceAddress + ":" + a.Port.ToString());
                                    if (Call.Calls[r.CallID].CallerIP.ToString() == ((IpPacket)udpPacket.ParentPacket).SourceAddress.ToString())
                                    {
                                        Call.Calls[r.CallID].CallerRTPPort = a.Port;
                                    }
                                    else
                                    {
                                        Call.Calls[r.CallID].CalleeRTPPort = a.Port;
                                    }
                                }
                            }

                            if (Call.Calls.ContainsKey(r.CallID))
                            {
                                if (r.StatusCodeType == SIP_StatusCodeType.Success && Call.Calls[r.CallID].SeenBYE)
                                {
                                    Call.Calls[r.CallID].Confirmed = true;
                                }
                            }
                        }

                        // Add packet to history
                        if (Call.Calls.ContainsKey(msg.CallID))
                        {
                            Call.Calls[msg.CallID].WritePacket(e.Packet, Call.PacketType.SIPDialog);
                            // Check to see is this call has been terminated
                            if (Call.Calls[msg.CallID].Confirmed)
                            {
                                // Close off the call now last data has been written
                                Console.WriteLine("Call Ended: " + msg.CallID);

                                // Close off the call
                                Call.Calls[msg.CallID].CloseCall();

                                // Remove the call from the in-memory list
                                Call.Calls.Remove(msg.CallID);
                            }
                        }
                    }
                    else
                    {
                        Call c = Call.GetCallByRTPPort(udpPacket.SourcePort);
                        if (c != null)
                        {
                            c.WritePacket(e.Packet, Call.PacketType.RTP);
                        }
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
예제 #25
0
        /// <summary>
        /// This method is called when new request is received.
        /// </summary>
        /// <param name="e">Request event arguments.</param>
        private void OnRequestReceived(SIP_RequestReceivedEventArgs e)
        {
            SIP_Request request = e.Request;

            try{
                #region Statefull

                // Statefull
                if ((m_ProxyMode & SIP_ProxyMode.Statefull) != 0)
                {
                    // Statefull proxy is transaction statefull proxy only,
                    // what don't create dialogs and keep dialog state.

                    /* RFC 3261 16.10.
                     *  StateFull proxy:
                     *          If a matching response context is found, the element MUST
                     *          immediately return a 200 (OK) response to the CANCEL request.
                     *
                     *          If a response context is not found, the element does not have any
                     *          knowledge of the request to apply the CANCEL to.  It MUST statelessly
                     *          forward the CANCEL request (it may have statelessly forwarded the
                     *          associated request previously).
                     */
                    if (e.Request.RequestLine.Method == SIP_Methods.CANCEL)
                    {
                        // Don't do server transaction before we get CANCEL matching transaction.
                        SIP_ServerTransaction trToCancel = m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request);
                        if (trToCancel != null)
                        {
                            trToCancel.Cancel();
                            e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x200_Ok, request));
                        }
                        else
                        {
                            ForwardRequest(false, e, true);
                        }
                    }
                    // ACK never creates transaction, it's always passed directly to transport layer.
                    else if (e.Request.RequestLine.Method == SIP_Methods.ACK)
                    {
                        ForwardRequest(false, e, true);
                    }
                    else
                    {
                        ForwardRequest(true, e, true);
                    }
                }

                #endregion

                #region B2BUA

                // B2BUA
                else if ((m_ProxyMode & SIP_ProxyMode.B2BUA) != 0)
                {
                    m_pB2BUA.OnRequestReceived(e);
                }

                #endregion

                #region Stateless

                // Stateless
                else if ((m_ProxyMode & SIP_ProxyMode.Stateless) != 0)
                {
                    // Stateless proxy don't do transaction, just forwards all.
                    ForwardRequest(false, e, true);
                }

                #endregion

                #region Proxy won't accept command

                else
                {
                    e.ServerTransaction.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x501_Not_Implemented, request));
                }

                #endregion
            }
            catch (Exception x) {
                try{
                    m_pStack.TransportLayer.SendResponse(m_pStack.CreateResponse(SIP_ResponseCodes.x500_Server_Internal_Error + ": " + x.Message, e.Request));
                }
                catch {
                    // Skip transport layer exception if send fails.
                }

                // Don't raise OnError for transport errors.
                if (!(x is SIP_TransportException))
                {
                    m_pStack.OnError(x);
                }
            }
        }
예제 #26
0
        /// <summary>
        /// Forwards specified request to target recipient.
        /// </summary>
        /// <param name="statefull">Specifies if request is sent statefully or statelessly.</param>
        /// <param name="e">Request event arguments.</param>
        /// <param name="request">SIP request to forward.</param>
        /// <param name="addRecordRoute">Specifies if Record-Route header filed is added.</param>
        internal void ForwardRequest(bool statefull,
                                     SIP_RequestReceivedEventArgs e,
                                     SIP_Request request,
                                     bool addRecordRoute)
        {
            List<SIP_ProxyTarget> targetSet = new List<SIP_ProxyTarget>();
            List<NetworkCredential> credentials = new List<NetworkCredential>();
            SIP_Uri route = null;

            /* RFC 3261 16.
                1. Validate the request (Section 16.3)
                    1. Reasonable Syntax
                    2. URI scheme
                    3. Max-Forwards
                    4. (Optional) Loop Detection
                    5. Proxy-Require
                    6. Proxy-Authorization
                2. Preprocess routing information (Section 16.4)
                3. Determine target(s) for the request (Section 16.5)
                4. Forward the request (Section 16.6)
            */

            #region 1. Validate the request (Section 16.3)

            // 1.1 Reasonable Syntax.
            //      SIP_Message will do it.

            // 1.2 URI scheme check.
            if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()))
            {
                // TODO:
                SIP_GatewayEventArgs eArgs = OnGetGateways("uriScheme", "userName");
                // No suitable gateway or authenticated user has no access.
                if (eArgs.Gateways.Count == 0)
                {
                    e.ServerTransaction.SendResponse(
                        m_pStack.CreateResponse(SIP_ResponseCodes.x416_Unsupported_URI_Scheme, e.Request));
                    return;
                }
            }

            // 1.3 Max-Forwards.
            if (request.MaxForwards <= 0)
            {
                e.ServerTransaction.SendResponse(m_pStack.CreateResponse(
                                                     SIP_ResponseCodes.x483_Too_Many_Hops, request));
                return;
            }

            // 1.4 (Optional) Loop Detection.
            //      Skip.

            // 1.5 Proxy-Require.
            //      TODO:

            // 1.6 Proxy-Authorization.
            // We need to auth all foreign calls.            
            if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) ||
                !OnIsLocalUri(((SIP_Uri) request.RequestLine.Uri).Host))
            {
                // We need to pass-through ACK.
                if (request.RequestLine.Method == SIP_Methods.ACK) {}
                else if (!AuthenticateRequest(e))
                {
                    return;
                }
            }

            #endregion

            #region 2. Preprocess routing information (Section 16.4).

            /*
                The proxy MUST inspect the Request-URI of the request.  If the
                Request-URI of the request contains a value this proxy previously
                placed into a Record-Route header field (see Section 16.6 item 4),
                the proxy MUST replace the Request-URI in the request with the last
                value from the Route header field, and remove that value from the
                Route header field.  The proxy MUST then proceed as if it received
                this modified request.
             
                If the first value in the Route header field indicates this proxy,
                the proxy MUST remove that value from the request.
            */

            // Strict route.
            if (SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) &&
                IsLocalRoute(((SIP_Uri) request.RequestLine.Uri)))
            {
                request.RequestLine.Uri =
                    request.Route.GetAllValues()[request.Route.GetAllValues().Length - 1].Address.Uri;
                SIP_t_AddressParam[] routes = request.Route.GetAllValues();
                route = (SIP_Uri) routes[routes.Length - 1].Address.Uri;
                request.Route.RemoveLastValue();
            }
                // Loose route.
            else if (request.Route.GetAllValues().Length > 0 &&
                     IsLocalRoute(SIP_Uri.Parse(request.Route.GetTopMostValue().Address.Uri.ToString())))
            {
                route = (SIP_Uri) request.Route.GetTopMostValue().Address.Uri;
                request.Route.RemoveTopMostValue();
            }

            #endregion

            #region 3. Determine target(s) for the request (Section 16.5)

            /* 3. Determine target(s) for the request (Section 16.5)
                    Next, the proxy calculates the target(s) of the request.  The set of
                    targets will either be predetermined by the contents of the request
                    or will be obtained from an abstract location service.  Each target
                    in the set is represented as a URI.
             
                    If the domain of the Request-URI indicates a domain this element is
                    not responsible for, the Request-URI MUST be placed into the target
                    set as the only target, and the element MUST proceed to the task of
                    Request Forwarding (Section 16.6).
              
                    If the target set for the request has not been predetermined as
                    described above, this implies that the element is responsible for the
                    domain in the Request-URI, and the element MAY use whatever mechanism
                    it desires to determine where to send the request.  Any of these
                    mechanisms can be modeled as accessing an abstract Location Service.
                    This may consist of obtaining information from a location service
                    created by a SIP Registrar, reading a database, consulting a presence
                    server, utilizing other protocols, or simply performing an
                    algorithmic substitution on the Request-URI.  When accessing the
                    location service constructed by a registrar, the Request-URI MUST
                    first be canonicalized as described in Section 10.3 before being used
                    as an index.  The output of these mechanisms is used to construct the
                    target set.
            */

            // Non-SIP
            // Foreign SIP
            // Local SIP

            // FIX ME: we may have tel: here
            SIP_Uri requestUri = (SIP_Uri) e.Request.RequestLine.Uri;

            // Proxy is not responsible for the domain in the Request-URI.
            if (!OnIsLocalUri(requestUri.Host))
            {
                /* NAT traversal.
                    When we do record routing, store request sender flow info and request target flow info.
                    Now the tricky part, how proxy later which flow is target (because both sides can send requests).
                      Sender-flow will store from-tag to flow and target-flow will store flowID only (Because we don't know to-tag).
                      Later if request to-tag matches(incoming request), use that flow, otherwise(outgoing request) other flow.
                 
                    flowInfo: sender-flow "/" target-flow
                              sender-flow = from-tag ":" flowID
                              target-flow = flowID                        
                */

                SIP_Flow targetFlow = null;
                string flowInfo = (route != null && route.Parameters["flowInfo"] != null)
                                      ? route.Parameters["flowInfo"].Value
                                      : null;
                if (flowInfo != null && request.To.Tag != null)
                {
                    string flow1Tag = flowInfo.Substring(0, flowInfo.IndexOf(':'));
                    string flow1ID = flowInfo.Substring(flowInfo.IndexOf(':') + 1,
                                                        flowInfo.IndexOf('/') - flowInfo.IndexOf(':') - 1);
                    string flow2ID = flowInfo.Substring(flowInfo.IndexOf('/') + 1);

                    if (flow1Tag == request.To.Tag)
                    {
                        targetFlow = m_pStack.TransportLayer.GetFlow(flow1ID);
                    }
                    else
                    {
                        ;
                        targetFlow = m_pStack.TransportLayer.GetFlow(flow2ID);
                    }
                }

                targetSet.Add(new SIP_ProxyTarget(requestUri, targetFlow));
            }
                // Proxy is responsible for the domain in the Request-URI.
            else
            {
                // TODO: tel:
                //SIP_Uri requestUri = SIP_Uri.Parse(e.Request.Uri);

                // Try to get AOR from registrar.
                SIP_Registration registration = m_pRegistrar.GetRegistration(requestUri.Address);

                // We have AOR specified in request-URI in registrar server.
                if (registration != null)
                {
                    // Add all AOR SIP contacts to target set.
                    foreach (SIP_RegistrationBinding binding in registration.Bindings)
                    {
                        if (binding.ContactURI is SIP_Uri && binding.TTL > 0)
                        {
                            targetSet.Add(new SIP_ProxyTarget((SIP_Uri) binding.ContactURI, binding.Flow));
                        }
                    }
                }
                    // We don't have AOR specified in request-URI in registrar server.
                else
                {
                    // If the Request-URI indicates a resource at this proxy that does not
                    // exist, the proxy MUST return a 404 (Not Found) response.                    
                    if (!OnAddressExists(requestUri.Address))
                    {
                        e.ServerTransaction.SendResponse(
                            m_pStack.CreateResponse(SIP_ResponseCodes.x404_Not_Found, e.Request));
                        return;
                    }
                }
            }

            // If the target set remains empty after applying all of the above, the proxy MUST return an error response, 
            // which SHOULD be the 480 (Temporarily Unavailable) response.
            if (targetSet.Count == 0)
            {
                e.ServerTransaction.SendResponse(
                    m_pStack.CreateResponse(SIP_ResponseCodes.x480_Temporarily_Unavailable, e.Request));
                return;
            }

            #endregion

            #region 4. Forward the request (Section 16.6)

            #region Statefull

            if (statefull)
            {
                // Create proxy context that will be responsible for forwarding request.
                SIP_ProxyContext proxyContext = new SIP_ProxyContext(this,
                                                                     e.ServerTransaction,
                                                                     request,
                                                                     addRecordRoute,
                                                                     m_ForkingMode,
                                                                     (ProxyMode & SIP_ProxyMode.B2BUA) != 0,
                                                                     false,
                                                                     false,
                                                                     targetSet.ToArray(),
                                                                     credentials.ToArray());
                m_pProxyContexts.Add(proxyContext);
                proxyContext.Start();
            }

                #endregion

                #region Stateless

            else
            {
                /* RFC 3261 16.6 Request Forwarding.
                For each target, the proxy forwards the request following these steps:
                    1.  Make a copy of the received request
                    2.  Update the Request-URI
                    3.  Update the Max-Forwards header field
                    4.  Optionally add a Record-route header field value
                    5.  Optionally add additional header fields
                    6.  Postprocess routing information
                    7.  Determine the next-hop address, port, and transport
                    8.  Add a Via header field value
                    9.  Add a Content-Length header field if necessary
                    10. Forward the new request
                */

                /* RFC 3261 16.11 Stateless Proxy.                 
                    o  A stateless proxy MUST choose one and only one target from the target set. This choice 
                       MUST only rely on fields in the message and time-invariant properties of the server. In
                       particular, a retransmitted request MUST be forwarded to the same destination each time 
                       it is processed. Furthermore, CANCEL and non-Routed ACK requests MUST generate the same
                       choice as their associated INVITE.
                 
                    However, a stateless proxy cannot simply use a random number generator to compute
                    the first component of the branch ID, as described in Section 16.6 bullet 8.
                    This is because retransmissions of a request need to have the same value, and 
                    a stateless proxy cannot tell a retransmission from the original request.
                
                    We just use: "z9hG4bK-" + md5(topmost branch)                
                */

                bool isStrictRoute = false;
                SIP_Hop[] hops = null;

                #region 1.  Make a copy of the received request

                SIP_Request forwardRequest = request.Copy();

                #endregion

                #region 2.  Update the Request-URI

                forwardRequest.RequestLine.Uri = targetSet[0].TargetUri;

                #endregion

                #region 3.  Update the Max-Forwards header field

                forwardRequest.MaxForwards--;

                #endregion

                #region 4.  Optionally add a Record-route header field value

                #endregion

                #region 5.  Optionally add additional header fields

                #endregion

                #region 6.  Postprocess routing information

                /* 6. Postprocess routing information.
             
                    If the copy contains a Route header field, the proxy MUST inspect the URI in its first value.  
                    If that URI does not contain an lr parameter, the proxy MUST modify the copy as follows:             
                        - The proxy MUST place the Request-URI into the Route header
                          field as the last value.
             
                        - The proxy MUST then place the first Route header field value
                          into the Request-URI and remove that value from the Route header field.
                */
                if (forwardRequest.Route.GetAllValues().Length > 0 &&
                    !forwardRequest.Route.GetTopMostValue().Parameters.Contains("lr"))
                {
                    forwardRequest.Route.Add(forwardRequest.RequestLine.Uri.ToString());

                    forwardRequest.RequestLine.Uri =
                        SIP_Utils.UriToRequestUri(forwardRequest.Route.GetTopMostValue().Address.Uri);
                    forwardRequest.Route.RemoveTopMostValue();

                    isStrictRoute = true;
                }

                #endregion

                #region 7.  Determine the next-hop address, port, and transport

                /* 7. Determine the next-hop address, port, and transport.
                      The proxy MAY have a local policy to send the request to a
                      specific IP address, port, and transport, independent of the
                      values of the Route and Request-URI.  Such a policy MUST NOT be
                      used if the proxy is not certain that the IP address, port, and
                      transport correspond to a server that is a loose router.
                      However, this mechanism for sending the request through a
                      specific next hop is NOT RECOMMENDED; instead a Route header
                      field should be used for that purpose as described above.
             
                      In the absence of such an overriding mechanism, the proxy
                      applies the procedures listed in [4] as follows to determine
                      where to send the request.  If the proxy has reformatted the
                      request to send to a strict-routing element as described in
                      step 6 above, the proxy MUST apply those procedures to the
                      Request-URI of the request.  Otherwise, the proxy MUST apply
                      the procedures to the first value in the Route header field, if
                      present, else the Request-URI.  The procedures will produce an
                      ordered set of (address, port, transport) tuples.
                      Independently of which URI is being used as input to the
                      procedures of [4], if the Request-URI specifies a SIPS
                      resource, the proxy MUST follow the procedures of [4] as if the
                      input URI were a SIPS URI.

                      As described in [4], the proxy MUST attempt to deliver the
                      message to the first tuple in that set, and proceed through the
                      set in order until the delivery attempt succeeds.

                      For each tuple attempted, the proxy MUST format the message as
                      appropriate for the tuple and send the request using a new
                      client transaction as detailed in steps 8 through 10.
             
                      Since each attempt uses a new client transaction, it represents
                      a new branch.  Thus, the branch parameter provided with the Via
                      header field inserted in step 8 MUST be different for each
                      attempt.

                      If the client transaction reports failure to send the request
                      or a timeout from its state machine, the proxy continues to the
                      next address in that ordered set.  If the ordered set is
                      exhausted, the request cannot be forwarded to this element in
                      the target set.  The proxy does not need to place anything in
                      the response context, but otherwise acts as if this element of
                      the target set returned a 408 (Request Timeout) final response.
                */
                SIP_Uri uri = null;
                if (isStrictRoute)
                {
                    uri = (SIP_Uri) forwardRequest.RequestLine.Uri;
                }
                else if (forwardRequest.Route.GetTopMostValue() != null)
                {
                    uri = (SIP_Uri) forwardRequest.Route.GetTopMostValue().Address.Uri;
                }
                else
                {
                    uri = (SIP_Uri) forwardRequest.RequestLine.Uri;
                }

                hops = m_pStack.GetHops(uri,
                                        forwardRequest.ToByteData().Length,
                                        ((SIP_Uri) forwardRequest.RequestLine.Uri).IsSecure);

                if (hops.Length == 0)
                {
                    if (forwardRequest.RequestLine.Method != SIP_Methods.ACK)
                    {
                        e.ServerTransaction.SendResponse(
                            m_pStack.CreateResponse(
                                SIP_ResponseCodes.x503_Service_Unavailable + ": No hop(s) for target.",
                                forwardRequest));
                    }

                    return;
                }

                #endregion

                #region 8.  Add a Via header field value

                forwardRequest.Via.AddToTop(
                    "SIP/2.0/transport-tl-addign sentBy-tl-assign-it;branch=z9hG4bK-" +
                    Core.ComputeMd5(request.Via.GetTopMostValue().Branch, true));

                // Add 'flowID' what received request, you should use the same flow to send response back.
                // For more info see RFC 3261 18.2.2.
                forwardRequest.Via.GetTopMostValue().Parameters.Add("flowID", request.Flow.ID);

                #endregion

                #region 9.  Add a Content-Length header field if necessary

                // Skip, our SIP_Message class is smart and do it when ever it's needed.

                #endregion

                #region 10. Forward the new request

                try
                {
                    try
                    {
                        if (targetSet[0].Flow != null)
                        {
                            m_pStack.TransportLayer.SendRequest(targetSet[0].Flow, request);

                            return;
                        }
                    }
                    catch
                    {
                        m_pStack.TransportLayer.SendRequest(request, null, hops[0]);
                    }
                }
                catch (SIP_TransportException x)
                {
                    string dummy = x.Message;

                    if (forwardRequest.RequestLine.Method != SIP_Methods.ACK)
                    {
                        /* RFC 3261 16.9 Handling Transport Errors
                            If the transport layer notifies a proxy of an error when it tries to
                            forward a request (see Section 18.4), the proxy MUST behave as if the
                            forwarded request received a 503 (Service Unavailable) response.
                        */
                        e.ServerTransaction.SendResponse(
                            m_pStack.CreateResponse(
                                SIP_ResponseCodes.x503_Service_Unavailable + ": Transport error.",
                                forwardRequest));
                    }
                }

                #endregion
            }

            #endregion

            #endregion
        }
예제 #27
0
        /// <summary>
        /// Gets specified realm SIP proxy credentials. Returns null if none exists for specified realm.
        /// </summary>
        /// <param name="request">SIP reques.</param>
        /// <param name="realm">Realm(domain).</param>
        /// <returns>Returns specified realm credentials or null if none.</returns>
        public static SIP_t_Credentials GetCredentials(SIP_Request request, string realm)
        {
            foreach (
                SIP_SingleValueHF<SIP_t_Credentials> authorization in request.ProxyAuthorization.HeaderFields)
            {
                if (authorization.ValueX.Method.ToLower() == "digest")
                {
                    Auth_HttpDigest authDigest = new Auth_HttpDigest(authorization.ValueX.AuthData,
                                                                     request.RequestLine.Method);
                    if (authDigest.Realm.ToLower() == realm.ToLower())
                    {
                        return authorization.ValueX;
                    }
                }
            }

            return null;
        }
예제 #28
0
            /// <summary>
            /// Initializes target.
            /// </summary>
            private void Init()
            {
                /* RFC 3261 16.6 Request Forwarding.
                For each target, the proxy forwards the request following these steps:
                    1.  Make a copy of the received request
                    2.  Update the Request-URI
                    3.  Update the Max-Forwards header field
                    4.  Optionally add a Record-route header field value
                    5.  Optionally add additional header fields
                    6.  Postprocess routing information
                    7.  Determine the next-hop address, port, and transport
                */

                bool isStrictRoute = false;

                #region 1. Make a copy of the received request.

                // 1. Make a copy of the received request.
                m_pRequest = m_pOwner.Request.Copy();

                #endregion

                #region 2. Update the Request-URI.

                // 2. Update the Request-URI.
                m_pRequest.RequestLine.Uri = m_pTargetUri;

                #endregion

                #region 3. Update the Max-Forwards header field.

                // 3. Update the Max-Forwards header field.
                m_pRequest.MaxForwards--;

                #endregion

                #region 5. Optionally add additional header fields.

                // 5. Optionally add additional header fields.
                //    Skip.

                #endregion

                #region 6. Postprocess routing information.

                /* 6. Postprocess routing information.
             
                    If the copy contains a Route header field, the proxy MUST inspect the URI in its first value.  
                    If that URI does not contain an lr parameter, the proxy MUST modify the copy as follows:             
                        - The proxy MUST place the Request-URI into the Route header
                          field as the last value.
             
                        - The proxy MUST then place the first Route header field value
                          into the Request-URI and remove that value from the Route header field.
                */
                if (m_pRequest.Route.GetAllValues().Length > 0 &&
                    !m_pRequest.Route.GetTopMostValue().Parameters.Contains("lr"))
                {
                    m_pRequest.Route.Add(m_pRequest.RequestLine.Uri.ToString());

                    m_pRequest.RequestLine.Uri =
                        SIP_Utils.UriToRequestUri(m_pRequest.Route.GetTopMostValue().Address.Uri);
                    m_pRequest.Route.RemoveTopMostValue();

                    isStrictRoute = true;
                }

                #endregion

                #region 7. Determine the next-hop address, port, and transport.

                /* 7. Determine the next-hop address, port, and transport.
                      The proxy MAY have a local policy to send the request to a
                      specific IP address, port, and transport, independent of the
                      values of the Route and Request-URI.  Such a policy MUST NOT be
                      used if the proxy is not certain that the IP address, port, and
                      transport correspond to a server that is a loose router.
                      However, this mechanism for sending the request through a
                      specific next hop is NOT RECOMMENDED; instead a Route header
                      field should be used for that purpose as described above.
             
                      In the absence of such an overriding mechanism, the proxy
                      applies the procedures listed in [4] as follows to determine
                      where to send the request.  If the proxy has reformatted the
                      request to send to a strict-routing element as described in
                      step 6 above, the proxy MUST apply those procedures to the
                      Request-URI of the request.  Otherwise, the proxy MUST apply
                      the procedures to the first value in the Route header field, if
                      present, else the Request-URI.  The procedures will produce an
                      ordered set of (address, port, transport) tuples.
                      Independently of which URI is being used as input to the
                      procedures of [4], if the Request-URI specifies a SIPS
                      resource, the proxy MUST follow the procedures of [4] as if the
                      input URI were a SIPS URI.

                      As described in [4], the proxy MUST attempt to deliver the
                      message to the first tuple in that set, and proceed through the
                      set in order until the delivery attempt succeeds.

                      For each tuple attempted, the proxy MUST format the message as
                      appropriate for the tuple and send the request using a new
                      client transaction as detailed in steps 8 through 10.
             
                      Since each attempt uses a new client transaction, it represents
                      a new branch.  Thus, the branch parameter provided with the Via
                      header field inserted in step 8 MUST be different for each
                      attempt.

                      If the client transaction reports failure to send the request
                      or a timeout from its state machine, the proxy continues to the
                      next address in that ordered set.  If the ordered set is
                      exhausted, the request cannot be forwarded to this element in
                      the target set.  The proxy does not need to place anything in
                      the response context, but otherwise acts as if this element of
                      the target set returned a 408 (Request Timeout) final response.
                */
                SIP_Uri uri = null;
                if (isStrictRoute)
                {
                    uri = (SIP_Uri) m_pRequest.RequestLine.Uri;
                }
                else if (m_pRequest.Route.GetTopMostValue() != null)
                {
                    uri = (SIP_Uri) m_pRequest.Route.GetTopMostValue().Address.Uri;
                }
                else
                {
                    uri = (SIP_Uri) m_pRequest.RequestLine.Uri;
                }

                // Queue hops.
                foreach (
                    SIP_Hop hop in
                        m_pOwner.Proxy.Stack.GetHops(uri,
                                                     m_pRequest.ToByteData().Length,
                                                     ((SIP_Uri) m_pRequest.RequestLine.Uri).IsSecure))
                {
                    m_pHops.Enqueue(hop);
                }

                #endregion

                #region 4. Optionally add a Record-route header field value.

                // We need to do step 4 after step 7, because then transport in known.
                // Each transport can have own host-name, otherwise we don't know what to put into Record-Route.

                /*
                    If the Request-URI contains a SIPS URI, or the topmost Route header
                    field value (after the post processing of bullet 6) contains a SIPS URI,                 
                    the URI placed into the Record-Route header field MUST be a SIPS URI.
                    Furthermore, if the request was not received over TLS, the proxy MUST 
                    insert a Record-Route header field. In a similar fashion, a proxy that 
                    receives a request over TLS, but generates a request without a SIPS URI 
                    in the Request-URI or topmost Route header field value (after the post
                    processing of bullet 6), MUST insert a Record-Route header field that 
                    is not a SIPS URI.
                */

                // NOTE: ACK don't add Record-route header.
                if (m_pHops.Count > 0 && m_AddRecordRoute && m_pRequest.RequestLine.Method != SIP_Methods.ACK)
                {
                    string recordRoute =
                        m_pOwner.Proxy.Stack.TransportLayer.GetRecordRoute(m_pHops.Peek().Transport);
                    if (recordRoute != null)
                    {
                        m_pRequest.RecordRoute.Add(recordRoute);
                    }
                }

                #endregion
            }