\section{Behavior of SIP Proxy and Redirect Servers}
\label{sec:searching}

This section describes behavior of SIP redirect and proxy
servers in detail.  Proxy servers can ``fork'' connections, i.e., a
single incoming request spawns several outgoing (client) requests. 

\subsection{Redirect Server}

A redirect server does not issue any SIP requests of its own.  After
receiving a request 
\begin{changebar}
other than {\CANCEL}, 
\end{changebar}
the server gathers the list of
alternative locations and returns a final response of class 3xx or it
refuses the request.  For well-formed {\CANCEL} requests, it {\SHOULD}
return a 2xx response.  This response ends the SIP transaction.  The
redirect server maintains transaction state for the whole SIP
transaction.  It is up to the client to detect forwarding loops between
redirect servers.

\subsection{User Agent Server}

User agent servers behave similarly to redirect servers, except that
they also accept requests and can return a response of class 2xx.

\subsection{Proxy Server}
\label{sec:proxy}

This section outlines processing rules for proxy servers.  A proxy
server can either be stateful or stateless.  When stateful, a proxy
remembers the incoming request which generated outgoing requests, and
the outgoing requests.  A stateless proxy forgets all information once
an outgoing request is generated.  A forking proxy {\SHOULD} be
<<<<<<< searching.tex
stateful.  
\begin{changebar}
Proxies that accept TCP connections {\MUST} be stateful.

\motivation{Otherwise, if the proxy were to loose a request, the TCP
client would never retransmit it.}
\end{changebar}

A stateful proxy {\MAY} become stateless at any time, but
{\SHOULD} remain stateful until it sends a definitive response upstream.
=======
stateful.  
\begin{changebar}
Proxies that accept TCP connections {\MUST} be stateful.

\motivation{Otherwise, if the proxy were to lose a request, the TCP
client would never retransmit it.}
\end{changebar}

\begin{changebar}
A stateful proxy {\SHOULDNOT} become stateless until after it sends a
definitive response upstream, at least 32 seconds after it received
a definitive response.
\end{changebar}
>>>>>>> 1.22
 
A stateful proxy acts as a virtual UAS/UAC.  It implements the server
state machine when receiving requests, and the client state machine for
generating outgoing requests, with the exception of receiving a 2xx
response to an {\INVITE}.  Instead of generating an {\ACK}, the 2xx
response is always forwarded upstream towards the caller.  Furthermore,
{\ACK}'s for 200 responses to {\INVITE}'s are always proxied downstream
towards the UAS, as they would be for a stateless proxy. 
 
A stateless proxy does not act as a virtual UAS/UAC (as this would
require state). Rather, a stateless proxy forwards every request it
receives downstream, and every response it receives upstream. 

\subsubsection{Proxying Requests}

To prevent loops, a server {\MUST} check if its own address is already
contained in the \header{Via} header field of the incoming request.

The \header{To}, \header{From}, \header{Call-ID}, and \header{Contact}
tags are copied exactly from the original request.  The proxy {\SHOULD}
change the \header{Request-URI} to indicate the server where it intends
to send the request.

A proxy server always inserts a \header{Via} header field containing its
own address into those requests that are caused by an incoming request. 
Each proxy {\MUST} insert a ``\header{branch}'' parameter
(Section~\ref{sec:Via}). 

\subsubsection{Proxying Responses}

A proxy only processes a response if the topmost \header{Via} field
matches one of its addresses.  A response with a non-matching top
\header{Via} field \header{MUST} be dropped.
 
\subsubsection{Stateless Proxy: Proxying Responses}
\label{sec:stateless_response}

A stateless proxy removes its own \header{Via} field, and checks the
address in the next \header{Via} field.  In the case of UDP, the
response is sent to the address listed in the ``\header{maddr}'' tag
if present, otherwise to the ``\header{received}'' tag if present, and
finally to the address in the ``\header{sent-by}'' field.
\begin{changebar}
A proxy {\MUST}
remain stateful when handling requests received via TCP.
\end{changebar}

A stateless proxy {\MUSTNOT} generate its own provisional responses.

\subsubsection{Stateful Proxy: Receiving Requests}
\label{sec:stateful_requests}

When a stateful proxy receives a request, it checks the \header{To},
\header{From} (including tags), \header{Call-ID} and \header{CSeq}
against existing request records.  If the tuple exists, the request is a
retransmission.  The provisional or final response sent previously is
retransmitted, as per the server state machine.  If the tuple does not
exist, the request corresponds to a new transaction, and the request
should be proxied.

A stateful proxy server {\MAY} generate its own provisional (1xx)
responses.

\subsubsection{Stateful Proxy: Receiving {\ACK}s}

