9e7c0d7c97f5205add40920a98b5a65ef1039367
[sip-router] / doc / seruser / intro.sgml
1     <chapter>
2         <title>Introduction to SER</title>
3
4         <section id="requestrouting">
5             <title>Request Routing and SER Scripts</title>
6             <para>
7                 The most important concept of every SIP server is that of
8                 request routing. The request routing logic determines the next
9                 hop of a request. It can be for example used to implement user 
10                 location service or enforce static routing to a gateway. Real-world
11                 deployments actually ask for quite complex routing logic, which
12                 needs to reflect static routes to PSTN gateways, dynamic routes
13                 to registered users, authentication policy, capabilities of
14                 SIP devices, etc.
15             </para>
16             <para>
17                 SER's answer to this need for routing flexibility is a routing
18                 language, which allows administrators to define the SIP request
19                 processing logic in a detailed manner. They can for example easily
20                 split SIP traffic by method or destination, perform user location, 
21                 trigger authentication, verify access permissions, and so on.
22             </para>
23             <para>
24                 The primary building block of the routing language are <emphasis>actions</emphasis>. 
25                 There are built-in actions (like <command>forward</command> for stateless forwarding
26                 or <command>strip</command> for stripping URIs) as 
27                 well as external actions imported from shared library modules. All actions can 
28                 be combined in compound actions by enclosing them in braces, 
29                 e.g. <command>{a1(); a2();}</command>. 
30                 Actions are aggregated in one or more <emphasis>route blocks</emphasis>.
31                 Initially, only the default routing block denoted by <command>route[0]</command>
32                 is called. Other routing blocks can be called by the action
33                 <command>route(blocknumber)</command>, recursion is permitted.
34                 The language includes <emphasis>conditional statements</emphasis>. 
35             </para>
36
37             <para>
38                 The routing script is executed for every received request in sequential order. 
39                 Actions may return positive/negative/zero value. 
40
41                 Positive values are considered success and evaluated as
42                 TRUE in conditional expressions. Negative values are considered FALSE. 
43
44                 Zero value means error and leaves execution of currently processed
45                 route block. The route block is left too, if <command>break</command> is explicitly
46                 called from it.
47
48             </para>
49             <para>
50                 The easiest and still very useful way for <application>ser</application>
51                 users to affect request routing logic is
52                 to determine next hop statically. An example is
53                 routing to a PSTN gateway whose static IP address is well known.
54                 To configure static routing, simply use the action
55                 <command>forward( IP_address, port_number)</command>.
56                 This action forwards an incoming request "as is" to the
57                 destination described in action's parameters.
58             </para>
59
60             <example>
61                 <title>Static Forwarding</title>
62                 <programlisting format="linespecific">
63 # if requests URI is numerical and starts with
64 # zero, forward statelessly to a static destination
65
66 if (uri=~"^sip:0[0-9]*@iptel.org") {
67     forward( 192.168.99.3, 5080 );
68
69                 </programlisting>
70             </example>
71
72             <para>
73                 However, static forwarding is not sufficient in many cases.
74                 Users desire mobility and change their location frequently.
75                 Lowering costs for termination of calls in PSTN requires
76                 locating a least-cost gateway. Which next-hop is taken may
77                 depend on user's preferences. These and many other scenarios
78                 need the routing logic to be more dynamic. We describe in
79                 <xref linkend="conditions"> how to make request processing
80                 subject to various conditions and in 
81                 <xref linkend="urirewriting"> how to determine next SIP hop.
82             </para>
83         </section>
84
85         <section id="conditions">
86             <title>Conditional Statements</title>
87             <para>
88                 A very useful feature is the ability to make routing
89                 logic depend on a condition. A script condition may for
90                 example distinguish between request processing for
91                 served and foreign domains, IP and PSTN routes,
92                 it may split traffic by method or username, it
93                 may determine whether a request should be authenticated
94                 or not, etc. <application moreinfo="none">ser</application>
95                 allows administrators to form conditions based on
96                 properties of processed request, such as method or uri,
97                 as well as on virtually any piece of data on the
98                 Internet.
99             </para>
100             <example>
101                 <title>Conditional Statement</title>
102                 <para>
103                     This example shows how a conditional statement is
104                     used to split incoming requests between a PSTN
105                     gateway and a user location server based on
106                     request URI.
107                 </para>
108                 <programlisting format="linespecific">
109 # if request URI is numerical, forward the request to PSTN gateway...
110 if (uri=~"^sip:[0-9]+@foo.bar") { # match using a regular expression
111     forward( gateway.foo.bar, 5060 );
112 } else { # ... forward the request to user location server otherwise
113     forward( userloc.foo.bar, 5060 );
114 };
115                 </programlisting>
116             </example>
117
118             <para>
119                 Conditional statements in <application>ser</application> scripts may depend
120                 on a variety of  expressions. The simplest expressions are 
121                 action calls. They return true if they completed successfully or false otherwise. 
122                 An example of an action frequently used in conditional statements is
123                 <command moreinfo="none">search</command> imported from textops module.
124                 <command moreinfo="none">search</command> action leverages textual
125                 nature of SIP and compares SIP requests against a regular expression.
126                 The action returns true if the expression matched, false otherwise.
127                 <example>
128                     <title>Use of <command>search</command> Action in Conditional Expression</title>
129                     <programlisting format="linespecific">
130 # prevent strangers from claiming to belong to our domain;
131 # if sender claims to be in our domain in From header field,
132 # better authenticate him 
133 if (search("(f|From): .*@mydomain.com)) {
134     if (!(proxy_authorize("mydomain.com" /* realm */,"subscriber" /* table name */ ))) {
135            proxy_challenge("mydomain.com /* ream */, "1" /* use qop */ );
136            break;
137     }
138 }
139                     </programlisting>
140                 </example>
141             </para>
142             <para>
143                 As modules may be created, which export new functions, there is virtually
144                 no limitation on what functionality <application moreinfo="none">ser</application>
145                 conditions are based on. Implementers may introduce new actions whose
146                 return status depends on request content or any external data as well. Such actions
147                 can query SQL, web, local file systems or any other place which can provide
148                 information wanted for request processing.
149             </para>
150             <para>
151                 Furthermore, many request properties may be examined using existing built-in operands
152                 and operators. Available left-hand-side operands and legal combination with
153                 operators and right-hand-side operands are described in <xref linkend="logicalexpr">.
154                 Expressions may be grouped together using logical operators:
155                 negation (<command>!</command>), AND (<command>&&</command>), OR (<command moreinfo="none">
156                 ||</command> and precedence parentheses (<command>()</command>).
157             </para>
158
159             <section id="operators">
160                 <title>Operators and Operands</title>
161                 <para>
162                     There is a set of predefined operators and operands
163                     in ser, which in addition to actions may be evaluated
164                     in conditional expressions. 
165                 </para>
166                 <para>
167                     Left hand-side operands, which <application>ser</application>
168                     understands are the following:
169                     <itemizedlist>
170                         <listitem>
171                             <para>
172                                 <emphasis>method</emphasis>, which refers to 
173                                 request method
174                                 such as REGISTER or INVITE
175                             </para>
176                         </listitem>
177                         <listitem>
178                             <para>
179                                 <emphasis>uri</emphasis>, which refers to current request URI,
180                                 such as 
181                                 "sip:john.doe@foo.bar"
182                                 <note>
183                                     <para>
184                                         Note that "uri" always refers to current
185                                         value of URI, which is subject to change
186                                         be uri-rewriting actions.
187                                     </para>
188                                 </note>
189                             </para>
190                         </listitem>
191                         <listitem>
192                             <para>
193                                 <emphasis>src_ip</emphasis>, which refers to IP address from 
194                                 which a request came.
195                             </para>
196                         </listitem>
197                         <listitem>
198                             <para>
199                                 <emphasis>dst_ip</emphasis> refers to server's IP address 
200                                 at which a request was received
201                             </para>
202                         </listitem>
203                         <listitem>
204                             <para>
205                                 <emphasis>src_port</emphasis> port number from which a SIP
206                                 request came
207                             </para>
208                         </listitem>
209                     </itemizedlist>
210                 </para>
211                 <para>
212                     ser understands the following operators:
213                     <itemizedlist>
214                         <listitem>
215                             <para>
216                                 == stands for equity
217                             </para>
218                             
219                         </listitem>
220                         <listitem>
221                             <para>
222                                 =~ stands for regular expression matching
223                             </para>
224                         </listitem>
225                         <listitem>
226                             <para>
227                                 logical operators: and, or, negation, parentheses
228                                 (C-notation for the operators may be used too)
229                             </para>
230                         </listitem>
231                     </itemizedlist>
232                 </para>
233
234             <table id="logicalexpr">
235                 <title>Valid Combinations of Operands and Operators in Expressions</title>
236                 <tgroup cols="4">
237                     <thead>
238                         <row>
239                             <entry>
240                                 left-hand-side operand
241                             </entry>                        
242                             <entry>
243                                 valid operators
244                             </entry>
245                             <entry>
246                                 valid right-hand side operators
247                             </entry>
248                             <entry>
249                                 examples/comments
250                             </entry>
251                         </row>
252
253                     </thead>
254                     <tbody>
255
256                         <row>
257                             <entry>
258                                 method
259                             </entry>                        
260                             <entry>
261                                 == (exact match), =~ (regular expression matching)
262                             </entry>
263                             <entry>
264                                 string
265                             </entry>
266                             <entry>
267                                 method=="INVITE" || method=="ACK" || method=="CANCEL"
268                             </entry>
269                         </row>                  
270
271                         <row>
272                             <entry>
273                                 uri
274                             </entry>                        
275                             <entry>
276                                 == (exact match), =~ (regular expression matching)
277                             </entry>
278                             <entry>
279                                 string
280                             </entry>
281                             <entry>
282                                 uri=="sip:foo@bar.com" matches only if exactly this uri
283                                 is in request URI
284
285                             </entry>
286                         </row>                          
287
288                         <row>
289                             <entry>
290                                 
291                             </entry>                        
292                             <entry>
293                                 == (exact match)
294                             </entry>
295                             <entry>
296                                 myself
297                             </entry>
298                             <entry>
299                                 
300                                 the expression uri==myself is true if the host part in 
301                                 request URI equals a server name or a server alias (set using
302                                 the alias option in configuration file)
303                                 
304                             </entry>
305                         </row>                          
306
307                         <row>
308                             <entry>
309                                 src_ip
310                             </entry>                        
311                             <entry>
312                                 == (match)
313                             </entry>
314                             <entry>
315                                 IP, IP/mask_length, IP/mask, hostname, myself
316                             </entry>
317                             <entry>
318                                 src_ip==192.168.0.0/16 matches requests coming from
319                                 a private network
320                             </entry>
321                         </row>
322
323                         <row>
324                             <entry>
325                                 dst_ip                          
326                             </entry>                        
327                             <entry>
328                                 == (match)
329                             </entry>
330                             <entry>
331                                 IP, IP/mask_length, IP/mask, hostname, myself
332                             </entry>
333                             <entry>
334                                 dst_ip==127.0.0.1 matches if a request was received
335                                 via loopback interface
336                             </entry>
337                         </row>
338
339                         <row>
340                             <entry>
341                                     src_port
342                             </entry>                        
343                             <entry>
344                                 == (match)
345                             </entry>
346                             <entry>
347                                 port number
348                             </entry>
349                             <entry>
350                                 port number from which a request was sent, e.g. src_port==5060
351                             </entry>
352                         </row>                      
353
354
355                     </tbody>
356                 </tgroup>
357             </table>
358             
359
360                 <example>
361                     <title>
362                         More examples of use of <application>ser</application> operators and operands in conditional
363                         statements
364                     </title>
365                     <programlisting format="linespecific">
366 # using an action as condition input; in this
367 # case, an actions 'search' looks for Contacts
368 # with private IP address in requests; the condition
369 # is processed if such a contact header field is
370 # found
371
372 if (search("^(Contact|m): .*@(192\.168\.|10\.|172\.16)")) {
373 # .... 
374
375 # this condition is true if request URI matches
376 # the regular expression "@bat\.iptel\.org"
377     if (uri=~"@bat\.iptel\.org") {
378 # ...
379
380 # and this condition is true if a request came
381 # from an IP address (useful for example for
382 # authentication by IP address if digest is not
383 # supported) AND the request method is INVITE
384
385 # if ( (src_ip==192.68.77.110 and method=="INVITE")
386 # ...
387 </programlisting>
388                 </example>
389             </section> <!-- operators and operands -->
390             <section>
391                 <title>URI Matching</title>
392                 <para>URI matching expressions have a broad use in a SIP server
393                     and deserve more explanation. Typical uses of
394                     URI matching include implementation of numbering plans,
395                     domain matching,
396                     binding external applications to specific URIs,
397                     etc. This section shows examples of typical applications
398                     of URI-matching.
399                 </para>
400                 <section id="domainmatching">
401                     <title>Domain Matching</title>
402                     <para>
403                         One of most important uses of URI matching is deciding
404                         whether a request is targeted to a served or outside domain.
405                         Typically, different request
406                         processing applies. Requests for outside domains
407                         are simply forwarded to them, whereas
408                         more complex logic applies to requests for a served domain.
409                         The logic may include saving user's contacts
410                         when REGISTER requests are received, forwarding requests
411                         to current user's location or a PSTN gateways, 
412                         interaction with external applications, etc.
413                     </para>
414                     <para>
415                         The easiest way to decide whether a request belongs
416                         a served domain is using the <command moreinfo="none">myself</command>
417                         operand. 
418                         The expression "uri==myself" returns true if domain name
419                         in request URI matches name of the host at which
420                         <application moreinfo="none">ser</application> is
421                         running. This may be insufficient in cases when
422                         server name is not equal to domain name for which the server
423                         is responsible. For example, the "uri==myself" condition
424                         does not match if a server "sipserver.foo.bar" 
425                         receives a request for "sip:john.doe@foo.bar". To
426                         match other names in URI than server's own,
427                         set up the <varname>alias</varname> configuration
428                         option. The option may be used multiple times,
429                         each its use adds a new item to a list of aliases.
430                         The myself condition returns then  true 
431                         also for any hostname on the list of aliases.
432                         <example>
433                             <title>Use of uri==myself Expression</title>
434                             <programlisting format="linespecific">
435 # ser powers a domain "foo.bar" and runs at host sipserver.foo.bar;
436 # Names of served domains need to be stated in the aliases
437 # option; myself would not match them otherwise and would only
438 # match requests with "sipserver.foo.bar" in request-URI
439 alias="foo.bar"
440 alias="sales.foo.bar"
441 route[0] {
442         if (uri==myself) {
443             # the request either has server name or some of the
444             # aliases in its URI
445             log(1,"request for served domain")
446             # some domain-specific logic follows here ....
447         } else {
448             # aha -- the server is not responsible for this
449             # requests; that happens for example with the following URIs
450             #  - sip:a@marketing.foo.bar
451             #  - sip:a@otherdomain.bar
452             log(1,"request for outbound domain");
453             # outbound forwarding                         
454             t_relay();
455         };
456 }                       </programlisting>
457                     </example>
458                 </para>
459                 <para>
460                     It is possible to recognize whether a request belongs to
461                     a domain using regular expressions too. Care needs to
462                     be paid to construction of regular expressions. URI
463                     syntax is rich and an incorrect expression would result
464                     in incorrect call processing. The following example shows
465                     how an expression for domain matching can be formed.
466                     <example id="redomainmatching">
467                         <title>Domain Matching Using Regular Expressions</title>
468                         <para>
469                             In this example, server named "sip.foo.bar" with
470                             IP address 192.168.0.10 is responsible for the
471                             "foo.bar" domain. That means, requests with the
472                             following hostnames in URI should be matched:
473                             <itemizedlist>
474                                 <listitem>
475                                     <para>
476                                         foo.bar, which is the name of server domain
477                                     </para>
478                                 </listitem>
479                                 <listitem>
480                                     <para>
481                                         sip.foo.bar, since it is server's name and some
482                                         devices put server's name in request URI
483                                     </para>
484                                 </listitem>
485                                 <listitem>
486                                     <para>
487                                         192.168.0.10, since it is server's IP address and
488                                         some devices put server's IP address in request URI
489                                     </para>
490                                 </listitem>
491                             </itemizedlist>                     
492                             Note how this regular expression is constructed. In particular:
493                             <itemizedlist>
494                                 <listitem>
495                                     <para>
496                                         User name is optional (it is for example never included
497                                         in REGISTER requests) and there are no restrictions on
498                                         what characters it contains. That is what 
499                                         <emphasis>(.+@)?</emphasis> mandates. 
500                                     </para>
501                                 </listitem>
502                                 <listitem>
503                                     <para>
504                                         Hostname must be followed by port number, parameters
505                                         or headers -- that is what the delimiters 
506                                         <emphasis>[:;\?]</emphasis> are good for. If none
507                                         it these follows, the URI must be ended 
508                                         (<emphasis>$</emphasis>). Otherwise, longer hostnames
509                                         such as 192.168.0.101 or foo.bar.otherdomain.com would
510                                         mistakenly match.
511                                     </para>
512                                 </listitem>
513                                 <listitem>
514                                     <para>
515                                         Matches are case-insensitive. All hostnames "foo.bar", "FOO.BAR"
516                                         and "FoO.bAr" match.
517                                     </para>
518                                 </listitem>
519                             </itemizedlist>
520                         </para>
521                         <programlisting>
522 if (uri=~"^sip:(.+@)?(192\.168\.0\.10|(sip\.)?foo\.bar)([:;\?].*)?$")
523       log(1, "yes, it is a request for our domain");
524       break;
525  };
526                         </programlisting>
527                     </example>
528                 </para>
529                 </section> <!-- domain matching -->
530                 <section id="numberingplans">
531                     <title>Numbering Plans</title>
532
533                     <para>
534                         Other use of URI matching is implementation of dialing
535                         plans. A typical task when designing a dialing plan for SIP networks
536                         is to distinguish between "pure-IP" and PSTN destinations.
537                         IP users typically have either alphanumerical or numerical
538                         usernames. The numerical usernames are convenient for PSTN
539                         callers who can only
540                         use numeric keypads. Next-hop destination of IP users is looked up dynamically
541                         using user location database. On the other hand, PSTN destinations are 
542                         always indicated by nummerical usernames. Requests to PSTN are statically 
543                         forwarded to well-known PSTN gateways.
544                     </para>
545                     <example>
546                         <title>A simple Numbering Plan</title>
547                         <para>
548                             This example shows a simple dialing plan which reserves
549                             dialing prefix "8" for IP users, other numbers
550                             are used for PSTN destinations and all other non-nummerical
551                             usernames are used for IP users.
552                         </para>
553                         <programlisting format="linespecific">
554 # is it a PSTN destination? (is username nummerical and does not begin with 8?)
555 if (uri=~"^sip:[0-79][0-9]*@") { # ... forward to gateways then;
556       # check first to which PSTN destination the requests goes;
557       # if it is US (prefix "1"), use the gateway 192.168.0.1...
558       if (uri=~"^sip:1") {
559            # strip the leading "1"
560            strip(1);
561            forward(192.168.0.1, 5060);
562       } else {
563            # ... use the gateway 10.0.0.1 for all other destinations
564            forward(10.0.0.1, 5060);
565       }
566       break;
567 } else {
568       # it is an IP destination -- try to lookup it up in user location DB
569       if (!lookup("location")) {
570           # bad luck ... user off-line
571           sl_send_reply("404", "Not Found");
572           break;
573       }
574       # user on-line...forward to his current destination
575       forward(uri:host,uri:port);
576 }
577                         </programlisting>
578                     </example>
579                 </section> <!-- numbering plans -->
580             </section>
581         </section> <!-- conditional statements -->
582         
583         <section id="urirewriting">
584             <title>Request URI Rewriting</title>
585
586             <para>
587                 The ability to give users and services a unique name using URI
588                 is a powerful tool. It allows users to advertise how to reach
589                 them, to state to whom they wish to communicate and what services 
590                 they wish to use.
591                 Thus, the ability to change URIs is very important and is
592                 used for implementation of many services. 
593                 "Unconditional forwarding" from user "boss" to user
594                 "secretary" is a typical example of application relying
595                 on change of URI address.
596             </para>
597             <para>
598                 <application moreinfo="none">ser</application> has the ability
599                 to change request URI in many ways.
600                 A script can use any of the following
601                 built-in actions to change request URI or a part of it:
602
603                 <command>rewriteuri</command>, 
604                 <command>rewritehost</command>, 
605                 <command>rewritehostport</command>, 
606                 <command>rewriteuser</command>, 
607                 <command>rewriteuserpass</command> and 
608                 <command>rewriteport</command>. 
609                 When later in the script
610                 a forwarding action is encountered, the action forwards
611                 the request to address in the rewritten URI.
612                 <example>
613                     <title>Rewriting URIs</title>
614                     <programlisting format="linespecific">
615 if (uri=~"dan@foo.bar") {
616     rewriteuri("sip:bla@somewherelse.com")
617     # forward statelessly to the destination in current URI, i.e.,
618     # to sip:bla@somewherelese.com:5060
619     forward( uri:host, uri:port);
620 }
621                     </programlisting>
622                 </example>
623             </para>         
624             <para>Two more built-in URI-rewriting commands are of special importance
625                 for implementation of dialing plans and manipulation of dialing
626                 prefixes. <command>prefix(s)
627                 </command>, inserts 
628                 a string "s" in front of SIP address and 
629                 <command>strip(n)</command> takes
630                 away the first "n" characters of a SIP address.
631                 See <xref linkend="urirewritingexamples"> for examples of use of
632                 built-in URI-rewriting actions.
633             </para>
634
635             <para>
636                 Commands exported by external modules can change URI too
637                 and many do so.
638                 The most important application is changing URI using the
639                 user location database. The command 
640                 <command>lookup(table)</command> looks up current
641                 user's location and rewrites user's address with it.
642                 If there is no registered contact, the  command returns a negative value.
643
644
645                 <example id=rewriteuri>
646                     <title>Rewriting URIs Using User Location Database</title>
647                     <programlisting format="linespecific">
648 # store user location if a REGISTER appears
649 if (method=="REGISTER") {
650    save("mydomain1");
651 } else {
652 # try to use the previously registered contacts to
653 # determine next hop
654    if(lookup("mydomain1")) {
655      # if found, forward there...
656      t_relay();
657    } else {
658      # ... if no contact on-line, tell it upstream
659      sl_send_reply("404", "Not Found" );
660    };
661 };
662                     </programlisting>
663                 </example>
664             </para>
665             <para>
666                 External applications can be used to rewrite URI too.
667                 The "exec" module provides script actions, which start external programs
668                 and read new URI value from their output. <command moreinfo="none">exec_dset</command>
669                 both calls an external program, passes SIP request elements to it, waits until it completes,
670                 and eventually rewrites current destination set with its output.
671             </para>
672             <para>
673                 It is important to realize that <application moreinfo="none">ser</application>
674                 operates over <emphasis>current URI</emphasis> all the time. If an original
675                 URI is rewritten by a new one, the original will will be forgotten and the new one will 
676                 be used in any further processing. In particular, the uri matching operand
677                 and the user location action <command moreinfo="none">lookup</command>
678                 always take current URI as input, regardless what the original URI was.
679             </para>
680             <para>
681                 <xref linkend="urirewritingexamples"> shows how URI-rewriting actions affect 
682                 an example URI, sip:12345@foo.bar:6060.
683                 <table id="urirewritingexamples">
684                     <title>URI-rewriting Using Built-In Actions</title>
685                     <tgroup cols="2">
686                         <thead>
687                             <row>
688                                 <entry>
689                                     Example Action
690                                 </entry>                                
691                                 <entry>
692                                     Resulting URI
693                                 </entry>
694                             </row>
695                         </thead>
696                         <tbody>
697                             <row>
698                                 <entry>
699                                     <command moreinfo="none">rewritehost("192.168.0.10")</command> rewrites
700                                     the hostname in URI, other parts (including port number) remain unaffected.
701                                 </entry>
702                                 <entry>
703                                     sip:12345@192.168.10:6060
704                                 </entry>
705                             </row>
706                             <row>
707                                 <entry>
708                                     <command moreinfo="none">rewriteuri("sip:alice@foo.bar");</command> rewrites
709                                     the whole URI completely.
710                                 </entry>
711                                 <entry>
712                                     sip:alice@foo.bar
713                                 </entry>
714                             </row>
715                             <row>
716                                 <entry>
717                                     <command moreinfo="none">rewritehostport("192.168.0.10:3040")</command>rewrites 
718                                     both hostname and port number in URI.
719                                 </entry>
720                                 <entry>
721                                     sip:12345@192.168.0.10:3040
722                                 </entry>
723                             </row>
724                             <row>
725                                 <entry>
726                                     <command moreinfo="none">rewriteuser("alice")</command> rewrites user part of URI.
727                                 </entry>
728                                 <entry>
729                                     sip:alice@foo.bar:6060
730                                 </entry>
731                             </row>
732                             <row>
733                                 <entry>
734                                     <command moreinfo="none">rewriteuserpass("alice:pw")</command> replaces the pair
735                                     user:password in URI with a new value. Rewriting password in URI is of historical
736                                         meaning though, since basic password has been replaced with digest authentication.
737                                 </entry>
738                                 <entry>
739                                     sip:alice:pw@foo.bar:6060
740                                 </entry>
741                             </row>
742                             <row>
743                                 <entry>
744                                     <command moreinfo="none">rewriteport("1234")</command> replaces port number in URI
745                                 </entry>
746                                 <entry>
747                                     sip:12345@foo.bar:1234
748                                 </entry>
749                             </row>
750                             <row>
751                                 <entry>
752                                     <command moreinfo="none">prefix("9")</command> inserts a string ahead of user part of URI
753                                 </entry>
754                                 <entry>
755                                     sip:912345@foo.bar:6060
756                                 </entry>
757                             </row>
758                             <row>
759                                 <entry>
760                                     <command moreinfo="none">strip(2)</command> removes leading characters from user part of URI
761                                 </entry>
762                                 <entry>
763                                     sip:345@foo.bar:6060
764                                 </entry>
765                             </row>
766
767
768                         </tbody>
769                     </tgroup>
770                 </table>
771             </para>         
772             <para>
773                 You can verify whether you understood URI processing by
774                 looking at the following example. It rewrites URI
775                 several times. The question is what is the final URI to which
776                 the script fill forward any incoming request.
777                 <example>
778                     <title>URI-rewriting Exercise</title>
779                     <programlisting format="linespecific">
780 exec_dset("echo sip:2234@foo.bar; echo > /dev/null");
781 strip(2);
782 if (uri=~"^sip:2") {
783     prefix("0");
784 } else {
785     prefix("1");
786 };                      
787 forward(uri:host, uri:port);
788                     </programlisting>
789                 </example>
790             </para>
791             <para>
792                 The correct answer is the resulting URI will be
793                 "sip:134@foo.bar". <command moreinfo="none">exec_dset</command>
794                 rewrites original URI to "sip:2234@foo.bar", 
795                 <command moreinfo="none">strip(2)</command> takes
796                 two leading characters from username away resulting
797                 in "34@iptel.org", the condition does not match
798                 because URI does not begin with "2" any more,
799                 so the prefix "1" is inserted.
800             </para>
801
802
803         </section> <!-- URI rewriting -->
804
805         <section>
806             <title>Destination Set</title>
807             <para>
808                 Whereas needs of many scenarios can by accommodated by maintaining
809                 a single request URI, some scenarios are better served by
810                 multiple URIs. Consider for example a user with address
811                 john.doe@iptel.org. The user wishes to be reachable at his 
812                 home phone, office phone, cell phone, softphone, etc. 
813                 However, he still wishes to maintain a single public address
814                 on his business card.
815             </para>
816             <para>
817                 To enable such scenarios, <application>ser</application>
818                 allows translation of a single request URI into multiple
819                 outgoing URIs. The ability to forward a request to multiple
820                 destinations is known as <emphasis>forking</emphasis>
821                 in SIP language. All outogoing URIs (in trivial case one of them)
822                 are called <emphasis>destination set</emphasis>. The destination
823                 set always includes one default URI, to which additional URIs
824                 can be appended. Maximum size of a destination set is limited by 
825                 a compile-time constant, MAX_BRANCHES,
826                 in <filename moreinfo="none">config.h</filename>.
827             </para>
828             <para>
829                 Some actions are designed for use with a single URI whereas
830                 other actions work with the whole destination set.
831             </para>
832             <para>
833                 Actions which are currently available for creating the destination
834                 set are <command>lookup</command> from usrloc module and 
835                 <command>exec_dset</command> from exec module.
836                 <command moreinfo="none">lookup</command> fills in the destination
837                 set with user contact's registered previously with REGISTER
838                 requests. The <command moreinfo="none">exec</command> actions
839                 fill in the destination set with output of an external program.
840                 In both cases, current destination set is completely rewritten.         
841                 New URIs can be appended to destination set by a call to the built-in
842                 action <command>append_branch(uri)</command>.
843             </para>
844             <para>              
845                 Currently supported features which utilize destination sets
846                 are <emphasis>forking</emphasis> and <emphasis>redirection</emphasis>. 
847                 Action <command>t_relay</command> (TM module) for stateful
848                 forwarding supports forking. If called with a non-trivial destination
849                 set, <command moreinfo="none">t_relay</command> forks
850                 incoming request to all URIs in current destination set.
851                 See <xref linkend="rewriteuri">. If a user
852                 previously registered from three locations, the destination set is filled with 
853                 all of them by <command>lookup</command> and the <command>t_relay</command>
854                 command forwards the incoming request to all these destinations.
855                 Eventually, all user's phone will be ringing in parallel.
856             </para>
857             <para>
858                 SIP redirection is another feature which leverages destination sets.
859                 It is a very light-weighted method to establish communication
860                 between two parties with minimum burden put on the server. In
861                 <application>ser</application>, the action <command>sl_send_reply</command>
862                 (SL module) is used for this purpose. This action 
863                 allows to generate replies to SIP requests without keeping 
864                 any state. If the status code passed to the action is 3xx, 
865                 the current destination set is printed in reply's Contact header
866                 fields. Such a reply instructs the originating client to 
867                 retry at these addresses. (See <xref linkend="redirectexample">).
868             </para>
869             <para>
870                 Most other  <application>ser</application> actions ignore destination
871                 sets: they either do not relate to URI processing (<command moreinfo="none">
872                 log</command>, for example) or they work only with the default URI.
873                 All URI-rewriting functions such as
874                 <command moreinfo="none">rewriteuri</command> belong in this
875                 category. URI-comparison operands only refer to the first URI
876                 (see <xref linkend="operators">). Also, the built-in action
877                 for stateless forwarding, <command>forward</command> works only
878                 with the default URI and ignores rest of the destination set. The reason 
879                 is a proxy server willing to fork must guarantee that the burden
880                 of processing multiple replies is not put unexpectedly on upstream
881                 client. This is only achievable with stateful processing.  
882                 Forking cannot be used along with stateless <command>forward</command>,
883                 which thus only processes one URI out of the whole destination set.
884             </para> 
885
886         </section> <!-- Destination Set -->
887
888         <section>
889             <title>User Location</title>
890             <para>
891                 Mobility is a key feature of SIP. Users are able to use one
892                 one or more SIP devices and be reachable at them. Incoming requests 
893                 for users are forwarded to all user's devices in use. The key
894                 concept is that of soft-state registration. Users can
895                 -- if in possession of valid credentials -- link SIP
896                 devices to their e-mail like address of record. Their SIP devices
897                 do so using a REGISTER request, as in <xref linkend="register">.
898                 The request creates a binding between the public address of
899                 record (To header field) and SIP device's current address
900                 (Contact header field). 
901                 <example id="register">
902                     <title>REGISTER Request</title>
903                     <programlisting format="linespecific">
904 REGISTER sip:192.168.2.16 SIP/2.0
905 Via: SIP/2.0/UDP 192.168.2.16;branch=z9hG4bKd5e5.5a9947e4.0
906 Via: SIP/2.0/UDP 192.168.2.33:5060
907 From: sip:123312@192.168.2.16
908 To: sip:123312@192.168.2.16
909 Call-ID: 00036bb9-0fd30217-491b6aa6-0a7092e9@192.168.2.33
910 Date: Wed, 29 Jan 2003 18:13:15 GMT
911 CSeq: 101 REGISTER
912 User-Agent: CSCO/4
913 Contact: sip:123312@192.168.2.33:5060
914 Content-Length: 0
915 Expires: 600
916                     </programlisting>
917                 </example>
918                 Similar requests can be used to query all user's current contacts or to
919                 delete them. All Contacts have certain time to live, when the time expires,
920                 contact is removed and no longer used for processing of incoming requests.
921             </para>
922             <para>
923                 <application moreinfo="none">ser</application> is built to do both: update
924                 user location database from received REGISTER requests and look-up these
925                 contacts when inbound requests for a user arrive. To achieve high performance,
926                 the user location table is stored in memory. In regular intervals
927                 (usrloc module's parameter <varname>timer_interval</varname> determines
928                 their length), all changes to the in-memory table are backed up in
929                 <application moreinfo="none">mysql</application> database to achieve
930                 peristence accross server reboots. Administrators or application writers
931                 can lookup list of current user's contacts stored in memory using the
932                 <application moreinfo="none">serctl</application> tool (see <xref linkend="serctl">).
933                 <example>
934                     <title>Use of <application>serctl</application> Tool to Query User Location</title>
935                     <screen format="linespecific">
936 <![CDATA[
937 [jiri@fox jiri]$ sc ul show jiri
938 <sip:jiri@212.202.172.134>;q=0.00;expires=456
939 <sip:7271@gateway.foo.bar>;q=0.00;expires=36000
940 ]]>
941                     </screen>
942                 </example>
943             </para>
944             <para>
945                 Building user location in <application moreinfo="none">ser</application> scripts is
946                 quite easy. One first needs to determine whether a request is for served domain,
947                 as described in <xref linkend="domainmatching">. If that is the case, the script
948                 needs to distinguish between REGISTER requests, that update user location table,
949                 and all other requests for which next hop is determined from the table. The
950                 <command moreinfo="none">save</command> action is used to update user location
951                 (i.e., it writes to it). The <command moreinfo="none">lookup</command> actions
952                 reads from the user location table and fills in destination set with current
953                 user's contacts.
954                 <example>
955                     <title>Use of User Location Actions</title>
956                     <programlisting format="linespecific">
957 # is the request for my domain ?
958 if (uri==myself) {
959     if (method=="REGISTER") { # REGISTERs are used to update
960          save("location");
961          break; # that's it, we saved the contacts, exit now
962     } else {
963          if (!lookup("location") { # no registered contact
964             sl_send_reply("404", "Not Found");
965             break;
966          }
967          # ok -- there are some contacts for the user; forward
968          # the incoming request to all of them
969          t_relay();
970     };
971 };
972                     </programlisting>
973                 </example>
974             </para>
975             <para>
976                 Note that we used the action for stateful forwarding, 
977                 <command moreinfo="none">t_relay</command>. That's because
978                 stateful forwarding allows to fork an incoming request to
979                 multiple destinations. If we used stateless forwarding,
980                 the request would be forwarded only to one uri out of
981                 all user's contacts.
982             </para>
983         </section> <!-- User Location -->
984         
985         <section>
986             <title>External Modules</title>
987             <para>
988                 <application moreinfo="none">ser</application> provides the ability to link the server with external
989                 third-party shared libraries. Lot of functionality which is
990                 included in the <application moreinfo="none">ser</application> distribution is actually located in
991                 modules to keep the server "core" compact and clean.
992                 Among others, there are modules for checking max_forwards
993                 value in SIP requests (maxfwd), transactional processing (tm),
994                 record routing (rr), accounting (acc), authentication (auth),
995                 SMS gateway (sms), replying requests (sl), user location
996                 (usrloc, registrar) and more.
997             </para>
998             <para>
999                 In order to utilize new actions exported by a module, 
1000                 ser must first load it. To load a module, the directive
1001                 <command moreinfo="none">loadmodule "filename"</command>
1002                 must be included in beginning of
1003                 a <application>ser</application> script file.
1004             </para>
1005
1006             <example>
1007                 <title>Using Modules</title>
1008                 <para>
1009                     This example shows how a script instructs 
1010                     <application moreinfo="none">ser</application> to
1011                     load a module and use actions exported by it.
1012                     Particularly, the sl module exports an action
1013                     <command>sl_send_reply</command> which makes 
1014                     <application>ser</application> act as a stateless
1015                     user agent and reply all incoming requests with 404.
1016                 </para>
1017                 <programlisting format="linespecific">
1018 # first of all, load the module!
1019 loadmodule "/usr/lib/ser/modules/sl.so
1020 route{
1021     # reply all requests with 404
1022     sl_send_reply("404", "I am so sorry -- user not found");
1023 }
1024 </programlisting>
1025             </example>
1026             <note>
1027                 <para>Note that unlike with core commands, all actions
1028                     exported by modules must have parameters enclosed
1029                     in quotation marks in current version of 
1030                     <application moreinfo="none">ser</application>.
1031                     In the following example, the built-in action
1032                     <command moreinfo="none">forward</command> for
1033                     stateless forwarding takes
1034                     IP address and port numbers as parameters without
1035                     quotation marks whereas a module action 
1036                     <command moreinfo="none">t_relay</command> for
1037                     stateful forwarding takes parameters enclosed in
1038                     quotation marks.
1039                     <example>
1040                         <title>Parameters in built-in and exported
1041                         actions</title>
1042                         <programlisting format="linespecific">
1043 # built-in action doesn't enclose IP addresses and port numbers
1044 # in quotation marks
1045 forward(192.168.99.100, 5060);
1046 # module-exported functions enclose all parameters in quotation
1047 # marks
1048 t_relay_to_udp("192.168.99.100", "5060");
1049                         </programlisting>
1050                     </example>
1051                 </para>
1052             </note>
1053             <para>
1054                 Many modules also allow users to change the way how they
1055                 work using predefined parameters. For example, the
1056                 authentication module needs to know location of MySQL
1057                 database which contains users' security credentials.
1058                 How module parameters
1059                 are set using the <command moreinfo="none">modparam</command>
1060                 directive is shown in <xref linkend="moduleparameters">. 
1061                 <command moreinfo="none">modparam</command>
1062                 always contains identification of module, parameter
1063                 name and parameter value. Description of parameters
1064                 available in modules is available in module documentation.
1065             </para>
1066             <para>
1067                 Yet another thing to notice in this example is module
1068                 dependency. Modules may depend on each other. For example,
1069                 the authentication modules leverages the mysql module
1070                 for accessing mysql databases and sl module for generating
1071                 authentication challenges. We recommend that modules are
1072                 loaded in dependency order to avoid ambiguous server
1073                 behaviour.
1074             </para>         
1075             <para>
1076                 <example id="moduleparameters">
1077                     <title>Module Parameters</title>
1078                     <programlisting format="linespecific">
1079 # ------------------ module loading ----------------------------------
1080
1081 # load first modules on which 'auth' module depends;
1082 # sl is used for sending challenges, mysql for storage
1083 # of user credentials
1084 loadmodule "modules/sl/sl.so"
1085 loadmodule "modules/mysql/mysql.so"
1086 loadmodule "modules/auth/auth.so"
1087
1088 # ------------------ module parameters -------------------------------
1089 # tell the auth module the access data for SQL database:
1090 # username, password, hostname and database name
1091 modparam("auth", "db_url","mysql://ser:secret@dbhost/ser")
1092
1093
1094 # -------------------------  request routing logic -------------------
1095
1096 # authenticate all requests prior to forwarding them
1097
1098 route{
1099
1100         if (!proxy_authorize("foo.bar" /* realm */,
1101                         "subscriber" /* table name */ )) {
1102                 proxy_challenge("foo.bar", "0");
1103                 break;
1104         };
1105         forward(192.168.0.10,5060);
1106 }
1107
1108                     </programlisting>
1109                 </example>
1110             </para>
1111         </section>
1112
1113         <section>
1114             <title>Writing Scripts</title>
1115             <para>
1116                 This section demonstrates simple examples
1117                 how to configure server's behaviour using the
1118                 <application moreinfo="none">ser</application>
1119                 request routing language. All configuration scripts follow the 
1120                 <application moreinfo="none">ser</application> language 
1121                 syntax, which dictates the following section ordering:
1122                 <itemizedlist>
1123                     <listitem>
1124                         <para>
1125                             <emphasis>global configuration parameters</emphasis> --
1126                             these value affect behaviour of the server such as port
1127                             number at which it listens, number of spawned children
1128                             processes, and log-level. See <xref linkend="coreoptions">
1129                             for a list of available options.
1130                         </para>
1131                     </listitem>
1132
1133                     <listitem>
1134                         <para>
1135                             <emphasis>module loading</emphasis> -- these statements
1136                             link external modules, such as transaction management
1137                             (tm) or stateless UA server (sl)  dynamically. See
1138                             <xref linkend="modulereference"> for a list of modules
1139                             included in <application moreinfo="none">ser</application>
1140                             distribution.
1141                         </para>
1142                         <note>
1143                                 <para>
1144                                         If modules depend on each other, than the depending
1145                                         modules must be loaded after modules on which they
1146                                         depend. We recommend to load first modules
1147                                         <command>tm</command> and <command>sl</command>
1148                                         because many other modules (authentication, user
1149                                         location, accounting, etc.) depend on these.
1150                                 </para>
1151                         </note>
1152                     </listitem>
1153                     <listitem>
1154                         <para>
1155                             <emphasis>module-specific parameters</emphasis> -- determine
1156                             how modules behave; for example, it is possible to configure
1157                             database to be used by authentication module.
1158                         </para>
1159                     </listitem>
1160                     <listitem>
1161                         <para>
1162                             one or more <emphasis>route blocks</emphasis> containing the
1163                             request processing logic, which includes built-in actions
1164                             as well as actions exported by modules. See <xref linkend="builtinref">
1165                             for a list of built-in actions.
1166                         </para>
1167                     </listitem>
1168                     <listitem>
1169                         <para>
1170                             optionally, if modules supporting reply
1171                             processing (currently only TM) are loaded,
1172                             one or more <emphasis>failure_route blocks</emphasis> containing
1173                             logic triggered by received replies. Restrictions on use of
1174                             actions within <command moreinfo="none">failure_route</command>
1175                             blocks apply -- see <xref linkend="builtinref"> for more
1176                             information.
1177                         </para>
1178                     </listitem>
1179                 </itemizedlist>
1180             </para>
1181
1182             <section id="defaultscript">
1183                 <title>Default Configuration Script</title>             
1184                 <para>
1185                     The configuration script, <filename moreinfo="none">ser.cfg</filename>,
1186                     is a part of every <application moreinfo="none">ser</application>
1187                     distribution and defines default behaviour. It allows users
1188                     to register with the server and have requests proxied to each
1189                     other.
1190                 </para>
1191                 <para>
1192                     After performing
1193                     routine checks, the script looks whether incoming request is for
1194                     served domain. If so and the request is "REGISTER", <application moreinfo="none">ser</application>
1195                     acts as SIP registrar and updates database of user's contacts.
1196                     Optionally, it verifies user's identity first to avoid
1197                     unauthorized contact manipulation.
1198                 </para>
1199                 <para>
1200                     Non-REGISTER requests for served domains are then processed using
1201                     user location database. If a contact is found for requested URI,
1202                     script execution proceeds to stateful forwarding, a negative 404
1203                     reply is generated otherwise. Requests outside served domain
1204                     are always statefully forwarded.
1205                 </para>
1206                 <para>
1207                     Note that this simple script features several limitations:
1208                     <itemizedlist>
1209                         <listitem>                          
1210                             <para>
1211                                 By default, authentication is turned off to avoid
1212                                 dependency on mysql. Unless it it turned on, anyone
1213                                 can register using any name and "steal" someone else's
1214                                 calls.
1215                             </para>
1216                         </listitem>
1217                         <listitem>
1218                             <para>
1219                                 Even it authentication is turned on, there is no relationship
1220                                 between authentication username and address of record. That
1221                                 means that for example a user authenticating himself correctly
1222                                 with "john.doe" id may register contacts for "gw.bush".
1223                                 Site policy may wish to mandate authentication id to be equal
1224                                 to username claimed in To header field. <action moreinfo="none">check_to</action>
1225                                 action from auth module can be used to enforce such a policy.
1226                             </para>
1227                         </listitem>
1228                         <listitem>
1229                             <para>
1230                                 There is no dialing plan implemented. All users are supposed to
1231                                 be reachable via user location database. See <xref linkend="numberingplans">
1232                                 for more information.
1233                             </para>
1234                         </listitem>
1235                         <listitem>
1236                             <para>
1237                                 The script assumes users will be using server's name as a part of
1238                                 their address of record. If users wish to use another name (domain
1239                                 name for example), this must be set using the <varname>alias</varname>
1240                                 options. See <xref linkend="domainmatching"> for more information.
1241                             </para>
1242                         </listitem>
1243                         <listitem>
1244                             <para>
1245                                 If authentication is turned on by uncommenting related configuration
1246                                 options, clear-text user passwords will by assumed in back-end database.
1247                             </para>
1248                         </listitem>
1249                     </itemizedlist>
1250                 </para>
1251                 <example>
1252                     <title>Default Configuration Script</title>
1253                     <programlisting format="linespecific">
1254 &defscr;                        
1255                     </programlisting>
1256                 </example>
1257             </section>
1258
1259             <section id="statefulua">
1260                 <title>Stateful User Agent Server</title>
1261                 <para>
1262                     This examples shows how to make ser act as a stateful user
1263                     agent (UA). Ability to act as as a stateful UA is essential
1264                     to many applications which terminate a SIP path. These
1265                     applications wish to focus on their added value. They
1266                     do not wish to be involved in all SIP gory details, such
1267                     as request and reply retransmission, reply formatting, etc.
1268                     For example, we use the UA functionality to shield 
1269                     SMS gateway and instant message store from SIP transactional
1270                     processing.
1271                     The simple example bellow issues a log report on receipt
1272                     of a new transaction. 
1273                     If we did not use a stateful UA, every single request retransmission
1274                     would cause the application to be re-executed which would result in
1275                     duplicated SMS messages, instant message in message store or 
1276                     log reports.
1277                 </para>
1278                 <para>
1279                     The most important actions are <command moreinfo="none">
1280                         t_newtran</command> and <command moreinfo="none">
1281                         t_reply</command>. <command moreinfo="none">
1282                         
1283                     t_newtran</command> shields subsequent code from retransmissions.
1284                     It returns success and continues when a new request arrived.
1285                     It exits current route block immediately on receipt of
1286                     a retransmission. It only returns a negative value when
1287                     a serious error, such as lack of memory, occurs.
1288                 </para>
1289                 <para>
1290                     <command moreinfo="none">t_reply</command> generates
1291                     a reply for a request. It generates the reply statefully,
1292                     i.e., it is kept for future retransmissions in memory.
1293                 </para>
1294                 <note>
1295                         <para>
1296                                 Applications that do not need stateful processing
1297                                 may act as stateless UA Server too. They just use
1298                                 the <command>sl_send_reply</command> action to
1299                                 send replies to requests without keeping any
1300                                 state. The benefit is memory cannot run out,
1301                                 the drawback is that each retransmission needs to
1302                                 be processed as a new request. An example of use
1303                                 of a stateless server is shown in
1304                         <xref linkend="redirectserver"> and
1305                         <xref linkend="executingscript">.
1306                         </para>
1307                 </note>
1308                 <example>
1309                     <title>Stateful UA Server</title>
1310                     <programlisting format="linespecific">
1311                         <!-- ../../examples/uas.cfg -->
1312                         &statefuluaexample;
1313                     </programlisting>
1314                 </example>
1315             </section> <!-- Stateful UAS -->
1316
1317             <section id="redirectserver">
1318                 <title>Redirect Server</title>
1319                 <para>
1320                     The redirect example shows how to redirect a request
1321                     to multiple destination using 3xx reply. Redirecting
1322                     requests as opposed to proxying them is essential to
1323                     various scalability scenarios. Once a message is
1324                     redirected, <application moreinfo="none">ser</application>
1325                     discards all related state and is no more involved
1326                     in subsequent SIP transactions (unless the redirection
1327                     addresses point to the same server again).
1328                 </para>
1329                 <para>
1330                     The key <application>ser</application> actions in this example 
1331                     are <command moreinfo="none">append_branch</command> and 
1332                     <command moreinfo="none">sl_send_reply</command> (sl module).
1333                 </para>
1334                 <para>
1335                     <command moreinfo="none">append_branch</command> adds
1336                     a new item to the destination set. The destinations set always
1337                     includes the current URI and may be enhanced up to
1338                     <constant>MAX_BRANCHES</constant> items.
1339                     <command moreinfo="none">sl_send_reply</command> command, 
1340                     if passed SIP reply code 3xx, takes all values in current 
1341                     destination set and adds them to Contact header field in 
1342                     the reply being  sent.
1343                 </para>
1344                 <example id="redirectexample">
1345                     <title>Redirect Server</title>
1346                     <programlisting format="linespecific">
1347                         <!-- ../../examples/redirect.cfg -->
1348                         &redirectexample;
1349                     </programlisting>
1350                 </example>
1351             </section> <!-- redirect server-->
1352             
1353             <section id="executingscript">
1354                 <title>Executing External Script</title>
1355                 <para>
1356                     Like in the previous example, we show how to
1357                     make <application>ser</application> act as a redirect server. The difference is 
1358                     that we do not use redirection addresses hardwired in
1359                     <application moreinfo="none">ser</application> script but
1360                     get them from external shell commands. We also use
1361                     ser's ability to execute shell commands to log
1362                     source IP address of incoming SIP requests.
1363                 </para>
1364                 <para>
1365                     The new commands introduced in this example are
1366                     <command moreinfo="none">exec_msg</command> and
1367                     <command moreinfo="none">exec_dset</command>.
1368                     <command moreinfo="none">exec_msg</command> takes
1369                     current requests, starts an external command, and
1370                     passes the requests to the command's standard input.
1371                     It also passes request's source IP address in
1372                     environment variable named <constant>SRCIP</constant>.
1373                 </para>
1374                 <para>
1375                     <command moreinfo="none">exec_dset</command> serves
1376                     for URI rewriting by external applications.  The
1377                     <command moreinfo="none">exec_dset</command> action
1378                     passes current URI to the called external program, 
1379                     and rewrites current destination
1380                     set with the program's output. An example use would
1381                     be an implementation of a Least-Cost-Router, software which
1382                     returns URI of the cheapest PSTN provider for a given
1383                     destination based on some pricing tables. <xref linkend="execscript">
1384                     is much easier: it prints fixed URIs on its output using
1385                     shell script <command moreinfo="none">echo</command> command.
1386                 </para>
1387                 <note>
1388                         <para>
1389                                 This script works statelessly -- it uses this action for
1390                                 stateless replying, <command>sl_send_reply</command>.
1391                                 No transaction is kept in memory and each request retransmission
1392                                 is processed as a brand-new request. That may be a particular
1393                                 concern if the server logic (<command>exec</command> actions
1394                                 in this example) is too expensive. See 
1395                         <xref linkend="statefulua"> for instructions on how
1396                                 to make server logic stateful, so that retransmissions
1397                                 are absorbed and do not cause re-execution of the logic.
1398                         
1399                         </para>
1400                 </note>
1401                 <example id="execscript">
1402                     <title>Executing External Script</title>
1403                     <programlisting format="linespecific">
1404                         <!-- ../../examples/exec.cfg -->
1405                         &execexample;
1406                     </programlisting>
1407                 </example>
1408             </section> <!-- exec example -->
1409             
1410             <section id="replyprocessingsection">
1411                 <title>On-Reply Processing (Forward on Unavailable)</title>
1412                 <para>
1413                     Many services depend on status of messages relayed
1414                     downstream: <emphasis>forward on busy</emphasis> and 
1415                     <emphasis>forward on no reply</emphasis> to name the
1416                     most well-known ones. To support implementation of
1417                     such services, <application moreinfo="none">ser</application>
1418                     allows to return to request processing when request
1419                     forwarding failed. When a request is reprocessed,
1420                     new request branches may be initiated or the transaction
1421                     can be completed at discretion of script writer.
1422                 </para>
1423                 <para>
1424                     The primitives used are <command moreinfo="none">t_on_failure(r)</command>
1425                     and <command moreinfo="none">failure_route[r]{}.</command> If
1426                     <command>t_on_failure</command> is called before
1427                     a request is statefuly forwarded and a forwarding failure occurs, 
1428                     <application moreinfo="none">ser</application>
1429                     will return to request processing in a <command moreinfo="none">failure_route</command>
1430                     block. Failures include receipt of a SIP error
1431                     (status code >= 300 ) from downstream or not receiving
1432                     any final reply within final response period.
1433                 </para>
1434                 <para>
1435                     The length of the timer is governed by parameters of the
1436                     tm module. <varname>fr_timer</varname> is the length of
1437                     timer set for non-INVITE transactions and INVITE transactions
1438                     for which no provisional response is received. If a timer
1439                     hits, it indicates that a downstream server is unresponsive.
1440                     <varname>fr_inv_timer</varname> governs time to wait for 
1441                     a final reply for an INVITE. It is typically longer than
1442                     <varname>fr_timer</varname> because final reply may take
1443                     long time until callee (finds a mobile phone in a pocket and)
1444                     answers the call.
1445                 </para>
1446                 <para>
1447                     In <xref linkend="replyprocessing">, <command moreinfo="none">failure_route[1]</command>
1448                     is set to be entered on error using the <command moreinfo="none">t_on_failure(1)</command>
1449                     action. Within this reply block, <application moreinfo="none">ser</application>
1450                     is instructed to initiate a new branch and try to reach called party
1451                     at another destination (sip:nonsense@iptel.org). To deal with the case when neither the alternate
1452                     destination succeeds, <application moreinfo="none">t_on_failure</application>
1453                     is set again. If the case really occurs, <command moreinfo="none">failure_route[2]</command>
1454                     is entered and a last resort destination (sip:foo@iptel.org) is tried.
1455                 </para>
1456                 <example id="replyprocessing">
1457                     <title>On-Reply Processing</title>
1458                     <programlisting format="linespecific">
1459                         <!-- ../../examples/onr.cfg -->
1460                         &replyexample;
1461                     </programlisting>
1462
1463                 </example>
1464             </section> <!-- reply processing -->
1465         </section> <!-- examples -->
1466     </chapter>