When an {\ACK} request is received, it is either processed locally
or proxied.  To make this determination, the \header{To}, \header{From},
\header{CSeq} and \header{Call-ID} fields are compared against those in
previous requests.  If there is no match, the \header{ACK} request is
proxied as if it were an {\INVITE} request.  If there is a match, and if
the server had ever sent a 200 response upstream, the {\ACK} is proxied. 
If the server had never sent any responses upstream, the {\ACK} is also
proxied.  If the server had sent a 3xx, 4xx, 5xx or 6xx response, but no
2xx response,
\begin{changebar}
the {\ACK} is processed locally if the tag in the
\header{To} field of the {\ACK} matches the tag sent by the proxy in
the response.
\end{changebar}

\subsubsection{Stateful Proxy: Receiving Responses}

When a proxy server receives a response that has passed the \header{Via}
checks, the proxy server checks the \header{To} (without the tag),
\header{From} (including the tag), \header{Call-ID} and \header{CSeq}
against values seen in previous requests.  If there is no match, the
response is forwarded upstream to the address listed in the \header{Via}
field.  If there is a match, the ``\header{branch}'' tag in the
\header{Via} field is examined.  If it matches a known branch
identifier, the response is for the given branch, and processed by the
virtual client for the given branch.  Otherwise, the response is
dropped.

A stateful proxy should obey the rules in Section
\ref{sec:server-several} to determine if the response should be
proxied upstream. If it is to be proxied, the same rules for stateless
proxies above are followed, with the following addition for TCP.
\begin{changebar}
If a
request was received via TCP (indicated by the protocol in the top
\header{Via} header, the proxy checks to see if it has a connection
currently open to that address.  If so, the response is sent on that
connection.  Otherwise, a new TCP connection is opened to the address
and port in the \header{Via} field, and the response is sent
there. Note that this implies that a UAC or proxy {\MUST} be prepared
to receive responses on the incoming side of a TCP
connection. Definitive non 200-class responses {\MUST} be
retransmitted by the proxy, even over a TCP connection.
\end{changebar}

\subsubsection{Stateless, Non-Forking Proxy}

Proxies in this category issue at most a single unicast request for each
incoming SIP request, that is, they do not ``fork'' requests.  However,
servers {\MAY} choose to always operate in a mode that allows issuing of
several requests, as described in Section~\ref{sec:server-several}.

The server can forward the request and any responses.  It does not have
to maintain any state for the SIP transaction.  Reliability is assured
by the next redirect or stateful proxy server in the server chain.

A proxy server {\SHOULD} cache the result of any address translations
and the response to speed forwarding of retransmissions.  After the
cache entry has been expired, the server cannot tell whether an incoming
request is actually a retransmission of an older request.  The server
will treat it as a new request and commence another search.

\subsection{Forking Proxy}
\label{sec:server-several}

The server {\MUST} respond to the request immediately with a 100
(Trying) response.

Successful responses to an {\INVITE} request {\SHOULD} contain a
\header{Contact} header field so that the following {\ACK} or {\BYE}
bypasses the proxy search mechanism.  If the proxy requires future
requests to be routed through it, it adds a \header{Record-Route} header
to the request (Section \ref{sec:Record-Route}).

The following C-code describes the behavior of a proxy server
issuing several requests in response to an incoming {\INVITE} request. 
The function {\tt request($r$, $a$, $b$)} sends a SIP request of type
$r$ to address $a$, with branch id $b$.  {\tt await\_response()} waits
until a response is received and returns the response.  {\tt close($a$)}
closes the TCP connection to client with address $a$.  {\tt
response($r$)} sends a response to the client.  {\tt ismulticast()}
returns 1 if the location is a multicast address and zero otherwise. 
The variable {\tt timeleft} indicates the amount of time left until the
maximum response time has expired.  The variable {\tt recurse} indicates
whether the server will recursively try addresses returned through a 3xx
response.  A server {\MAY} decide to recursively try only certain
addresses, e.g., those which are within the same domain as the proxy
server.  Thus, an initial multicast request can trigger additional
unicast requests.

\begin{verbatim}
  /* request type */
  typedef enum {INVITE, ACK, BYE, OPTIONS, CANCEL, REGISTER} Method;

  process_request(Method R, int N, address_t address[])
  {
    struct {
      int branch;         /* branch id */
      int done;           /* has responded */
    } outgoing[];
    int done[];           /* address has responded */
    char *location[];     /* list of locations */
    int heard = 0;        /* number of sites heard from */
    int class;            /* class of status code */
    int timeleft = 120;   /* sample timeout value */ 
    int loc = 0;          /* number of locations */
    struct {              /* response */
      int status;         /* response: CANCEL=-1 */
      int locations;      /* number of redirect locations */
      char *location[];   /* redirect locations */ 
      address_t a;        /* address of respondent */
      int branch;         /* branch identifier */
    } r, best;            /* response, best response */
    int i;

    best.status = 1000;
    for (i = 0; i < N; i++) {
      request(R, address[i], i);
      outgoing[i].done = 0;
      outgoing[i].branch = i;
    }

    while (timeleft > 0 && heard < N) {
      r = await_response();
      class = r.status / 100;

      /* If final response, mark branch as done. */
      if (class >= 2) {
        heard++;
        for (i = 0; i < N; i++) {
          if (r.branch == outgoing[i].branch) {
            outgoing[i].done = 1;
            break;
          }
        }
      }
      /* CANCEL: respond, fork and wait for responses */
      else if (class < 0) {
        best.status = 200;
        response(best);
        for (i = 0; i < N; i++) {
          if (!outgoing[i].done)
            request(CANCEL, address[i], outgoing[i].branch);
        }
        best.status = -1;
      }

      /* Send an ACK */
   
      if (class != 2) {
        if (R == INVITE) request(ACK, r.a, r.branch);
      }


      if (class == 2) {
        if (r.status < best.status) best = r;
        break;
      }
      else if (class == 3) {
		/* A server MAY optionally recurse.  The server MUST check
		 * whether it has tried this location before and whether the
		 * location is part of the Via path of the incoming request. 
		 * This check is omitted here for brevity.  Multicast locations
		 * MUST NOT be returned to the client if the server is not
		 * recursing.
         */
        if (recurse) {
          multicast = 0;
          N += r.locations;
          for (i = 0; i < r.locations; i++) {  
            request(R, r.location[i]);
          }
        } else if (!ismulticast(r.location)) {
          best = r;
        }
      }
      else if (class == 4) {
        if (best.status >= 400) best = r;
      }
      else if (class == 5) {
        if (best.status >= 500) best = r; 
      }
      else if (class == 6) {
        best = r;
        break;
      }
    }

    /* We haven't heard anything useful from anybody. */
    if (best.status == 1000) {
      best.status = 404;
    }
    if (best.status/100 != 3) loc = 0;
    response(best);
  }
\end{verbatim}

Responses are processed as follows.  The process completes (and state
can be freed) when all requests have been answered by final status
responses (for unicast) or 60 seconds have elapsed (for multicast).  A
proxy {\MAY} send a {\CANCEL} to all branches and return a 408 (Timeout)
to the client after 60 seconds or more.

\begin{description}
\item[1xx:] The proxy {\MAY} forward the response upstream towards the
client.

\item[2xx:] The proxy {\MUST} forward the response upstream towards the
client, without sending an {\ACK} downstream.  After receiving a 2xx,
the server {\MAY} terminate all other pending requests by sending a
{\CANCEL} request and closing the TCP connection, if applicable. 
(Terminating pending requests is advisable as searches consume
resources.  Also, {\INVITE} requests could ``ring'' on a number of
workstations if the callee is currently logged in more than once.)

\item[3xx:] The proxy {\MUST} send an {\ACK} and {\MAY} recurse on the
listed \header{Contact} addresses.  Otherwise, the lowest-numbered
response is returned if there were no 2xx responses. 
\motivation{Location lists are not merged as that would prevent
forwarding of authenticated responses.  Also, responses can have message
bodies, so that merging is not feasible.}

\item[4xx, 5xx:] The proxy {\MUST} send an {\ACK} and remember the
response if it has a lower status code than any previous 4xx and 5xx
responses.  On completion, the lowest-numbered response is returned if
there were no 2xx or 3xx responses.

\item[6xx:] The proxy {\MUST} forward the response to the client and
send an {\ACK}.  Other pending requests {\MAY} be terminated with
{\CANCEL} as described for 2xx responses.

\end{description}

A proxy server forwards any response for \header{Call-ID}s for which it
does not have a pending transaction according to the response's
\header{Via} header.  User agent servers respond to {\BYE} requests for
unknown call legs with status code 481 (Transaction Does Not Exist);
they drop {\ACK} requests with unknown call legs silently.

Special considerations apply for choosing forwarding destinations for
{\ACK} and {\BYE} requests.  In most cases, these requests will bypass
proxies and reach the desired party directly, keeping proxies from
having to make forwarding decisions.

A proxy {\MAY} maintain call state for a period of its choosing.  If a
proxy still has list of destinations that it forwarded the last
{\INVITE} to, it {\SHOULD} direct {\ACK} requests only to those
downstream servers. 
