Merged revisions 194484 via svnmerge from
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Implementation of Session Initiation Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  *
28  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29  * Configuration file \link Config_sip sip.conf \endlink
30  *
31  * ********** IMPORTANT *
32  * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33  *      settings, dialplan commands and dialplans apps/functions
34  * See \ref sip_tcp_tls
35  * 
36  *
37  * ******** General TODO:s
38  * \todo Better support of forking
39  * \todo VIA branch tag transaction checking
40  * \todo Transaction support
41  * \todo Asterisk should send a non-100 provisional response every minute to keep proxies
42  *  from cancelling the transaction (RFC 3261 13.3.1.1). See bug #11157.
43  * 
44  * ******** Wishlist: Improvements
45  * - Support of SIP domains for devices, so that we match on username@domain in the From: header
46  * - Connect registrations with a specific device on the incoming call. It's not done
47  *   automatically in Asterisk
48  *
49  * \ingroup channel_drivers
50  *
51  * \par Overview of the handling of SIP sessions
52  * The SIP channel handles several types of SIP sessions, or dialogs,
53  * not all of them being "telephone calls".
54  * - Incoming calls that will be sent to the PBX core
55  * - Outgoing calls, generated by the PBX
56  * - SIP subscriptions and notifications of states and voicemail messages
57  * - SIP registrations, both inbound and outbound
58  * - SIP peer management (peerpoke, OPTIONS)
59  * - SIP text messages
60  *
61  * In the SIP channel, there's a list of active SIP dialogs, which includes
62  * all of these when they are active. "sip show channels" in the CLI will
63  * show most of these, excluding subscriptions which are shown by
64  * "sip show subscriptions"
65  *
66  * \par incoming packets
67  * Incoming packets are received in the monitoring thread, then handled by
68  * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
69  * sipsock_read() function parses the packet and matches an existing
70  * dialog or starts a new SIP dialog.
71  * 
72  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
73  * If it is a response to an outbound request, the packet is sent to handle_response().
74  * If it is a request, handle_incoming() sends it to one of a list of functions
75  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
76  * sipsock_read locks the ast_channel if it exists (an active call) and
77  * unlocks it after we have processed the SIP message.
78  *
79  * A new INVITE is sent to handle_request_invite(), that will end up
80  * starting a new channel in the PBX, the new channel after that executing
81  * in a separate channel thread. This is an incoming "call".
82  * When the call is answered, either by a bridged channel or the PBX itself
83  * the sip_answer() function is called.
84  *
85  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
86  * in rtp.c 
87  * 
88  * \par Outbound calls
89  * Outbound calls are set up by the PBX through the sip_request_call()
90  * function. After that, they are activated by sip_call().
91  * 
92  * \par Hanging up
93  * The PBX issues a hangup on both incoming and outgoing calls through
94  * the sip_hangup() function
95  */
96
97 /*!  
98  * \page sip_tcp_tls SIP TCP and TLS support
99  * 
100  * \par tcpfixes TCP implementation changes needed
101  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
102  * \todo Save TCP/TLS sessions in registry
103  *      If someone registers a SIPS uri, this forces us to set up a TLS connection back.
104  * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
105  * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
106  *       The tcpbindaddr config option should only be used to open ADDITIONAL ports
107  *       So we should propably go back to
108  *              bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
109  *                              if tlsenable=yes, open TLS port (provided we also have cert)
110  *              tcpbindaddr = extra address for additional TCP connections
111  *              tlsbindaddr = extra address for additional TCP/TLS connections
112  *              udpbindaddr = extra address for additional UDP connections
113  *                      These three options should take multiple IP/port pairs
114  *      Note: Since opening additional listen sockets is a *new* feature we do not have today
115  *              the XXXbindaddr options needs to be disabled until we have support for it
116  *              
117  * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
118  *      thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
119  *      even if udp is the configured first transport.
120  *      
121  * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
122  *       specially to communication with other peers (proxies).
123  * \todo We need to test TCP sessions with SIP proxies and in regards
124  *       to the SIP outbound specs.
125  * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
126  *
127  * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
128  *       message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
129  * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
130  *       multiple domains in our TLS implementation, meaning one socket and one cert per domain
131  * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
132  *       also considering outbound proxy options.
133  *              First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
134  *              Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
135  *      DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
136  *      Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
137  * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
138  *      devices directly from the dialplan. UDP is only a fallback if no other method works,
139  *      in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
140  *      MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
141  *
142  *      When dialling unconfigured peers (with no port number)  or devices in external domains
143  *      NAPTR records MUST be consulted to find configured transport. If they are not found,
144  *      SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
145  *      If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
146  *      \note this only applies if there's no outbound proxy configured for the session. If an outbound
147  *      proxy is configured, these procedures might apply for locating the proxy and determining
148  *      the transport to use for communication with the proxy.
149  * \par Other bugs to fix ----
150  * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
151  *      - sets TLS port as default for all TCP connections, unless other port is given in contact.
152  * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
153  *      - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is 
154  *        a bad guess.
155  *      - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
156  * get_destination(struct sip_pvt *p, struct sip_request *oreq)
157  *      - Doesn't store the information that we got an incoming SIPS request in the channel, so that
158  *        we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
159  *        fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
160  *        channel variable in the dialplan.
161  * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
162  *      - As above, if we have a SIPS: uri in the refer-to header
163  *      - Does not check transport in refer_to uri.
164  */
165
166 /*** MODULEINFO
167         <depend>chan_local</depend>
168  ***/
169
170 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
171
172         The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
173         refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
174         request at a negotiated interval. If a session refresh fails then all the entities that support Session-
175         Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
176         the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
177         that do not support Session-Timers).
178
179         The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
180         per-peer settings override the global settings. The following new parameters have been
181         added to the sip.conf file.
182                 session-timers=["accept", "originate", "refuse"]
183                 session-expires=[integer]
184                 session-minse=[integer]
185                 session-refresher=["uas", "uac"]
186
187         The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
188         Asterisk. The Asterisk can be configured in one of the following three modes:
189
190         1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
191                 made by remote end-points. A remote end-point can request Asterisk to engage
192                 session-timers by either sending it an INVITE request with a "Supported: timer"
193                 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
194                 Session-Expires: header in it. In this mode, the Asterisk server does not 
195                 request session-timers from remote end-points. This is the default mode.
196         2. Originate :: In the "originate" mode, the Asterisk server requests the remote 
197                 end-points to activate session-timers in addition to honoring such requests
198                 made by the remote end-pints. In order to get as much protection as possible
199                 against hanging SIP channels due to network or end-point failures, Asterisk
200                 resends periodic re-INVITEs even if a remote end-point does not support
201                 the session-timers feature.
202         3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
203                 timers for inbound or outbound requests. If a remote end-point requests
204                 session-timers in a dialog, then Asterisk ignores that request unless it's
205                 noted as a requirement (Require: header), in which case the INVITE is 
206                 rejected with a 420 Bad Extension response.
207
208 */
209
210 #include "asterisk.h"
211
212 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
213
214 #include <ctype.h>
215 #include <sys/ioctl.h>
216 #include <fcntl.h>
217 #include <signal.h>
218 #include <sys/signal.h>
219 #include <regex.h>
220 #include <time.h>
221
222 #include "asterisk/network.h"
223 #include "asterisk/paths.h"     /* need ast_config_AST_SYSTEM_NAME */
224
225 #include "asterisk/lock.h"
226 #include "asterisk/channel.h"
227 #include "asterisk/config.h"
228 #include "asterisk/module.h"
229 #include "asterisk/pbx.h"
230 #include "asterisk/sched.h"
231 #include "asterisk/io.h"
232 #include "asterisk/rtp_engine.h"
233 #include "asterisk/udptl.h"
234 #include "asterisk/acl.h"
235 #include "asterisk/manager.h"
236 #include "asterisk/callerid.h"
237 #include "asterisk/cli.h"
238 #include "asterisk/app.h"
239 #include "asterisk/musiconhold.h"
240 #include "asterisk/dsp.h"
241 #include "asterisk/features.h"
242 #include "asterisk/srv.h"
243 #include "asterisk/astdb.h"
244 #include "asterisk/causes.h"
245 #include "asterisk/utils.h"
246 #include "asterisk/file.h"
247 #include "asterisk/astobj.h"
248 /* 
249    Uncomment the define below,  if you are having refcount related memory leaks.
250    With this uncommented, this module will generate a file, /tmp/refs, which contains
251    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
252    be modified to ao2_t_* calls, and include a tag describing what is happening with 
253    enough detail, to make pairing up a reference count increment with its corresponding decrement.
254    The refcounter program in utils/ can be invaluable in highlighting objects that are not
255    balanced, along with the complete history for that object.
256    In normal operation, the macros defined will throw away the tags, so they do not 
257    affect the speed of the program at all. They can be considered to be documentation.
258 */
259 /* #define  REF_DEBUG 1 */
260 #include "asterisk/astobj2.h"
261 #include "asterisk/dnsmgr.h"
262 #include "asterisk/devicestate.h"
263 #include "asterisk/linkedlists.h"
264 #include "asterisk/stringfields.h"
265 #include "asterisk/monitor.h"
266 #include "asterisk/netsock.h"
267 #include "asterisk/localtime.h"
268 #include "asterisk/abstract_jb.h"
269 #include "asterisk/threadstorage.h"
270 #include "asterisk/translate.h"
271 #include "asterisk/ast_version.h"
272 #include "asterisk/event.h"
273 #include "asterisk/tcptls.h"
274 #include "asterisk/stun.h"
275
276 /*** DOCUMENTATION
277         <application name="SIPDtmfMode" language="en_US">
278                 <synopsis>
279                         Change the dtmfmode for a SIP call.
280                 </synopsis>
281                 <syntax>
282                         <parameter name="mode" required="true">
283                                 <enumlist>
284                                         <enum name="inband" />
285                                         <enum name="info" />
286                                         <enum name="rfc2833" />
287                                 </enumlist>
288                         </parameter>
289                 </syntax>
290                 <description>
291                         <para>Changes the dtmfmode for a SIP call.</para>
292                 </description>
293         </application>
294         <application name="SIPAddHeader" language="en_US">
295                 <synopsis>
296                         Add a SIP header to the outbound call.
297                 </synopsis>
298                 <syntax argsep=":">
299                         <parameter name="Header" required="true" />
300                         <parameter name="Content" required="true" />
301                 </syntax>
302                 <description>
303                         <para>Adds a header to a SIP call placed with DIAL.</para>
304                         <para>Remember to use the X-header if you are adding non-standard SIP
305                         headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
306                         Adding the wrong headers may jeopardize the SIP dialog.</para>
307                         <para>Always returns <literal>0</literal>.</para>
308                 </description>
309         </application>
310         <application name="SIPRemoveHeader" language="en_US">
311                 <synopsis>
312                         Remove SIP headers previously added with SIPAddHeader
313                 </synopsis>
314                 <syntax>
315                         <parameter name="Header" required="false" />
316                 </syntax>
317                 <description>
318                         <para>SIPRemoveHeader() allows you to remove headers which were previously 
319                         added with SIPAddHeader(). If no parameter is supplied, all previously added 
320                         headers will be removed. If a parameter is supplied, only the matching headers 
321                         will be removed.</para>
322                         <para>For example you have added these 2 headers:</para>
323                         <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
324                         <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
325                         <para></para>
326                         <para>// remove all headers</para>
327                         <para>SIPRemoveHeader();</para>
328                         <para>// remove all P- headers</para>
329                         <para>SIPRemoveHeader(P-);</para>
330                         <para>// remove only the PAI header (note the : at the end)</para>
331                         <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
332                         <para></para>
333                         <para>Always returns <literal>0</literal>.</para>
334                 </description>
335         </application>
336         <function name="SIP_HEADER" language="en_US">
337                 <synopsis>
338                         Gets the specified SIP header.
339                 </synopsis>
340                 <syntax>
341                         <parameter name="name" required="true" />
342                         <parameter name="number">
343                                 <para>If not specified, defaults to <literal>1</literal>.</para>
344                         </parameter>
345                 </syntax>
346                 <description>
347                         <para>Since there are several headers (such as Via) which can occur multiple
348                         times, SIP_HEADER takes an optional second argument to specify which header with
349                         that name to retrieve. Headers start at offset <literal>1</literal>.</para>
350                 </description>
351         </function>
352         <function name="SIPPEER" language="en_US">
353                 <synopsis>
354                         Gets SIP peer information.
355                 </synopsis>
356                 <syntax>
357                         <parameter name="peername" required="true" />
358                         <parameter name="item">
359                                 <enumlist>
360                                         <enum name="ip">
361                                                 <para>(default) The ip address.</para>
362                                         </enum>
363                                         <enum name="port">
364                                                 <para>The port number.</para>
365                                         </enum>
366                                         <enum name="mailbox">
367                                                 <para>The configured mailbox.</para>
368                                         </enum>
369                                         <enum name="context">
370                                                 <para>The configured context.</para>
371                                         </enum>
372                                         <enum name="expire">
373                                                 <para>The epoch time of the next expire.</para>
374                                         </enum>
375                                         <enum name="dynamic">
376                                                 <para>Is it dynamic? (yes/no).</para>
377                                         </enum>
378                                         <enum name="callerid_name">
379                                                 <para>The configured Caller ID name.</para>
380                                         </enum>
381                                         <enum name="callerid_num">
382                                                 <para>The configured Caller ID number.</para>
383                                         </enum>
384                                         <enum name="callgroup">
385                                                 <para>The configured Callgroup.</para>
386                                         </enum>
387                                         <enum name="pickupgroup">
388                                                 <para>The configured Pickupgroup.</para>
389                                         </enum>
390                                         <enum name="codecs">
391                                                 <para>The configured codecs.</para>
392                                         </enum>
393                                         <enum name="status">
394                                                 <para>Status (if qualify=yes).</para>
395                                         </enum>
396                                         <enum name="regexten">
397                                                 <para>Registration extension.</para>
398                                         </enum>
399                                         <enum name="limit">
400                                                 <para>Call limit (call-limit).</para>
401                                         </enum>
402                                         <enum name="busylevel">
403                                                 <para>Configured call level for signalling busy.</para>
404                                         </enum>
405                                         <enum name="curcalls">
406                                                 <para>Current amount of calls. Only available if call-limit is set.</para>
407                                         </enum>
408                                         <enum name="language">
409                                                 <para>Default language for peer.</para>
410                                         </enum>
411                                         <enum name="accountcode">
412                                                 <para>Account code for this peer.</para>
413                                         </enum>
414                                         <enum name="useragent">
415                                                 <para>Current user agent id for peer.</para>
416                                         </enum>
417                                         <enum name="chanvar[name]">
418                                                 <para>A channel variable configured with setvar for this peer.</para>
419                                         </enum>
420                                         <enum name="codec[x]">
421                                                 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
422                                         </enum>
423                                 </enumlist>
424                         </parameter>
425                 </syntax>
426                 <description />
427         </function>
428         <function name="SIPCHANINFO" language="en_US">
429                 <synopsis>
430                         Gets the specified SIP parameter from the current channel.
431                 </synopsis>
432                 <syntax>
433                         <parameter name="item" required="true">
434                                 <enumlist>
435                                         <enum name="peerip">
436                                                 <para>The IP address of the peer.</para>
437                                         </enum>
438                                         <enum name="recvip">
439                                                 <para>The source IP address of the peer.</para>
440                                         </enum>
441                                         <enum name="from">
442                                                 <para>The URI from the <literal>From:</literal> header.</para>
443                                         </enum>
444                                         <enum name="uri">
445                                                 <para>The URI from the <literal>Contact:</literal> header.</para>
446                                         </enum>
447                                         <enum name="useragent">
448                                                 <para>The useragent.</para>
449                                         </enum>
450                                         <enum name="peername">
451                                                 <para>The name of the peer.</para>
452                                         </enum>
453                                         <enum name="t38passthrough">
454                                                 <para><literal>1</literal> if T38 is offered or enabled in this channel,
455                                                 otherwise <literal>0</literal>.</para>
456                                         </enum>
457                                 </enumlist>
458                         </parameter>
459                 </syntax>
460                 <description />
461         </function>
462         <function name="CHECKSIPDOMAIN" language="en_US">
463                 <synopsis>
464                         Checks if domain is a local domain.
465                 </synopsis>
466                 <syntax>
467                         <parameter name="domain" required="true" />
468                 </syntax>
469                 <description>
470                         <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
471                         as a local SIP domain that this Asterisk server is configured to handle.
472                         Returns the domain name if it is locally handled, otherwise an empty string.
473                         Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
474                 </description>
475         </function>
476  ***/
477
478 #ifndef FALSE
479 #define FALSE    0
480 #endif
481
482 #ifndef TRUE
483 #define TRUE     1
484 #endif
485
486 #ifndef MAX
487 #define MAX(a,b) ((a) > (b) ? (a) : (b))
488 #endif
489
490 /* Arguments for find_peer */
491 #define FINDUSERS (1 << 0)
492 #define FINDPEERS (1 << 1)
493 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
494
495 #define SIPBUFSIZE              512             /*!< Buffer size for many operations */
496
497 #define XMIT_ERROR              -2
498
499 #define SIP_RESERVED ";/?:@&=+$,# "             /*!< Reserved characters in the username part of the URI */
500
501 /* #define VOCAL_DATA_HACK */
502
503 #define DEFAULT_DEFAULT_EXPIRY  120
504 #define DEFAULT_MIN_EXPIRY      60
505 #define DEFAULT_MAX_EXPIRY      3600
506 #define DEFAULT_MWI_EXPIRY      3600
507 #define DEFAULT_REGISTRATION_TIMEOUT 20
508 #define DEFAULT_MAX_FORWARDS    "70"
509
510 /* guard limit must be larger than guard secs */
511 /* guard min must be < 1000, and should be >= 250 */
512 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
513 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
514                                                          EXPIRY_GUARD_SECS */
515 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
516                                                    GUARD_PCT turns out to be lower than this, it 
517                                                    will use this time instead.
518                                                    This is in milliseconds. */
519 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
520                                                     below EXPIRY_GUARD_LIMIT */
521 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
522
523 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
524 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
525 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
526 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
527
528 #define DEFAULT_QUALIFY_GAP   100
529 #define DEFAULT_QUALIFY_PEERS 1
530
531
532 #define CALLERID_UNKNOWN        "Unknown"
533
534 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
535 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
536 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
537
538 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
539 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
540 #define DEFAULT_TIMER_T1                 500              /*!< SIP timer T1 (according to RFC 3261) */
541 #define SIP_TRANS_TIMEOUT            64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1 
542                                                       \todo Use known T1 for timeout (peerpoke)
543                                                       */
544 #define DEFAULT_TRANS_TIMEOUT        -1               /*!< Use default SIP transaction timeout */
545 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
546
547 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
548 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
549 #define SIP_MIN_PACKET               4096             /*!< Initialize size of memory to allocate for packets */
550 #define MAX_HISTORY_ENTRIES          50               /*!< Max entires in the history list for a sip_pvt */
551
552 #define INITIAL_CSEQ                 101              /*!< Our initial sip sequence number */
553
554 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
555 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
556
557 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
558
559 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
560 static struct ast_jb_conf default_jbconf =
561 {
562         .flags = 0,
563         .max_size = -1,
564         .resync_threshold = -1,
565         .impl = ""
566 };
567 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
568
569 static const char config[] = "sip.conf";                /*!< Main configuration file */
570 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
571
572 #define RTP     1
573 #define NO_RTP  0
574
575 /*! \brief Authorization scheme for call transfers 
576
577 \note Not a bitfield flag, since there are plans for other modes,
578         like "only allow transfers for authenticated devices" */
579 enum transfermodes {
580         TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
581         TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
582 };
583
584
585 /*! \brief The result of a lot of functions */
586 enum sip_result {
587         AST_SUCCESS = 0,                /*!< FALSE means success, funny enough */
588         AST_FAILURE = -1,               /*!< Failure code */
589 };
590
591 /*! \brief States for the INVITE transaction, not the dialog 
592         \note this is for the INVITE that sets up the dialog
593 */
594 enum invitestates {
595         INV_NONE = 0,           /*!< No state at all, maybe not an INVITE dialog */
596         INV_CALLING = 1,        /*!< Invite sent, no answer */
597         INV_PROCEEDING = 2,     /*!< We got/sent 1xx message */
598         INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
599         INV_COMPLETED = 4,      /*!< Got final response with error. Wait for ACK, then CONFIRMED */
600         INV_CONFIRMED = 5,      /*!< Confirmed response - we've got an ack (Incoming calls only) */
601         INV_TERMINATED = 6,     /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
602                                      The only way out of this is a BYE from one side */
603         INV_CANCELLED = 7,      /*!< Transaction cancelled by client or server in non-terminated state */
604 };
605
606 /*! \brief Readable descriptions of device states.
607        \note Should be aligned to above table as index */
608 static const struct invstate2stringtable {
609         const enum invitestates state;
610         const char *desc;
611 } invitestate2string[] = {
612         {INV_NONE,              "None"  },
613         {INV_CALLING,           "Calling (Trying)"},
614         {INV_PROCEEDING,        "Proceeding "},
615         {INV_EARLY_MEDIA,       "Early media"},
616         {INV_COMPLETED,         "Completed (done)"},
617         {INV_CONFIRMED,         "Confirmed (up)"},
618         {INV_TERMINATED,        "Done"},
619         {INV_CANCELLED,         "Cancelled"}
620 };
621
622 /*! \brief When sending a SIP message, we can send with a few options, depending on
623         type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
624         where the original response would be sent RELIABLE in an INVITE transaction */
625 enum xmittype {
626         XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
627                                               If it fails, it's critical and will cause a teardown of the session */
628         XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
629         XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
630 };
631
632 /*! \brief Results from the parse_register() function */
633 enum parse_register_result {
634         PARSE_REGISTER_FAILED,
635         PARSE_REGISTER_UPDATE,
636         PARSE_REGISTER_QUERY,
637 };
638
639 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
640 enum subscriptiontype { 
641         NONE = 0,
642         XPIDF_XML,
643         DIALOG_INFO_XML,
644         CPIM_PIDF_XML,
645         PIDF_XML,
646         MWI_NOTIFICATION
647 };
648
649 /*! \brief Subscription types that we support. We support
650    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
651    - SIMPLE presence used for device status
652    - Voicemail notification subscriptions
653 */
654 static const struct cfsubscription_types {
655         enum subscriptiontype type;
656         const char * const event;
657         const char * const mediatype;
658         const char * const text;
659 } subscription_types[] = {
660         { NONE,            "-",        "unknown",                    "unknown" },
661         /* RFC 4235: SIP Dialog event package */
662         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
663         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
664         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
665         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
666         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
667 };
668
669
670 /*! \brief Authentication types - proxy or www authentication 
671         \note Endpoints, like Asterisk, should always use WWW authentication to
672         allow multiple authentications in the same call - to the proxy and
673         to the end point.
674 */
675 enum sip_auth_type {
676         PROXY_AUTH = 407,
677         WWW_AUTH = 401,
678 };
679
680 /*! \brief Authentication result from check_auth* functions */
681 enum check_auth_result {
682         AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
683                 /* XXX maybe this is the same as AUTH_NOT_FOUND */
684
685         AUTH_SUCCESSFUL = 0,
686         AUTH_CHALLENGE_SENT = 1,
687         AUTH_SECRET_FAILED = -1,
688         AUTH_USERNAME_MISMATCH = -2,
689         AUTH_NOT_FOUND = -3,    /*!< returned by register_verify */
690         AUTH_FAKE_AUTH = -4,
691         AUTH_UNKNOWN_DOMAIN = -5,
692         AUTH_PEER_NOT_DYNAMIC = -6,
693         AUTH_ACL_FAILED = -7,
694         AUTH_BAD_TRANSPORT = -8,
695         AUTH_RTP_FAILED = 9,
696 };
697
698 /*! \brief States for outbound registrations (with register= lines in sip.conf */
699 enum sipregistrystate {
700         REG_STATE_UNREGISTERED = 0,     /*!< We are not registered 
701                  *  \note Initial state. We should have a timeout scheduled for the initial
702                  * (or next) registration transmission, calling sip_reregister
703                  */
704
705         REG_STATE_REGSENT,      /*!< Registration request sent 
706                  * \note sent initial request, waiting for an ack or a timeout to
707                  * retransmit the initial request.
708                 */
709
710         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate 
711                  * \note entered after transmit_register with auth info,
712                  * waiting for an ack.
713                  */
714
715         REG_STATE_REGISTERED,   /*!< Registered and done */
716
717         REG_STATE_REJECTED,     /*!< Registration rejected *
718                  * \note only used when the remote party has an expire larger than
719                  * our max-expire. This is a final state from which we do not
720                  * recover (not sure how correctly).
721                  */
722
723         REG_STATE_TIMEOUT,      /*!< Registration timed out *
724                 * \note XXX unused */
725
726         REG_STATE_NOAUTH,       /*!< We have no accepted credentials
727                  * \note fatal - no chance to proceed */
728
729         REG_STATE_FAILED,       /*!< Registration failed after several tries
730                  * \note fatal - no chance to proceed */
731 };
732
733 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
734 enum st_mode {
735         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
736         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
737         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
738         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
739 };
740
741 /*! \brief The entity playing the refresher role for Session-Timers */
742 enum st_refresher {
743         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
744         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
745         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
746 };
747
748 /*! \brief Define some implemented SIP transports 
749         \note Asterisk does not support SCTP or UDP/DTLS 
750 */
751 enum sip_transport {
752         SIP_TRANSPORT_UDP = 1,          /*!< Unreliable transport for SIP, needs retransmissions */
753         SIP_TRANSPORT_TCP = 1 << 1,     /*!< Reliable, but unsecure */
754         SIP_TRANSPORT_TLS = 1 << 2,     /*!< TCP/TLS - reliable and secure transport for signalling */
755 };
756
757 /*! \brief definition of a sip proxy server
758  *
759  * For outbound proxies, a sip_peer will contain a reference to a 
760  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
761  * contain a reference to a peer's outboundproxy, or it may contain
762  * a reference to the sip_cfg.outboundproxy.
763  */
764 struct sip_proxy {
765         char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
766         struct sockaddr_in ip;          /*!< Currently used IP address and port */
767         time_t last_dnsupdate;          /*!< When this was resolved */
768         enum sip_transport transport;   
769         int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
770         /* Room for a SRV record chain based on the name */
771 };
772
773 /*! \brief argument for the 'show channels|subscriptions' callback. */
774 struct __show_chan_arg { 
775         int fd;
776         int subscriptions;
777         int numchans;   /* return value */
778 };
779
780
781 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
782 enum can_create_dialog {
783         CAN_NOT_CREATE_DIALOG,
784         CAN_CREATE_DIALOG,
785         CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
786 };
787
788 /*! \brief SIP Request methods known by Asterisk 
789
790    \note Do _NOT_ make any changes to this enum, or the array following it;
791    if you think you are doing the right thing, you are probably
792    not doing the right thing. If you think there are changes
793    needed, get someone else to review them first _before_
794    submitting a patch. If these two lists do not match properly
795    bad things will happen.
796 */
797
798 enum sipmethod {
799         SIP_UNKNOWN,            /*!< Unknown response */
800         SIP_RESPONSE,           /*!< Not request, response to outbound request */
801         SIP_REGISTER,           /*!< Registration to the mothership, tell us where you are located */
802         SIP_OPTIONS,            /*!< Check capabilities of a device, used for "ping" too */
803         SIP_NOTIFY,             /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
804         SIP_INVITE,             /*!< Set up a session */
805         SIP_ACK,                /*!< End of a three-way handshake started with INVITE. */
806         SIP_PRACK,              /*!< Reliable pre-call signalling. Not supported in Asterisk. */
807         SIP_BYE,                /*!< End of a session */
808         SIP_REFER,              /*!< Refer to another URI (transfer) */
809         SIP_SUBSCRIBE,          /*!< Subscribe for updates (voicemail, session status, device status, presence) */
810         SIP_MESSAGE,            /*!< Text messaging */
811         SIP_UPDATE,             /*!< Update a dialog. We can send UPDATE; but not accept it */
812         SIP_INFO,               /*!< Information updates during a session */
813         SIP_CANCEL,             /*!< Cancel an INVITE */
814         SIP_PUBLISH,            /*!< Not supported in Asterisk */
815         SIP_PING,               /*!< Not supported at all, no standard but still implemented out there */
816 };
817
818 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
819 enum notifycid_setting {
820         DISABLED       = 0,
821         ENABLED        = 1,
822         IGNORE_CONTEXT = 2,
823 };
824
825 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
826         structure and then route the messages according to the type.
827
828       \note Note that sip_methods[i].id == i must hold or the code breaks */
829 static const struct  cfsip_methods { 
830         enum sipmethod id;
831         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
832         char * const text;
833         enum can_create_dialog can_create;
834 } sip_methods[] = {
835         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
836         { SIP_RESPONSE,  NO_RTP, "SIP/2.0",     CAN_NOT_CREATE_DIALOG },
837         { SIP_REGISTER,  NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
838         { SIP_OPTIONS,   NO_RTP, "OPTIONS",     CAN_CREATE_DIALOG },
839         { SIP_NOTIFY,    NO_RTP, "NOTIFY",      CAN_CREATE_DIALOG },
840         { SIP_INVITE,    RTP,    "INVITE",      CAN_CREATE_DIALOG },
841         { SIP_ACK,       NO_RTP, "ACK",         CAN_NOT_CREATE_DIALOG },
842         { SIP_PRACK,     NO_RTP, "PRACK",       CAN_NOT_CREATE_DIALOG },
843         { SIP_BYE,       NO_RTP, "BYE",         CAN_NOT_CREATE_DIALOG },
844         { SIP_REFER,     NO_RTP, "REFER",       CAN_CREATE_DIALOG },
845         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",   CAN_CREATE_DIALOG },
846         { SIP_MESSAGE,   NO_RTP, "MESSAGE",     CAN_CREATE_DIALOG },
847         { SIP_UPDATE,    NO_RTP, "UPDATE",      CAN_NOT_CREATE_DIALOG },
848         { SIP_INFO,      NO_RTP, "INFO",        CAN_NOT_CREATE_DIALOG },
849         { SIP_CANCEL,    NO_RTP, "CANCEL",      CAN_NOT_CREATE_DIALOG },
850         { SIP_PUBLISH,   NO_RTP, "PUBLISH",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
851         { SIP_PING,      NO_RTP, "PING",        CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
852 };
853
854 /*!  Define SIP option tags, used in Require: and Supported: headers 
855         We need to be aware of these properties in the phones to use 
856         the replace: header. We should not do that without knowing
857         that the other end supports it... 
858         This is nothing we can configure, we learn by the dialog
859         Supported: header on the REGISTER (peer) or the INVITE
860         (other devices)
861         We are not using many of these today, but will in the future.
862         This is documented in RFC 3261
863 */
864 #define SUPPORTED               1
865 #define NOT_SUPPORTED           0
866
867 /* SIP options */
868 #define SIP_OPT_REPLACES        (1 << 0)
869 #define SIP_OPT_100REL          (1 << 1)
870 #define SIP_OPT_TIMER           (1 << 2)
871 #define SIP_OPT_EARLY_SESSION   (1 << 3)
872 #define SIP_OPT_JOIN            (1 << 4)
873 #define SIP_OPT_PATH            (1 << 5)
874 #define SIP_OPT_PREF            (1 << 6)
875 #define SIP_OPT_PRECONDITION    (1 << 7)
876 #define SIP_OPT_PRIVACY         (1 << 8)
877 #define SIP_OPT_SDP_ANAT        (1 << 9)
878 #define SIP_OPT_SEC_AGREE       (1 << 10)
879 #define SIP_OPT_EVENTLIST       (1 << 11)
880 #define SIP_OPT_GRUU            (1 << 12)
881 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
882 #define SIP_OPT_NOREFERSUB      (1 << 14)
883 #define SIP_OPT_HISTINFO        (1 << 15)
884 #define SIP_OPT_RESPRIORITY     (1 << 16)
885 #define SIP_OPT_FROMCHANGE      (1 << 17)
886 #define SIP_OPT_RECLISTINV      (1 << 18)
887 #define SIP_OPT_RECLISTSUB      (1 << 19)
888 #define SIP_OPT_OUTBOUND        (1 << 20)
889 #define SIP_OPT_UNKNOWN         (1 << 21)
890
891
892 /*! \brief List of well-known SIP options. If we get this in a require,
893    we should check the list and answer accordingly. */
894 static const struct cfsip_options {
895         int id;                 /*!< Bitmap ID */
896         int supported;          /*!< Supported by Asterisk ? */
897         char * const text;      /*!< Text id, as in standard */
898 } sip_options[] = {     /* XXX used in 3 places */
899         /* RFC3262: PRACK 100% reliability */
900         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
901         /* RFC3959: SIP Early session support */
902         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
903         /* SIMPLE events:  RFC4662 */
904         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
905         /* RFC 4916- Connected line ID updates */
906         { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED,  "from-change" },
907         /* GRUU: Globally Routable User Agent URI's */
908         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
909         /* RFC4244 History info */
910         { SIP_OPT_HISTINFO,     NOT_SUPPORTED,  "histinfo" },
911         /* RFC3911: SIP Join header support */
912         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
913         /* Disable the REFER subscription, RFC 4488 */
914         { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED,  "norefersub" },
915         /* SIP outbound - the final NAT battle - draft-sip-outbound */
916         { SIP_OPT_OUTBOUND,     NOT_SUPPORTED,  "outbound" },
917         /* RFC3327: Path support */
918         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
919         /* RFC3840: Callee preferences */
920         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
921         /* RFC3312: Precondition support */
922         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
923         /* RFC3323: Privacy with proxies*/
924         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
925         /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
926         { SIP_OPT_RECLISTINV,   NOT_SUPPORTED,  "recipient-list-invite" },
927         /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
928         { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED,  "recipient-list-subscribe" },
929         /* RFC3891: Replaces: header for transfer */
930         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
931         /* One version of Polycom firmware has the wrong label */
932         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },    
933         /* RFC4412 Resource priorities */
934         { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED,  "resource-priority" },
935         /* RFC3329: Security agreement mechanism */
936         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
937         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
938         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
939         /* RFC4028: SIP Session-Timers */
940         { SIP_OPT_TIMER,        SUPPORTED,      "timer" },
941         /* RFC4538: Target-dialog */
942         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "tdialog" },
943 };
944
945 /*! \brief Diversion header reasons
946  *
947  * The core defines a bunch of constants used to define
948  * redirecting reasons. This provides a translation table
949  * between those and the strings which may be present in
950  * a SIP Diversion header
951  */
952 static const struct sip_reasons {
953         enum AST_REDIRECTING_REASON code;
954         char * const text;
955 } sip_reason_table[] = {
956         { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
957         { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
958         { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
959         { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
960         { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
961         { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
962         { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
963         { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
964         { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
965         { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
966         { AST_REDIRECTING_REASON_AWAY, "away" },
967         { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
968 };
969
970 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
971 {
972         enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
973         int i;
974
975         for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
976                 if (!strcasecmp(text, sip_reason_table[i].text)) {
977                         ast = sip_reason_table[i].code;
978                         break;
979                 }
980         }
981
982         return ast;
983 }
984
985 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
986 {
987         if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
988                 return sip_reason_table[code].text;
989         }
990
991         return "unknown";
992 }
993
994 /*! \brief SIP Methods we support 
995         \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
996         allowsubscribe and allowrefer on in sip.conf.
997 */
998 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
999
1000 /*! \brief SIP Extensions we support 
1001         \note This should be generated based on the previous array
1002                 in combination with settings.
1003         \todo We should not have "timer" if it's disabled in the configuration file.
1004 */
1005 #define SUPPORTED_EXTENSIONS "replaces, timer" 
1006
1007 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
1008 #define STANDARD_SIP_PORT       5060
1009 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
1010 #define STANDARD_TLS_PORT       5061
1011
1012 /*! \note in many SIP headers, absence of a port number implies port 5060,
1013  * and this is why we cannot change the above constant.
1014  * There is a limited number of places in asterisk where we could,
1015  * in principle, use a different "default" port number, but
1016  * we do not support this feature at the moment.
1017  * You can run Asterisk with SIP on a different port with a configuration
1018  * option. If you change this value, the signalling will be incorrect.
1019  */
1020
1021 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
1022
1023    These are default values in the source. There are other recommended values in the
1024    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
1025    yet encouraging new behaviour on new installations 
1026  */
1027 /*@{*/ 
1028 #define DEFAULT_CONTEXT         "default"       /*!< The default context for [general] section as well as devices */
1029 #define DEFAULT_MOHINTERPRET    "default"       /*!< The default music class */
1030 #define DEFAULT_MOHSUGGEST      ""
1031 #define DEFAULT_VMEXTEN         "asterisk"      /*!< Default voicemail extension */
1032 #define DEFAULT_CALLERID        "asterisk"      /*!< Default caller ID */
1033 #define DEFAULT_MWI_FROM ""
1034 #define DEFAULT_NOTIFYMIME      "application/simple-message-summary"
1035 #define DEFAULT_ALLOWGUEST      TRUE
1036 #define DEFAULT_RTPKEEPALIVE    0               /*!< Default RTPkeepalive setting */
1037 #define DEFAULT_CALLCOUNTER     FALSE
1038 #define DEFAULT_SRVLOOKUP       TRUE            /*!< Recommended setting is ON */
1039 #define DEFAULT_COMPACTHEADERS  FALSE           /*!< Send compact (one-character) SIP headers. Default off */
1040 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
1041 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
1042 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
1043 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
1044 #define DEFAULT_COS_SIP         4               /*!< Level 2 class of service for SIP signalling */
1045 #define DEFAULT_COS_AUDIO       5               /*!< Level 2 class of service for audio media  */
1046 #define DEFAULT_COS_VIDEO       6               /*!< Level 2 class of service for video media */
1047 #define DEFAULT_COS_TEXT        5               /*!< Level 2 class of service for text media (T.140) */
1048 #define DEFAULT_ALLOW_EXT_DOM   TRUE            /*!< Allow external domains */
1049 #define DEFAULT_REALM           "asterisk"      /*!< Realm for HTTP digest authentication */
1050 #define DEFAULT_NOTIFYRINGING   TRUE            /*!< Notify devicestate system on ringing state */
1051 #define DEFAULT_NOTIFYCID               DISABLED        /*!< Include CID with ringing notifications */
1052 #define DEFAULT_PEDANTIC        FALSE           /*!< Avoid following SIP standards for dialog matching */
1053 #define DEFAULT_AUTOCREATEPEER  FALSE           /*!< Don't create peers automagically */
1054 #define DEFAULT_MATCHEXTERNIPLOCALLY FALSE      /*!< Match extern IP locally default setting */
1055 #define DEFAULT_QUALIFY         FALSE           /*!< Don't monitor devices */
1056 #define DEFAULT_CALLEVENTS      FALSE           /*!< Extra manager SIP call events */
1057 #define DEFAULT_ALWAYSAUTHREJECT        FALSE   /*!< Don't reject authentication requests always */
1058 #define DEFAULT_REGEXTENONQUALIFY FALSE
1059 #define DEFAULT_T1MIN           100             /*!< 100 MS for minimal roundtrip time */
1060 #define DEFAULT_MAX_CALL_BITRATE (384)          /*!< Max bitrate for video */
1061 #ifndef DEFAULT_USERAGENT
1062 #define DEFAULT_USERAGENT "Asterisk PBX"        /*!< Default Useragent: header unless re-defined in sip.conf */
1063 #define DEFAULT_SDPSESSION "Asterisk PBX"       /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
1064 #define DEFAULT_SDPOWNER "root"                 /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
1065 #define DEFAULT_ENGINE "asterisk"               /*!< Default RTP engine to use for sessions */
1066 #endif
1067 /*@}*/ 
1068
1069 /*! \name DefaultSettings
1070         Default setttings are used as a channel setting and as a default when
1071         configuring devices 
1072 */
1073 /*@{*/ 
1074 static char default_language[MAX_LANGUAGE];
1075 static char default_callerid[AST_MAX_EXTENSION];
1076 static char default_mwi_from[80];
1077 static char default_fromdomain[AST_MAX_EXTENSION];
1078 static char default_notifymime[AST_MAX_EXTENSION];
1079 static int default_qualify;             /*!< Default Qualify= setting */
1080 static char default_vmexten[AST_MAX_EXTENSION];
1081 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
1082 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
1083                                                     *   a bridged channel on hold */
1084 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
1085 static char default_engine[256];        /*!< Default RTP engine */
1086 static int default_maxcallbitrate;      /*!< Maximum bitrate for call */
1087 static struct ast_codec_pref default_prefs;             /*!< Default codec prefs */
1088 static unsigned int default_transports;                 /*!< Default Transports (enum sip_transport) that are acceptable */
1089 static unsigned int default_primary_transport;          /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
1090
1091 /*@}*/ 
1092
1093 /*! \name GlobalSettings
1094         Global settings apply to the channel (often settings you can change in the general section
1095         of sip.conf
1096 */
1097 /*@{*/ 
1098 /*! \brief a place to store all global settings for the sip channel driver 
1099         These are settings that will be possibly to apply on a group level later on.
1100         \note Do not add settings that only apply to the channel itself and can't
1101               be applied to devices (trunks, services, phones)
1102 */
1103 struct sip_settings {
1104         int peer_rtupdate;              /*!< G: Update database with registration data for peer? */
1105         int rtsave_sysname;             /*!< G: Save system name at registration? */
1106         int ignore_regexpire;           /*!< G: Ignore expiration of peer  */
1107         int rtautoclear;                /*!< Realtime ?? */
1108         int directrtpsetup;             /*!< Enable support for Direct RTP setup (no re-invites) */
1109         int pedanticsipchecking;        /*!< Extra checking ?  Default off */
1110         int autocreatepeer;             /*!< Auto creation of peers at registration? Default off. */
1111         int srvlookup;                  /*!< SRV Lookup on or off. Default is on */
1112         int allowguest;                 /*!< allow unauthenticated peers to connect? */
1113         int alwaysauthreject;           /*!< Send 401 Unauthorized for all failing requests */
1114         int compactheaders;             /*!< send compact sip headers */
1115         int allow_external_domains;     /*!< Accept calls to external SIP domains? */
1116         int callevents;                 /*!< Whether we send manager events or not */
1117         int regextenonqualify;          /*!< Whether to add/remove regexten when qualifying peers */
1118         int matchexterniplocally;       /*!< Match externip/externhost setting against localnet setting */
1119         int notifyringing;              /*!< Send notifications on ringing */
1120         int notifyhold;                 /*!< Send notifications on hold */
1121         enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
1122         enum transfermodes allowtransfer;       /*!< SIP Refer restriction scheme */
1123         int allowsubscribe;             /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
1124                                             the global setting is in globals_flags[1] */
1125         char realm[MAXHOSTNAMELEN];             /*!< Default realm */
1126         struct sip_proxy outboundproxy; /*!< Outbound proxy */
1127         char default_context[AST_MAX_CONTEXT];
1128         char default_subscribecontext[AST_MAX_CONTEXT];
1129 };
1130
1131 static struct sip_settings sip_cfg;
1132
1133 static int global_match_auth_username;          /*!< Match auth username if available instead of From: Default off. */
1134
1135 static int global_relaxdtmf;            /*!< Relax DTMF */
1136 static int global_rtptimeout;           /*!< Time out call if no RTP */
1137 static int global_rtpholdtimeout;       /*!< Time out call if no RTP during hold */
1138 static int global_rtpkeepalive;         /*!< Send RTP keepalives */
1139 static int global_reg_timeout;  
1140 static int global_regattempts_max;      /*!< Registration attempts before giving up */
1141 static int global_callcounter;          /*!< Enable call counters for all devices. This is currently enabled by setting the peer
1142                                                 call-limit to 999. When we remove the call-limit from the code, we can make it
1143                                                 with just a boolean flag in the device structure */
1144 static unsigned int global_tos_sip;             /*!< IP type of service for SIP packets */
1145 static unsigned int global_tos_audio;           /*!< IP type of service for audio RTP packets */
1146 static unsigned int global_tos_video;           /*!< IP type of service for video RTP packets */
1147 static unsigned int global_tos_text;            /*!< IP type of service for text RTP packets */
1148 static unsigned int global_cos_sip;             /*!< 802.1p class of service for SIP packets */
1149 static unsigned int global_cos_audio;           /*!< 802.1p class of service for audio RTP packets */
1150 static unsigned int global_cos_video;           /*!< 802.1p class of service for video RTP packets */
1151 static unsigned int global_cos_text;            /*!< 802.1p class of service for text RTP packets */
1152 static int recordhistory;               /*!< Record SIP history. Off by default */
1153 static int dumphistory;                 /*!< Dump history to verbose before destroying SIP dialog */
1154 static char global_regcontext[AST_MAX_CONTEXT];         /*!< Context for auto-extensions */
1155 static char global_useragent[AST_MAX_EXTENSION];        /*!< Useragent for the SIP channel */
1156 static char global_sdpsession[AST_MAX_EXTENSION];       /*!< SDP session name for the SIP channel */
1157 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
1158 static int global_authfailureevents;            /*!< Whether we send authentication failure manager events or not. Default no. */
1159 static int global_t1;                   /*!< T1 time */
1160 static int global_t1min;                /*!< T1 roundtrip time minimum */
1161 static int global_timer_b;                      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
1162 static int global_autoframing;                  /*!< Turn autoframing on or off. */
1163 static int global_qualifyfreq;                  /*!< Qualify frequency */
1164 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
1165 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
1166
1167
1168 /*! \brief Codecs that we support by default: */
1169 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
1170
1171 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
1172 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
1173 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
1174 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
1175
1176 /*@}*/ 
1177
1178 /*! \brief Global list of addresses dynamic peers are not allowed to use */
1179 static struct ast_ha *global_contact_ha = NULL;
1180 static int global_dynamic_exclude_static = 0;
1181
1182 /*! \name Object counters @{
1183  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
1184  * should be used to modify these values. */
1185 static int speerobjs = 0;                /*!< Static peers */
1186 static int rpeerobjs = 0;                /*!< Realtime peers */
1187 static int apeerobjs = 0;                /*!< Autocreated peer objects */
1188 static int regobjs = 0;                  /*!< Registry objects */
1189 /* }@ */
1190
1191 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
1192 static char used_context[AST_MAX_CONTEXT];              /*!< name of automatically created context for unloading */
1193
1194
1195 AST_MUTEX_DEFINE_STATIC(netlock);
1196
1197 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
1198    when it's doing something critical. */
1199 AST_MUTEX_DEFINE_STATIC(monlock);
1200
1201 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
1202
1203 /*! \brief This is the thread for the monitor which checks for input on the channels
1204    which are not currently in use.  */
1205 static pthread_t monitor_thread = AST_PTHREADT_NULL;
1206
1207 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
1208 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
1209
1210 static struct sched_context *sched;     /*!< The scheduling context */
1211 static struct io_context *io;           /*!< The IO context */
1212 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
1213
1214 #define DEC_CALL_LIMIT  0
1215 #define INC_CALL_LIMIT  1
1216 #define DEC_CALL_RINGING 2
1217 #define INC_CALL_RINGING 3
1218
1219 /*! \brief The SIP socket definition */
1220 struct sip_socket {
1221         enum sip_transport type;        /*!< UDP, TCP or TLS */
1222         int fd;                         /*!< Filed descriptor, the actual socket */
1223         uint16_t port;
1224         struct ast_tcptls_session_instance *tcptls_session;     /* If tcp or tls, a socket manager */
1225 };
1226
1227 /*! \brief sip_request: The data grabbed from the UDP socket
1228  *
1229  * \verbatim
1230  * Incoming messages: we first store the data from the socket in data[],
1231  * adding a trailing \0 to make string parsing routines happy.
1232  * Then call parse_request() and req.method = find_sip_method();
1233  * to initialize the other fields. The \r\n at the end of each line is   
1234  * replaced by \0, so that data[] is not a conforming SIP message anymore.
1235  * After this processing, rlPart1 is set to non-NULL to remember
1236  * that we can run get_header() on this kind of packet.
1237  *
1238  * parse_request() splits the first line as follows:
1239  * Requests have in the first line      method uri SIP/2.0
1240  *      rlPart1 = method; rlPart2 = uri;
1241  * Responses have in the first line     SIP/2.0 NNN description
1242  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
1243  *
1244  * For outgoing packets, we initialize the fields with init_req() or init_resp()
1245  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
1246  * and then fill the rest with add_header() and add_line().
1247  * The \r\n at the end of the line are still there, so the get_header()
1248  * and similar functions don't work on these packets. 
1249  * \endverbatim
1250  */
1251 struct sip_request {
1252         ptrdiff_t rlPart1;              /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
1253         ptrdiff_t rlPart2;              /*!< Offset of the Request URI or Response Status */
1254         int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
1255         int headers;            /*!< # of SIP Headers */
1256         int method;             /*!< Method of this request */
1257         int lines;              /*!< Body Content */
1258         unsigned int sdp_start; /*!< the line number where the SDP begins */
1259         unsigned int sdp_end;   /*!< the line number where the SDP ends */
1260         char debug;             /*!< print extra debugging if non zero */
1261         char has_to_tag;        /*!< non-zero if packet has To: tag */
1262         char ignore;            /*!< if non-zero This is a re-transmit, ignore it */
1263         /* Array of offsets into the request string of each SIP header*/
1264         ptrdiff_t header[SIP_MAX_HEADERS];
1265         /* Array of offsets into the request string of each SDP line*/
1266         ptrdiff_t line[SIP_MAX_LINES];
1267         struct ast_str *data;   
1268         /* XXX Do we need to unref socket.ser when the request goes away? */
1269         struct sip_socket socket;       /*!< The socket used for this request */
1270         AST_LIST_ENTRY(sip_request) next;
1271 };
1272
1273 /* \brief given a sip_request and an offset, return the char * that resides there
1274  *
1275  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
1276  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
1277  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
1278  * provided to retrieve the string at a particular offset within the request's buffer
1279  */
1280 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
1281
1282 /*! \brief structure used in transfers */
1283 struct sip_dual {
1284         struct ast_channel *chan1;      /*!< First channel involved */
1285         struct ast_channel *chan2;      /*!< Second channel involved */
1286         struct sip_request req;         /*!< Request that caused the transfer (REFER) */
1287         int seqno;                      /*!< Sequence number */
1288 };
1289
1290 struct sip_pkt;
1291
1292 /*! \brief Parameters to the transmit_invite function */
1293 struct sip_invite_param {
1294         int addsipheaders;              /*!< Add extra SIP headers */
1295         const char *uri_options;        /*!< URI options to add to the URI */
1296         const char *vxml_url;           /*!< VXML url for Cisco phones */
1297         char *auth;                     /*!< Authentication */
1298         char *authheader;               /*!< Auth header */
1299         enum sip_auth_type auth_type;   /*!< Authentication type */
1300         const char *replaces;           /*!< Replaces header for call transfers */
1301         int transfer;                   /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
1302 };
1303
1304 /*! \brief Structure to save routing information for a SIP session */
1305 struct sip_route {
1306         struct sip_route *next;
1307         char hop[0];
1308 };
1309
1310 /*! \brief Modes for SIP domain handling in the PBX */
1311 enum domain_mode {
1312         SIP_DOMAIN_AUTO,                /*!< This domain is auto-configured */
1313         SIP_DOMAIN_CONFIG,              /*!< This domain is from configuration */
1314 };
1315
1316 /*! \brief Domain data structure. 
1317         \note In the future, we will connect this to a configuration tree specific
1318         for this domain
1319 */
1320 struct domain {
1321         char domain[MAXHOSTNAMELEN];            /*!< SIP domain we are responsible for */
1322         char context[AST_MAX_EXTENSION];        /*!< Incoming context for this domain */
1323         enum domain_mode mode;                  /*!< How did we find this domain? */
1324         AST_LIST_ENTRY(domain) list;            /*!< List mechanics */
1325 };
1326
1327 static AST_LIST_HEAD_STATIC(domain_list, domain);       /*!< The SIP domain list */
1328
1329
1330 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
1331 struct sip_history {
1332         AST_LIST_ENTRY(sip_history) list;
1333         char event[0];  /* actually more, depending on needs */
1334 };
1335
1336 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
1337
1338 /*! \brief sip_auth: Credentials for authentication to other SIP services */
1339 struct sip_auth {
1340         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
1341         char username[256];             /*!< Username */
1342         char secret[256];               /*!< Secret */
1343         char md5secret[256];            /*!< MD5Secret */
1344         struct sip_auth *next;          /*!< Next auth structure in list */
1345 };
1346
1347 /*! \name SIPflags
1348         Various flags for the flags field in the pvt structure 
1349         Trying to sort these up (one or more of the following):
1350         D: Dialog
1351         P: Peer/user
1352         G: Global flag
1353         When flags are used by multiple structures, it is important that
1354         they have a common layout so it is easy to copy them.
1355 */
1356 /*@{*/ 
1357 #define SIP_OUTGOING            (1 << 0)        /*!< D: Direction of the last transaction in this dialog */
1358 #define SIP_RINGING             (1 << 2)        /*!< D: Have sent 180 ringing */
1359 #define SIP_PROGRESS_SENT       (1 << 3)        /*!< D: Have sent 183 message progress */
1360 #define SIP_NEEDREINVITE        (1 << 4)        /*!< D: Do we need to send another reinvite? */
1361 #define SIP_PENDINGBYE          (1 << 5)        /*!< D: Need to send bye after we ack? */
1362 #define SIP_GOTREFER            (1 << 6)        /*!< D: Got a refer? */
1363 #define SIP_CALL_LIMIT          (1 << 7)        /*!< D: Call limit enforced for this call */
1364 #define SIP_INC_COUNT           (1 << 8)        /*!< D: Did this dialog increment the counter of in-use calls? */
1365 #define SIP_INC_RINGING         (1 << 9)        /*!< D: Did this connection increment the counter of in-use calls? */
1366 #define SIP_DEFER_BYE_ON_TRANSFER       (1 << 10)       /*!< D: Do not hangup at first ast_hangup */
1367
1368 #define SIP_PROMISCREDIR        (1 << 11)       /*!< DP: Promiscuous redirection */
1369 #define SIP_TRUSTRPID           (1 << 12)       /*!< DP: Trust RPID headers? */
1370 #define SIP_USEREQPHONE         (1 << 13)       /*!< DP: Add user=phone to numeric URI. Default off */
1371 #define SIP_USECLIENTCODE       (1 << 14)       /*!< DP: Trust X-ClientCode info message */
1372
1373 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
1374 #define SIP_DTMF                (7 << 15)       /*!< DP: DTMF Support: five settings, uses three bits */
1375 #define SIP_DTMF_RFC2833        (0 << 15)       /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
1376 #define SIP_DTMF_INBAND         (1 << 15)       /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
1377 #define SIP_DTMF_INFO           (2 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" */
1378 #define SIP_DTMF_AUTO           (3 << 15)       /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
1379 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
1380
1381 /* NAT settings - see nat2str() */
1382 #define SIP_NAT                 (3 << 18)       /*!< DP: four settings, uses two bits */
1383 #define SIP_NAT_NEVER           (0 << 18)       /*!< DP: No nat support */
1384 #define SIP_NAT_RFC3581         (1 << 18)       /*!< DP: NAT RFC3581 */
1385 #define SIP_NAT_ROUTE           (2 << 18)       /*!< DP: NAT Only ROUTE */
1386 #define SIP_NAT_ALWAYS          (3 << 18)       /*!< DP: NAT Both ROUTE and RFC3581 */
1387
1388 /* re-INVITE related settings */
1389 #define SIP_REINVITE            (7 << 20)       /*!< DP: four settings, uses three bits */
1390 #define SIP_REINVITE_NONE       (0 << 20)       /*!< DP: no reinvite allowed */
1391 #define SIP_CAN_REINVITE        (1 << 20)       /*!< DP: allow peers to be reinvited to send media directly p2p */
1392 #define SIP_CAN_REINVITE_NAT    (2 << 20)       /*!< DP: allow media reinvite when new peer is behind NAT */
1393 #define SIP_REINVITE_UPDATE     (4 << 20)       /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
1394
1395 /* "insecure" settings - see insecure2str() */
1396 #define SIP_INSECURE            (3 << 23)       /*!< DP: three settings, uses two bits */
1397 #define SIP_INSECURE_NONE       (0 << 23)       /*!< DP: secure mode */
1398 #define SIP_INSECURE_PORT       (1 << 23)       /*!< DP: don't require matching port for incoming requests */
1399 #define SIP_INSECURE_INVITE     (1 << 24)       /*!< DP: don't require authentication for incoming INVITEs */
1400
1401 /* Sending PROGRESS in-band settings */
1402 #define SIP_PROG_INBAND         (3 << 25)       /*!< DP: three settings, uses two bits */
1403 #define SIP_PROG_INBAND_NEVER   (0 << 25)
1404 #define SIP_PROG_INBAND_NO      (1 << 25)
1405 #define SIP_PROG_INBAND_YES     (2 << 25)
1406
1407 #define SIP_SENDRPID            (3 << 29)       /*!< DP: Remote Party-ID Support */
1408 #define SIP_SENDRPID_NO     (0 << 29)
1409 #define SIP_SENDRPID_PAI    (1 << 29)   /*!< Use "P-Asserted-Identity" for rpid */
1410 #define SIP_SENDRPID_RPID   (2 << 29)   /*!< Use "Remote-Party-ID" for rpid */
1411 #define SIP_G726_NONSTANDARD    (1 << 31)       /*!< DP: Use non-standard packing for G726-32 data */
1412
1413 /*! \brief Flags to copy from peer/user to dialog */
1414 #define SIP_FLAGS_TO_COPY \
1415         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
1416          SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
1417          SIP_USEREQPHONE | SIP_INSECURE)
1418 /*@}*/ 
1419
1420 /*! \name SIPflags2
1421         a second page of flags (for flags[1] */
1422 /*@{*/ 
1423 /* realtime flags */
1424 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)        /*!< GP: Should we keep RT objects in memory for extended time? */
1425 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)        /*!< GP: Should we clean memory from peers after expiry? */
1426 /* Space for addition of other realtime flags in the future */
1427 #define SIP_PAGE2_STATECHANGEQUEUE      (1 << 9)        /*!< D: Unsent state pending change exists */
1428
1429 #define SIP_PAGE2_CONNECTLINEUPDATE_PEND                (1 << 10)
1430 #define SIP_PAGE2_RPID_IMMEDIATE                        (1 << 11)
1431
1432 #define SIP_PAGE2_PREFERRED_CODEC       (1 << 13)       /*!< GDP: Only respond with single most preferred joint codec */
1433 #define SIP_PAGE2_VIDEOSUPPORT          (1 << 14)       /*!< DP: Video supported if offered? */
1434 #define SIP_PAGE2_TEXTSUPPORT           (1 << 15)       /*!< GDP: Global text enable */
1435 #define SIP_PAGE2_ALLOWSUBSCRIBE        (1 << 16)       /*!< GP: Allow subscriptions from this peer? */
1436 #define SIP_PAGE2_ALLOWOVERLAP          (1 << 17)       /*!< DP: Allow overlap dialing ? */
1437 #define SIP_PAGE2_SUBSCRIBEMWIONLY      (1 << 18)       /*!< GP: Only issue MWI notification if subscribed to */
1438 #define SIP_PAGE2_IGNORESDPVERSION      (1 << 19)       /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
1439
1440 #define SIP_PAGE2_T38SUPPORT            (7 << 20)       /*!< GDP: T38 Fax Passthrough Support */
1441 #define SIP_PAGE2_T38SUPPORT_UDPTL      (1 << 20)       /*!< GDP: T38 Fax Passthrough Support */
1442 #define SIP_PAGE2_T38SUPPORT_RTP        (2 << 20)       /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1443 #define SIP_PAGE2_T38SUPPORT_TCP        (4 << 20)       /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1444
1445 #define SIP_PAGE2_CALL_ONHOLD           (3 << 23)       /*!< D: Call hold states: */
1446 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
1447 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR    (2 << 23)       /*!< D: One directional hold */
1448 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE  (3 << 23)       /*!< D: Inactive hold */
1449
1450 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)       /*!< DP: Compensate for buggy RFC2833 implementations */
1451 #define SIP_PAGE2_BUGGY_MWI             (1 << 26)       /*!< DP: Buggy CISCO MWI fix */
1452 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
1453 #define SIP_PAGE2_FAX_DETECT            (1 << 28)               /*!< DP: Fax Detection support */
1454 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
1455 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
1456 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS   (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
1457
1458 #define SIP_PAGE2_FLAGS_TO_COPY \
1459         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
1460         SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
1461         SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
1462         SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | SIP_PAGE2_PREFERRED_CODEC | \
1463         SIP_PAGE2_RPID_IMMEDIATE)
1464
1465 /*@}*/ 
1466
1467 /*! \name SIPflagsT38
1468         T.38 set of flags */
1469
1470 /*@{*/ 
1471 #define T38FAX_FILL_BIT_REMOVAL                 (1 << 0)        /*!< Default: 0 (unset)*/
1472 #define T38FAX_TRANSCODING_MMR                  (1 << 1)        /*!< Default: 0 (unset)*/
1473 #define T38FAX_TRANSCODING_JBIG                 (1 << 2)        /*!< Default: 0 (unset)*/
1474 /* Rate management */
1475 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF   (0 << 3)
1476 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF        (1 << 3)        /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
1477 /* UDP Error correction */
1478 #define T38FAX_UDP_EC_NONE                      (0 << 4)        /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
1479 #define T38FAX_UDP_EC_FEC                       (1 << 4)        /*!< Set for t38UDPFEC */
1480 #define T38FAX_UDP_EC_REDUNDANCY                (2 << 4)        /*!< Set for t38UDPRedundancy */
1481 /* T38 Spec version */
1482 #define T38FAX_VERSION                          (3 << 6)        /*!< two bits, 2 values so far, up to 4 values max */
1483 #define T38FAX_VERSION_0                        (0 << 6)        /*!< Version 0 */
1484 #define T38FAX_VERSION_1                        (1 << 6)        /*!< Version 1 */
1485 /* Maximum Fax Rate */
1486 #define T38FAX_RATE_2400                        (1 << 8)        /*!< 2400 bps t38FaxRate */
1487 #define T38FAX_RATE_4800                        (1 << 9)        /*!< 4800 bps t38FaxRate */
1488 #define T38FAX_RATE_7200                        (1 << 10)       /*!< 7200 bps t38FaxRate */
1489 #define T38FAX_RATE_9600                        (1 << 11)       /*!< 9600 bps t38FaxRate */
1490 #define T38FAX_RATE_12000                       (1 << 12)       /*!< 12000 bps t38FaxRate */
1491 #define T38FAX_RATE_14400                       (1 << 13)       /*!< 14400 bps t38FaxRate */
1492
1493 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
1494 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
1495 /*@}*/ 
1496
1497 /*! \brief debugging state
1498  * We store separately the debugging requests from the config file
1499  * and requests from the CLI. Debugging is enabled if either is set
1500  * (which means that if sipdebug is set in the config file, we can
1501  * only turn it off by reloading the config).
1502  */
1503 enum sip_debug_e {
1504         sip_debug_none = 0,
1505         sip_debug_config = 1,
1506         sip_debug_console = 2,
1507 };
1508
1509 static enum sip_debug_e sipdebug;
1510
1511 /*! \brief extra debugging for 'text' related events.
1512  * At the moment this is set together with sip_debug_console.
1513  * \note It should either go away or be implemented properly.
1514  */
1515 static int sipdebug_text;
1516
1517 /*! \brief T38 States for a call */
1518 enum t38state {
1519         T38_DISABLED = 0,                /*!< Not enabled */
1520         T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
1521         T38_PEER_DIRECT,                 /*!< Offered from peer */
1522         T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
1523         T38_ENABLED                      /*!< Negotiated (enabled) */
1524 };
1525
1526 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
1527 struct t38properties {
1528         struct ast_flags t38support;    /*!< Flag for udptl, rtp or tcp support for this session */
1529         int capability;                 /*!< Our T38 capability */
1530         int peercapability;             /*!< Peers T38 capability */
1531         int jointcapability;            /*!< Supported T38 capability at both ends */
1532         enum t38state state;            /*!< T.38 state */
1533         unsigned int direct:1;          /*!< Whether the T38 came from the initial invite or not */
1534 };
1535
1536 /*! \brief Parameters to know status of transfer */
1537 enum referstatus {
1538         REFER_IDLE,                    /*!< No REFER is in progress */
1539         REFER_SENT,                    /*!< Sent REFER to transferee */
1540         REFER_RECEIVED,                /*!< Received REFER from transferrer */
1541         REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
1542         REFER_ACCEPTED,                /*!< Accepted by transferee */
1543         REFER_RINGING,                 /*!< Target Ringing */
1544         REFER_200OK,                   /*!< Answered by transfer target */
1545         REFER_FAILED,                  /*!< REFER declined - go on */
1546         REFER_NOAUTH                   /*!< We had no auth for REFER */
1547 };
1548
1549 /*! \brief generic struct to map between strings and integers.
1550  * Fill it with x-s pairs, terminate with an entry with s = NULL;
1551  * Then you can call map_x_s(...) to map an integer to a string,
1552  * and map_s_x() for the string -> integer mapping.
1553  */
1554 struct _map_x_s {
1555         int x;
1556         const char *s;
1557 };              
1558
1559 static const struct _map_x_s referstatusstrings[] = {
1560         { REFER_IDLE,           "<none>" },
1561         { REFER_SENT,           "Request sent" },
1562         { REFER_RECEIVED,       "Request received" },
1563         { REFER_CONFIRMED,      "Confirmed" },
1564         { REFER_ACCEPTED,       "Accepted" },
1565         { REFER_RINGING,        "Target ringing" },
1566         { REFER_200OK,          "Done" },
1567         { REFER_FAILED,         "Failed" },
1568         { REFER_NOAUTH,         "Failed - auth failure" },
1569         { -1,                   NULL} /* terminator */
1570 };
1571
1572 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1573         \note OEJ: Should be moved to string fields */
1574 struct sip_refer {
1575         char refer_to[AST_MAX_EXTENSION];               /*!< Place to store REFER-TO extension */
1576         char refer_to_domain[AST_MAX_EXTENSION];        /*!< Place to store REFER-TO domain */
1577         char refer_to_urioption[AST_MAX_EXTENSION];     /*!< Place to store REFER-TO uri options */
1578         char refer_to_context[AST_MAX_EXTENSION];       /*!< Place to store REFER-TO context */
1579         char referred_by[AST_MAX_EXTENSION];            /*!< Place to store REFERRED-BY extension */
1580         char referred_by_name[AST_MAX_EXTENSION];       /*!< Place to store REFERRED-BY extension */
1581         char refer_contact[AST_MAX_EXTENSION];          /*!< Place to store Contact info from a REFER extension */
1582         char replaces_callid[SIPBUFSIZE];                       /*!< Replace info: callid */
1583         char replaces_callid_totag[SIPBUFSIZE/2];               /*!< Replace info: to-tag */
1584         char replaces_callid_fromtag[SIPBUFSIZE/2];             /*!< Replace info: from-tag */
1585         struct sip_pvt *refer_call;                     /*!< Call we are referring. This is just a reference to a
1586                                                          * dialog owned by someone else, so we should not destroy
1587                                                          * it when the sip_refer object goes.
1588                                                          */
1589         int attendedtransfer;                           /*!< Attended or blind transfer? */
1590         int localtransfer;                              /*!< Transfer to local domain? */
1591         enum referstatus status;                        /*!< REFER status */
1592 };
1593
1594
1595 /*! \brief Structure that encapsulates all attributes related to running 
1596  *   SIP Session-Timers feature on a per dialog basis.
1597  */
1598 struct sip_st_dlg {
1599         int st_active;                          /*!< Session-Timers on/off */ 
1600         int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
1601         int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
1602         enum st_refresher st_ref;               /*!< Session-Timers session refresher */
1603         int st_expirys;                         /*!< Session-Timers number of expirys */
1604         int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
1605         int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
1606         int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
1607         enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
1608         enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
1609 };
1610
1611
1612 /*! \brief Structure that encapsulates all attributes related to configuration 
1613  *   of SIP Session-Timers feature on a per user/peer basis.
1614  */
1615 struct sip_st_cfg {
1616         enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
1617         enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
1618         int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
1619         int st_max_se;                  /*!< Highest threshold for session refresh interval */
1620 };
1621
1622
1623
1624
1625 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
1626  * Created and initialized by sip_alloc(), the descriptor goes into the list of
1627  * descriptors (dialoglist).
1628  */
1629 struct sip_pvt {
1630         struct sip_pvt *next;                   /*!< Next dialog in chain */
1631         enum invitestates invitestate;          /*!< Track state of SIP_INVITEs */
1632         int method;                             /*!< SIP method that opened this dialog */
1633         AST_DECLARE_STRING_FIELDS(
1634                 AST_STRING_FIELD(callid);       /*!< Global CallID */
1635                 AST_STRING_FIELD(randdata);     /*!< Random data */
1636                 AST_STRING_FIELD(accountcode);  /*!< Account code */
1637                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1638                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1639                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1640                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1641                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1642                 AST_STRING_FIELD(from);         /*!< The From: header */
1643                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
1644                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
1645                 AST_STRING_FIELD(context);      /*!< Context for this call */
1646                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1647                 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1648                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
1649                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
1650                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
1651                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
1652                 AST_STRING_FIELD(todnid);       /*!< DNID of this call (overrides host) */
1653                 AST_STRING_FIELD(language);     /*!< Default language for this call */
1654                 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1655                 AST_STRING_FIELD(mohsuggest);   /*!< MOH class to suggest when putting a peer on hold */
1656                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
1657                 AST_STRING_FIELD(redircause);   /*!< Referring cause */
1658                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
1659                 AST_STRING_FIELD(username);     /*!< [user] name */
1660                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
1661                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
1662                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
1663                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1664                 AST_STRING_FIELD(peersecret);   /*!< Password */
1665                 AST_STRING_FIELD(peermd5secret);
1666                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID number */
1667                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID name */
1668                 AST_STRING_FIELD(mwi_from); /*!< Name to place in the From header in outgoing NOTIFY requests */
1669                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
1670                         /* we only store the part in <brackets> in this field. */
1671                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
1672                 AST_STRING_FIELD(url);          /*!< URL to be sent with next message to peer */
1673                 AST_STRING_FIELD(parkinglot);           /*!< Parkinglot */
1674                 AST_STRING_FIELD(engine);       /*!< RTP engine to use */
1675         );
1676         char via[128];                          /*!< Via: header */
1677         struct sip_socket socket;               /*!< The socket used for this dialog */
1678         unsigned int ocseq;                     /*!< Current outgoing seqno */
1679         unsigned int icseq;                     /*!< Current incoming seqno */
1680         ast_group_t callgroup;                  /*!< Call group */
1681         ast_group_t pickupgroup;                /*!< Pickup group */
1682         int lastinvite;                         /*!< Last Cseq of invite */
1683         int lastnoninvite;                      /*!< Last Cseq of non-invite */
1684         struct ast_flags flags[2];              /*!< SIP_ flags */
1685
1686         /* boolean or small integers that don't belong in flags */
1687         char do_history;                        /*!< Set if we want to record history */
1688         char alreadygone;                       /*!< already destroyed by our peer */
1689         char needdestroy;                       /*!< need to be destroyed by the monitor thread */
1690         char outgoing_call;                     /*!< this is an outgoing call */
1691         char answered_elsewhere;                /*!< This call is cancelled due to answer on another channel */
1692         char novideo;                           /*!< Didn't get video in invite, don't offer */
1693         char notext;                            /*!< Text not supported  (?) */
1694
1695         int timer_t1;                           /*!< SIP timer T1, ms rtt */
1696         int timer_b;                            /*!< SIP timer B, ms */
1697         unsigned int sipoptions;                /*!< Supported SIP options on the other end */
1698         unsigned int reqsipoptions;             /*!< Required SIP options on the other end */
1699         struct ast_codec_pref prefs;            /*!< codec prefs */
1700         int capability;                         /*!< Special capability (codec) */
1701         int jointcapability;                    /*!< Supported capability at both ends (codecs) */
1702         int peercapability;                     /*!< Supported peer capability */
1703         int prefcodec;                          /*!< Preferred codec (outbound only) */
1704         int noncodeccapability;                 /*!< DTMF RFC2833 telephony-event */
1705         int jointnoncodeccapability;            /*!< Joint Non codec capability */
1706         int redircodecs;                        /*!< Redirect codecs */
1707         int maxcallbitrate;                     /*!< Maximum Call Bitrate for Video Calls */    
1708         struct sip_proxy *outboundproxy;        /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
1709         struct t38properties t38;               /*!< T38 settings */
1710         struct sockaddr_in udptlredirip;        /*!< Where our T.38 UDPTL should be going if not to us */
1711         struct ast_udptl *udptl;                /*!< T.38 UDPTL session */
1712         int callingpres;                        /*!< Calling presentation */
1713         int authtries;                          /*!< Times we've tried to authenticate */
1714         int expiry;                             /*!< How long we take to expire */
1715         long branch;                            /*!< The branch identifier of this session */
1716         long invite_branch;                     /*!< The branch used when we sent the initial INVITE */
1717         char tag[11];                           /*!< Our tag for this session */
1718         int sessionid;                          /*!< SDP Session ID */
1719         int sessionversion;                     /*!< SDP Session Version */
1720         uint64_t sessionversion_remote;         /*!< Remote UA's SDP Session Version */
1721         int session_modify;                     /*!< Session modification request true/false  */
1722         struct sockaddr_in sa;                  /*!< Our peer */
1723         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
1724         struct sockaddr_in vredirip;            /*!< Where our Video RTP should be going if not to us */
1725         struct sockaddr_in tredirip;            /*!< Where our Text RTP should be going if not to us */
1726         time_t lastrtprx;                       /*!< Last RTP received */
1727         time_t lastrtptx;                       /*!< Last RTP sent */
1728         int rtptimeout;                         /*!< RTP timeout time */
1729         struct sockaddr_in recv;                /*!< Received as */
1730         struct sockaddr_in ourip;               /*!< Our IP (as seen from the outside) */
1731         struct ast_channel *owner;              /*!< Who owns us (if we have an owner) */
1732         struct sip_route *route;                /*!< Head of linked list of routing steps (fm Record-Route) */
1733         int route_persistant;                   /*!< Is this the "real" route? */
1734         struct ast_variable *notify_headers;    /*!< Custom notify type */
1735         struct sip_auth *peerauth;              /*!< Realm authentication */
1736         int noncecount;                         /*!< Nonce-count */
1737         char lastmsg[256];                      /*!< Last Message sent/received */
1738         int amaflags;                           /*!< AMA Flags */
1739         int pendinginvite;                      /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1740         int glareinvite;                        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
1741                                                 value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
1742                                                 held in order to properly process acknowledgements for our 491 response. */
1743         struct sip_request initreq;             /*!< Latest request that opened a new transaction
1744                                                         within this dialog.
1745                                                         NOT the request that opened the dialog */
1746
1747         int initid;                             /*!< Auto-congest ID if appropriate (scheduler) */
1748         int waitid;                             /*!< Wait ID for scheduler after 491 or other delays */
1749         int autokillid;                         /*!< Auto-kill ID (scheduler) */
1750         int t38id;                              /*!< T.38 Response ID */
1751         enum transfermodes allowtransfer;       /*!< REFER: restriction scheme */
1752         struct sip_refer *refer;                /*!< REFER: SIP transfer data structure */
1753         enum subscriptiontype subscribed;       /*!< SUBSCRIBE: Is this dialog a subscription?  */
1754         int stateid;                            /*!< SUBSCRIBE: ID for devicestate subscriptions */
1755         int laststate;                          /*!< SUBSCRIBE: Last known extension state */
1756         int dialogver;                          /*!< SUBSCRIBE: Version for subscription dialog-info */
1757
1758         struct ast_dsp *vad;                    /*!< Inband DTMF Detection dsp */
1759
1760         struct sip_peer *relatedpeer;           /*!< If this dialog is related to a peer, which one 
1761                                                         Used in peerpoke, mwi subscriptions */
1762         struct sip_registry *registry;          /*!< If this is a REGISTER dialog, to which registry */
1763         struct ast_rtp_instance *rtp;                   /*!< RTP Session */
1764         struct ast_rtp_instance *vrtp;                  /*!< Video RTP session */
1765         struct ast_rtp_instance *trtp;                  /*!< Text RTP session */
1766         struct sip_pkt *packets;                /*!< Packets scheduled for re-transmission */
1767         struct sip_history_head *history;       /*!< History of this SIP dialog */
1768         size_t history_entries;                 /*!< Number of entires in the history */
1769         struct ast_variable *chanvars;          /*!< Channel variables to set for inbound call */
1770         AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
1771         int request_queue_sched_id;             /*!< Scheduler ID of any scheduled action to process queued requests */
1772         struct sip_invite_param *options;       /*!< Options for INVITE */
1773         int autoframing;                        /*!< The number of Asters we group in a Pyroflax
1774                                                         before strolling to the GrokyzpÃ¥
1775                                                         (A bit unsure of this, please correct if
1776                                                         you know more) */
1777         struct sip_st_dlg *stimer;              /*!< SIP Session-Timers */              
1778   
1779         int red;                                /*!< T.140 RTP Redundancy */
1780         int hangupcause;                        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
1781
1782         struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
1783 }; 
1784
1785
1786 /*! \brief
1787  * Here we implement the container for dialogs (sip_pvt), defining
1788  * generic wrapper functions to ease the transition from the current
1789  * implementation (a single linked list) to a different container.
1790  * In addition to a reference to the container, we need functions to lock/unlock
1791  * the container and individual items, and functions to add/remove
1792  * references to the individual items.
1793  */
1794 struct ao2_container *dialogs;
1795
1796 #define sip_pvt_lock(x) ao2_lock(x)
1797 #define sip_pvt_trylock(x) ao2_trylock(x)
1798 #define sip_pvt_unlock(x) ao2_unlock(x)
1799
1800 /*! \brief
1801  * when we create or delete references, make sure to use these
1802  * functions so we keep track of the refcounts.
1803  * To simplify the code, we allow a NULL to be passed to dialog_unref().
1804  */
1805 #ifdef REF_DEBUG
1806 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1807 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1808
1809 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1810 {
1811         if (p)
1812                 _ao2_ref_debug(p, 1, tag, file, line, func);
1813         else
1814                 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1815         return p;
1816 }
1817
1818 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1819 {
1820         if (p)
1821                 _ao2_ref_debug(p, -1, tag, file, line, func);
1822         return NULL;
1823 }
1824 #else
1825 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
1826 {
1827         if (p)
1828                 ao2_ref(p, 1);
1829         else
1830                 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1831         return p;
1832 }
1833
1834 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
1835 {
1836         if (p)
1837                 ao2_ref(p, -1);
1838         return NULL;
1839 }
1840 #endif
1841
1842 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1843  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1844  * Each packet holds a reference to the parent struct sip_pvt.
1845  * This structure is allocated in __sip_reliable_xmit() and only for packets that
1846  * require retransmissions.
1847  */
1848 struct sip_pkt {
1849         struct sip_pkt *next;                   /*!< Next packet in linked list */
1850         int retrans;                            /*!< Retransmission number */
1851         int method;                             /*!< SIP method for this packet */
1852         int seqno;                              /*!< Sequence number */
1853         char is_resp;                           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1854         char is_fatal;                          /*!< non-zero if there is a fatal error */
1855         struct sip_pvt *owner;                  /*!< Owner AST call */
1856         int retransid;                          /*!< Retransmission ID */
1857         int timer_a;                            /*!< SIP timer A, retransmission timer */
1858         int timer_t1;                           /*!< SIP Timer T1, estimated RTT or 500 ms */
1859         int packetlen;                          /*!< Length of packet */
1860         struct ast_str *data;
1861 };      
1862
1863 /*!
1864  * \brief A peer's mailbox
1865  *
1866  * We could use STRINGFIELDS here, but for only two strings, it seems like
1867  * too much effort ...
1868  */
1869 struct sip_mailbox {
1870         char *mailbox;
1871         char *context;
1872         /*! Associated MWI subscription */
1873         struct ast_event_sub *event_sub;
1874         AST_LIST_ENTRY(sip_mailbox) entry;
1875 };
1876
1877 enum sip_peer_type {
1878         SIP_TYPE_PEER = (1 << 0),
1879         SIP_TYPE_USER = (1 << 1),
1880 };
1881
1882 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
1883 */
1884 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
1885 struct sip_peer {
1886         char name[80];                                  /*!< the unique name of this object */
1887         AST_DECLARE_STRING_FIELDS(
1888                 AST_STRING_FIELD(secret);               /*!< Password for inbound auth */
1889                 AST_STRING_FIELD(md5secret);            /*!< Password in MD5 */
1890                 AST_STRING_FIELD(remotesecret);         /*!< Remote secret (trunks, remote devices) */
1891                 AST_STRING_FIELD(context);              /*!< Default context for incoming calls */
1892                 AST_STRING_FIELD(subscribecontext);     /*!< Default context for subscriptions */
1893                 AST_STRING_FIELD(username);             /*!< Temporary username until registration */ 
1894                 AST_STRING_FIELD(accountcode);          /*!< Account code */
1895                 AST_STRING_FIELD(tohost);               /*!< If not dynamic, IP address */
1896                 AST_STRING_FIELD(regexten);             /*!< Extension to register (if regcontext is used) */
1897                 AST_STRING_FIELD(fromuser);             /*!< From: user when calling this peer */
1898                 AST_STRING_FIELD(fromdomain);           /*!< From: domain when calling this peer */
1899                 AST_STRING_FIELD(fullcontact);          /*!< Contact registered with us (not in sip.conf) */
1900                 AST_STRING_FIELD(cid_num);              /*!< Caller ID num */
1901                 AST_STRING_FIELD(cid_name);             /*!< Caller ID name */
1902                 AST_STRING_FIELD(vmexten);              /*!< Dialplan extension for MWI notify message*/
1903                 AST_STRING_FIELD(language);             /*!<  Default language for prompts */
1904                 AST_STRING_FIELD(mohinterpret);         /*!<  Music on Hold class */
1905                 AST_STRING_FIELD(mohsuggest);           /*!<  Music on Hold class */
1906                 AST_STRING_FIELD(parkinglot);           /*!<  Parkinglot */
1907                 AST_STRING_FIELD(useragent);            /*!<  User agent in SIP request (saved from registration) */
1908                 AST_STRING_FIELD(mwi_from);         /*!< Name to place in From header for outgoing NOTIFY requests */
1909                 AST_STRING_FIELD(engine);               /*!<  RTP Engine to use */
1910                 );
1911         struct sip_socket socket;       /*!< Socket used for this peer */
1912         unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
1913         struct sip_auth *auth;          /*!< Realm authentication list */
1914         int amaflags;                   /*!< AMA Flags (for billing) */
1915         int callingpres;                /*!< Calling id presentation */
1916         int inUse;                      /*!< Number of calls in use */
1917         int inRinging;                  /*!< Number of calls ringing */
1918         int onHold;                     /*!< Peer has someone on hold */
1919         int call_limit;                 /*!< Limit of concurrent calls */
1920         int busy_level;                 /*!< Level of active channels where we signal busy */
1921         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1922         struct ast_codec_pref prefs;    /*!<  codec prefs */
1923         int lastmsgssent;
1924         unsigned int sipoptions;        /*!<  Supported SIP options */
1925         struct ast_flags flags[2];      /*!<  SIP_ flags */
1926         
1927         /*! Mailboxes that this peer cares about */
1928         AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1929
1930         /* things that don't belong in flags */
1931         char is_realtime;               /*!< this is a 'realtime' peer */
1932         char rt_fromcontact;            /*!< copy fromcontact from realtime */
1933         char host_dynamic;              /*!< Dynamic Peers register with Asterisk */
1934         char selfdestruct;              /*!< Automatic peers need to destruct themselves */
1935         char the_mark;                  /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
1936
1937         int expire;                     /*!<  When to expire this peer registration */
1938         int capability;                 /*!<  Codec capability */
1939         int rtptimeout;                 /*!<  RTP timeout */
1940         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
1941         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
1942         ast_group_t callgroup;          /*!<  Call group */
1943         ast_group_t pickupgroup;        /*!<  Pickup group */
1944         struct sip_proxy *outboundproxy;        /*!< Outbound proxy for this peer */
1945         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
1946         struct sockaddr_in addr;        /*!<  IP address of peer */
1947         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1948         
1949         /* Qualification */
1950         struct sip_pvt *call;           /*!<  Call pointer */
1951         int pokeexpire;                 /*!<  When to expire poke (qualify= checking) */
1952         int lastms;                     /*!<  How long last response took (in ms), or -1 for no response */
1953         int maxms;                      /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
1954         int qualifyfreq;                /*!<  Qualification: How often to check for the host to be up */
1955         struct timeval ps;              /*!<  Time for sending SIP OPTION in sip_pke_peer() */
1956         struct sockaddr_in defaddr;     /*!<  Default IP address, used until registration */
1957         struct ast_ha *ha;              /*!<  Access control list */
1958         struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
1959         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
1960         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
1961         int autoframing;
1962         struct sip_st_cfg stimer;       /*!<  SIP Session-Timers */
1963         int timer_t1;                   /*!<  The maximum T1 value for the peer */
1964         int timer_b;                    /*!<  The maximum timer B (transaction timeouts) */
1965         int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1966         
1967         /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
1968         enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
1969 };
1970
1971
1972 /*! 
1973  * \brief Registrations with other SIP proxies
1974  *
1975  * Created by sip_register(), the entry is linked in the 'regl' list,
1976  * and never deleted (other than at 'sip reload' or module unload times).
1977  * The entry always has a pending timeout, either waiting for an ACK to
1978  * the REGISTER message (in which case we have to retransmit the request),
1979  * or waiting for the next REGISTER message to be sent (either the initial one,
1980  * or once the previously completed registration one expires).
1981  * The registration can be in one of many states, though at the moment
1982  * the handling is a bit mixed.
1983  *
1984  * XXX \todo Reference count handling for this object has some problems with
1985  * respect to scheduler entries.  The ref count is handled in some places,
1986  * but not all of them.  There are some places where references get leaked
1987  * when this scheduler entry gets cancelled.  At worst, this would cause
1988  * memory leaks on reloads if registrations get removed from configuration.
1989  */
1990 struct sip_registry {
1991         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1992         AST_DECLARE_STRING_FIELDS(
1993                 AST_STRING_FIELD(callid);       /*!< Global Call-ID */
1994                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1995                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1996                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1997                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1998                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1999                 AST_STRING_FIELD(username);     /*!< Who we are registering as */
2000                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
2001                 AST_STRING_FIELD(hostname);     /*!< Domain or host we register to */
2002                 AST_STRING_FIELD(secret);       /*!< Password in clear text */  
2003                 AST_STRING_FIELD(md5secret);    /*!< Password in md5 */
2004                 AST_STRING_FIELD(callback);     /*!< Contact extension */
2005                 AST_STRING_FIELD(random);
2006         );
2007         enum sip_transport transport;   /*!< Transport for this registration UDP, TCP or TLS */
2008         int portno;                     /*!<  Optional port override */
2009         int expire;                     /*!< Sched ID of expiration */
2010         int expiry;                     /*!< Value to use for the Expires header */
2011         int regattempts;                /*!< Number of attempts (since the last success) */
2012         int timeout;                    /*!< sched id of sip_reg_timeout */
2013         int refresh;                    /*!< How often to refresh */
2014         struct sip_pvt *call;           /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
2015         enum sipregistrystate regstate; /*!< Registration state (see above) */
2016         struct timeval regtime;         /*!< Last successful registration time */
2017         int callid_valid;               /*!< 0 means we haven't chosen callid for this registry yet. */
2018         unsigned int ocseq;             /*!< Sequence number we got to for REGISTERs for this registry */
2019         struct ast_dnsmgr_entry *dnsmgr;        /*!<  DNS refresh manager for register */
2020         struct sockaddr_in us;          /*!< Who the server thinks we are */
2021         int noncecount;                 /*!< Nonce-count */
2022         char lastmsg[256];              /*!< Last Message sent/received */
2023 };
2024
2025 /*! \brief Definition of a thread that handles a socket */
2026 struct sip_threadinfo {
2027         int stop;
2028         pthread_t threadid;
2029         struct ast_tcptls_session_instance *tcptls_session;
2030         enum sip_transport type;        /*!< We keep a copy of the type here so we can display it in the connection list */
2031         AST_LIST_ENTRY(sip_threadinfo) list;
2032 };
2033
2034 /*! \brief Definition of an MWI subscription to another server */
2035 struct sip_subscription_mwi {
2036         ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
2037         AST_DECLARE_STRING_FIELDS(
2038                 AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
2039                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
2040                 AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
2041                 AST_STRING_FIELD(secret);       /*!< Password in clear text */
2042                 AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
2043                 );
2044         enum sip_transport transport;    /*!< Transport to use */
2045         int portno;                      /*!< Optional port override */
2046         int resub;                       /*!< Sched ID of resubscription */
2047         unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
2048         struct sip_pvt *call;            /*!< Outbound subscription dialog */
2049         struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
2050         struct sockaddr_in us;           /*!< Who the server thinks we are */
2051 };
2052
2053 /* --- Hash tables of various objects --------*/
2054
2055 #ifdef LOW_MEMORY
2056 static int hash_peer_size = 17;
2057 static int hash_dialog_size = 17;
2058 static int hash_user_size = 17;
2059 #else
2060 static int hash_peer_size = 563;        /*!< Size of peer hash table, prime number preferred! */
2061 static int hash_dialog_size = 563;
2062 static int hash_user_size = 563;
2063 #endif
2064
2065 /*! \brief  The thread list of TCP threads */
2066 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
2067
2068 /*! \brief  The peer list: Users, Peers and Friends */
2069 struct ao2_container *peers;
2070 struct ao2_container *peers_by_ip;
2071
2072 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
2073 static struct ast_register_list {
2074         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
2075         int recheck;
2076 } regl;
2077
2078 /*! \brief  The MWI subscription list */
2079 static struct ast_subscription_mwi_list {
2080         ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
2081 } submwil;
2082
2083 /*! \brief
2084  * \note The only member of the peer used here is the name field
2085  */
2086 static int peer_hash_cb(const void *obj, const int flags)
2087 {
2088         const struct sip_peer *peer = obj;
2089
2090         return ast_str_case_hash(peer->name);
2091 }
2092
2093 /*!
2094  * \note The only member of the peer used here is the name field
2095  */
2096 static int peer_cmp_cb(void *obj, void *arg, int flags)
2097 {
2098         struct sip_peer *peer = obj, *peer2 = arg;
2099
2100         return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
2101 }
2102
2103 /*!
2104  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
2105  */
2106 static int peer_iphash_cb(const void *obj, const int flags)
2107 {
2108         const struct sip_peer *peer = obj;
2109         int ret1 = peer->addr.sin_addr.s_addr;
2110         if (ret1 < 0)
2111                 ret1 = -ret1;
2112         
2113         if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
2114                 return ret1;
2115         } else {
2116                 return ret1 + peer->addr.sin_port;
2117         }
2118 }
2119
2120 /*!
2121  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
2122  */
2123 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
2124 {
2125         struct sip_peer *peer = obj, *peer2 = arg;
2126
2127         if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr)
2128                 return 0;
2129         
2130         if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
2131                 if (peer->addr.sin_port == peer2->addr.sin_port)
2132                         return CMP_MATCH | CMP_STOP;
2133                 else
2134                         return 0;
2135         }
2136         return CMP_MATCH | CMP_STOP;
2137 }
2138
2139 /*!
2140  * \note The only member of the dialog used here callid string
2141  */
2142 static int dialog_hash_cb(const void *obj, const int flags)
2143 {
2144         const struct sip_pvt *pvt = obj;
2145
2146         return ast_str_case_hash(pvt->callid);
2147 }
2148
2149 /*!
2150  * \note The only member of the dialog used here callid string
2151  */
2152 static int dialog_cmp_cb(void *obj, void *arg, int flags)
2153 {
2154         struct sip_pvt *pvt = obj, *pvt2 = arg;
2155         
2156         return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
2157 }
2158
2159 static int temp_pvt_init(void *);
2160 static void temp_pvt_cleanup(void *);
2161
2162 /*! \brief A per-thread temporary pvt structure */
2163 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
2164
2165 #ifdef LOW_MEMORY
2166 static void ts_ast_rtp_destroy(void *);
2167
2168 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
2169 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
2170 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
2171 #endif
2172
2173 /*! \brief Authentication list for realm authentication 
2174  * \todo Move the sip_auth list to AST_LIST */
2175 static struct sip_auth *authl = NULL;
2176
2177
2178 /* --- Sockets and networking --------------*/
2179
2180 /*! \brief Main socket for UDP SIP communication.
2181  *
2182  * sipsock is shared between the SIP manager thread (which handles reload
2183  * requests), the udp io handler (sipsock_read()) and the user routines that
2184  * issue udp writes (using __sip_xmit()).
2185  * The socket is -1 only when opening fails (this is a permanent condition),
2186  * or when we are handling a reload() that changes its address (this is
2187  * a transient situation during which we might have a harmless race, see
2188  * below). Because the conditions for the race to be possible are extremely
2189  * rare, we don't want to pay the cost of locking on every I/O.
2190  * Rather, we remember that when the race may occur, communication is
2191  * bound to fail anyways, so we just live with this event and let
2192  * the protocol handle this above us.
2193  */
2194 static int sipsock  = -1;
2195
2196 static struct sockaddr_in bindaddr;     /*!< UDP: The address we bind to */
2197
2198 /*! \brief our (internal) default address/port to put in SIP/SDP messages
2199  *  internip is initialized picking a suitable address from one of the
2200  * interfaces, and the same port number we bind to. It is used as the
2201  * default address/port in SIP messages, and as the default address
2202  * (but not port) in SDP messages.
2203  */
2204 static struct sockaddr_in internip;
2205
2206 /*! \brief our external IP address/port for SIP sessions.
2207  * externip.sin_addr is only set when we know we might be behind
2208  * a NAT, and this is done using a variety of (mutually exclusive)
2209  * ways from the config file:
2210  *
2211  * + with "externip = host[:port]" we specify the address/port explicitly.
2212  *   The address is looked up only once when (re)loading the config file;
2213  * 
2214  * + with "externhost = host[:port]" we do a similar thing, but the
2215  *   hostname is stored in externhost, and the hostname->IP mapping
2216  *   is refreshed every 'externrefresh' seconds;
2217  * 
2218  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
2219  *   to the specified server, and store the result in externip.
2220  *
2221  * Other variables (externhost, externexpire, externrefresh) are used
2222  * to support the above functions.
2223  */
2224 static struct sockaddr_in externip;             /*!< External IP address if we are behind NAT */
2225
2226 static char externhost[MAXHOSTNAMELEN];         /*!< External host name */
2227 static time_t externexpire;                     /*!< Expiration counter for re-resolving external host name in dynamic DNS */
2228 static int externrefresh = 10;
2229 static struct sockaddr_in stunaddr;             /*!< stun server address */
2230
2231 /*! \brief  List of local networks
2232  * We store "localnet" addresses from the config file into an access list,
2233  * marked as 'DENY', so the call to ast_apply_ha() will return
2234  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
2235  * (i.e. presumably public) addresses.
2236  */
2237 static struct ast_ha *localaddr;                /*!< List of local networks, on the same side of NAT as this Asterisk */
2238
2239 static int ourport_tcp;                         /*!< The port used for TCP connections */
2240 static int ourport_tls;                         /*!< The port used for TCP/TLS connections */
2241 static struct sockaddr_in debugaddr;
2242
2243 static struct ast_config *notify_types;         /*!< The list of manual NOTIFY types we know how to send */
2244
2245 /*! some list management macros. */
2246  
2247 #define UNLINK(element, head, prev) do {        \
2248         if (prev)                               \
2249                 (prev)->next = (element)->next; \
2250         else                                    \
2251                 (head) = (element)->next;       \
2252         } while (0)
2253
2254 enum t38_action_flag {
2255         SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
2256         SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
2257         SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
2258 };
2259
2260 /*---------------------------- Forward declarations of functions in chan_sip.c */
2261 /* Note: This is added to help splitting up chan_sip.c into several files
2262         in coming releases. */
2263
2264 /*--- PBX interface functions */
2265 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
2266 static int sip_devicestate(void *data);
2267 static int sip_sendtext(struct ast_channel *ast, const char *text);
2268 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
2269 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
2270 static int sip_hangup(struct ast_channel *ast);
2271 static int sip_answer(struct ast_channel *ast);
2272 static struct ast_frame *sip_read(struct ast_channel *ast);
2273 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
2274 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
2275 static int sip_transfer(struct ast_channel *ast, const char *dest);
2276 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
2277 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
2278 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
2279 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
2280 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
2281 static const char *sip_get_callid(struct ast_channel *chan);
2282
2283 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
2284 static int sip_standard_port(enum sip_transport type, int port);
2285 static int sip_prepare_socket(struct sip_pvt *p);
2286 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
2287
2288 /*--- Transmitting responses and requests */
2289 static int sipsock_read(int *id, int fd, short events, void *ignore);
2290 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
2291 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
2292 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
2293 static int retrans_pkt(const void *data);
2294 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
2295 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
2296 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
2297 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
2298 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
2299 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
2300 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
2301 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
2302 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
2303 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
2304 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
2305 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
2306 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
2307 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
2308 static int transmit_info_with_vidupdate(struct sip_pvt *p);
2309 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
2310 static int transmit_refer(struct sip_pvt *p, const char *dest);
2311 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
2312 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
2313 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
2314 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
2315 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
2316 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
2317 static void copy_request(struct sip_request *dst, const struct sip_request *src);
2318 static void receive_message(struct sip_pvt *p, struct sip_request *req);
2319 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
2320 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
2321
2322 /*--- Dialog management */
2323 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
2324                                  int useglobal_nat, const int intended_method);
2325 static int __sip_autodestruct(const void *data);
2326 static void sip_scheddestroy(struct sip_pvt *p, int ms);
2327 static int sip_cancel_destroy(struct sip_pvt *p);
2328 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
2329 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
2330 static void *registry_unref(struct sip_registry *reg, char *tag);
2331 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
2332 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
2333 static void __sip_pretend_ack(struct sip_pvt *p);
2334 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
2335 static int auto_congest(const void *arg);
2336 static int update_call_counter(struct sip_pvt *fup, int event);
2337 static int hangup_sip2cause(int cause);
2338 static const char *hangup_cause2sip(int cause);
2339 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
2340 static void free_old_route(struct sip_route *route);
2341 static void list_route(struct sip_route *route);
2342 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
2343 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
2344                                               struct sip_request *req, char *uri);
2345 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
2346 static void check_pendings(struct sip_pvt *p);
2347 static void *sip_park_thread(void *stuff);
2348 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
2349 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
2350
2351 /*--- Codec handling / SDP */
2352 static void try_suggested_sip_codec(struct sip_pvt *p);
2353 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
2354 static const char *get_sdp(struct sip_request *req, const char *name);
2355 static int find_sdp(struct sip_request *req);
2356 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
2357 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
2358                              struct ast_str **m_buf, struct ast_str **a_buf,
2359                              int debug, int *min_packet_size);
2360 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
2361                                 struct ast_str **m_buf, struct ast_str **a_buf,
2362                                 int debug);
2363 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
2364 static void do_setnat(struct sip_pvt *p, int natflags);
2365 static void stop_media_flows(struct sip_pvt *p);
2366
2367 /*--- Authentication stuff */
2368 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
2369 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
2370 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
2371                                          const char *secret, const char *md5secret, int sipmethod,
2372                                          char *uri, enum xmittype reliable, int ignore);
2373 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
2374                                               int sipmethod, char *uri, enum xmittype reliable,
2375                                               struct sockaddr_in *sin, struct sip_peer **authpeer);
2376 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
2377
2378 /*--- Domain handling */
2379 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
2380 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
2381 static void clear_sip_domains(void);
2382
2383 /*--- SIP realm authentication */
2384 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
2385 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
2386 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
2387
2388 /*--- Misc functions */
2389 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
2390 static int sip_do_reload(enum channelreloadreason reason);
2391 static int reload_config(enum channelreloadreason reason);
2392 static int expire_register(const void *data);
2393 static void *do_monitor(void *data);
2394 static int restart_monitor(void);
2395 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
2396 static struct ast_variable *copy_vars(struct ast_variable *src);
2397 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
2398 static int sip_refer_allocate(struct sip_pvt *p);
2399 static void ast_quiet_chan(struct ast_channel *chan);
2400 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
2401 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
2402
2403 /*!
2404  * \brief generic function for determining if a correct transport is being 
2405  * used to contact a peer
2406  *
2407  * this is done as a macro so that the "tmpl" var can be passed either a 
2408  * sip_request or a sip_peer 
2409  */
2410 #define check_request_transport(peer, tmpl) ({ \
2411         int ret = 0; \
2412         if (peer->socket.type == tmpl->socket.type) \
2413                 ; \
2414         else if (!(peer->transports & tmpl->socket.type)) {\
2415                 ast_log(LOG_ERROR, \
2416                         "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2417                         get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2418                         ); \
2419                 ret = 1; \
2420         } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2421                 ast_log(LOG_WARNING, \
2422                         "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2423                         peer->name, get_transport(tmpl->socket.type) \
2424                 ); \
2425         } else { \
2426                 ast_debug(1, \
2427                         "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2428                         peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2429                 ); \
2430         }\
2431         (ret); \
2432 })
2433
2434
2435 /*--- Device monitoring and Device/extension state/event handling */
2436 static int cb_extensionstate(char *context, char* exten, int state, void *data);
2437 static int sip_devicestate(void *data);
2438 static int sip_poke_noanswer(const void *data);
2439 static int sip_poke_peer(struct sip_peer *peer, int force);
2440 static void sip_poke_all_peers(void);
2441 static void sip_peer_hold(struct sip_pvt *p, int hold);
2442 static void mwi_event_cb(const struct ast_event *, void *);
2443
2444 /*--- Applications, functions, CLI and manager command helpers */
2445 static const char *sip_nat_mode(const struct sip_pvt *p);
2446 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2447 static char *transfermode2str(enum transfermodes mode) attribute_const;
2448 static const char *nat2str(int nat) attribute_const;
2449 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
2450 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2451 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2452 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2453 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2454 static void  print_group(int fd, ast_group_t group, int crlf);
2455 static const char *dtmfmode2str(int mode) attribute_const;
2456 static int str2dtmfmode(const char *str) attribute_unused;
2457 static const char *insecure2str(int mode) attribute_const;
2458 static void cleanup_stale_contexts(char *new, char *old);
2459 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
2460 static const char *domain_mode_to_text(const enum domain_mode mode);
2461 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2462 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2463 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2464 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2465 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2466 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2467 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2468 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2469 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2470 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
2471 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2472 static char *complete_sip_peer(const char *word, int state, int flags2);
2473 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
2474 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
2475 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
2476 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
2477 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
2478 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2479 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2480 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2481 static char *sip_do_debug_ip(int fd, char *arg);
2482 static char *sip_do_debug_peer(int fd, char *arg);
2483 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2484 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2485 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2486 static int sip_dtmfmode(struct ast_channel *chan, void *data);
2487 static int sip_addheader(struct ast_channel *chan, void *data);
2488 static int sip_do_reload(enum channelreloadreason reason);
2489 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2490 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
2491
2492 /*--- Debugging 
2493         Functions for enabling debug per IP or fully, or enabling history logging for
2494         a SIP dialog
2495 */
2496 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to debuglog at end of dialog, before destroying data */
2497 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
2498 static inline int sip_debug_test_pvt(struct sip_pvt *p);
2499
2500
2501 /*! \brief Append to SIP dialog history 
2502         \return Always returns 0 */
2503 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
2504 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
2505 static void sip_dump_history(struct sip_pvt *dialog);
2506
2507 /*--- Device object handling */
2508 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
2509 static int update_call_counter(struct sip_pvt *fup, int event);
2510 static void sip_destroy_peer(struct sip_peer *peer);
2511 static void sip_destroy_peer_fn(void *peer);
2512 static void set_peer_defaults(struct sip_peer *peer);
2513 static struct sip_peer *temp_peer(const char *name);
2514 static void register_peer_exten(struct sip_peer *peer, int onoff);
2515 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only);
2516 static int sip_poke_peer_s(const void *data);
2517 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
2518 static void reg_source_db(struct sip_peer *peer);
2519 static void destroy_association(struct sip_peer *peer);
2520 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
2521 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
2522
2523 /* Realtime device support */
2524 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms);
2525 static void update_peer(struct sip_peer *p, int expire);
2526 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
2527 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
2528 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
2529 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2530
2531 /*--- Internal UA client handling (outbound registrations) */
2532 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
2533 static void sip_registry_destroy(struct sip_registry *reg);
2534 static int sip_register(const char *value, int lineno);
2535 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
2536 static int sip_reregister(const void *data);
2537 static int __sip_do_register(struct sip_registry *r);
2538 static int sip_reg_timeout(const void *data);
2539 static void sip_send_all_registers(void);
2540 static int sip_reinvite_retry(const void *data);
2541
2542 /*--- Parsing SIP requests and responses */
2543 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
2544 static int determine_firstline_parts(struct sip_request *req);
2545 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2546 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
2547 static int find_sip_method(const char *msg);
2548 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
2549 static int parse_request(struct sip_request *req);
2550 static const char *get_header(const struct sip_request *req, const char *name);
2551 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
2552 static int method_match(enum sipmethod id, const char *name);
2553 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
2554 static char *get_in_brackets(char *tmp);
2555 static const char *find_alias(const char *name, const char *_default);
2556 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
2557 static int lws2sws(char *msgbuf, int len);
2558 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
2559 static char *remove_uri_parameters(char *uri);
2560 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
2561 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
2562 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
2563 static int set_address_from_contact(struct sip_pvt *pvt);
2564 static void check_via(struct sip_pvt *p, struct sip_request *req);
2565 static char *get_calleridname(const char *input, char *output, size_t outputsize);
2566 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
2567 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
2568 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
2569 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
2570 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
2571 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
2572 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
2573 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);
2574
2575 /*-- TCP connection handling ---*/
2576 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
2577 static void *sip_tcp_worker_fn(void *);
2578
2579 /*--- Constructing requests and responses */
2580 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
2581 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
2582 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
2583 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
2584 static int init_resp(struct sip_request *resp, const char *msg);
2585 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
2586 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
2587 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
2588 static void build_via(struct sip_pvt *p);
2589 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
2590 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
2591 static char *generate_random_string(char *buf, size_t size);
2592 static void build_callid_pvt(struct sip_pvt *pvt);
2593 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
2594 static void make_our_tag(char *tagbuf, size_t len);
2595 static int add_header(struct sip_request *req, const char *var, const char *value);
2596 static int add_header_contentLength(struct sip_request *req, int len);
2597 static int add_line(struct sip_request *req, const char *line);
2598 static int add_text(struct sip_request *req, const char *text);
2599 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
2600 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
2601 static int add_vidupdate(struct sip_request *req);
2602 static void add_route(struct sip_request *req, struct sip_route *route);
2603 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2604 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2605 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
2606 static void set_destination(struct sip_pvt *p, char *uri);
2607 static void append_date(struct sip_request *req);
2608 static void build_contact(struct sip_pvt *p);
2609
2610 /*------Request handling functions */
2611 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
2612 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
2613 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
2614 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
2615 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
2616 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
2617 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
2618 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2619 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
2620 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
2621 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
2622 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2623 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
2624
2625 /*------Response handling functions */
2626 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2627 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2628 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2629 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2630 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2631 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2632
2633 /*------ T38 Support --------- */
2634 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
2635 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
2636 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
2637 static void change_t38_state(struct sip_pvt *p, int state);
2638
2639 /*------ Session-Timers functions --------- */
2640 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
2641 static int  proc_session_timer(const void *vp);
2642 static void stop_session_timer(struct sip_pvt *p);
2643 static void start_session_timer(struct sip_pvt *p);
2644 static void restart_session_timer(struct sip_pvt *p);
2645 static const char *strefresher2str(enum st_refresher r);
2646 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
2647 static int parse_minse(const char *p_hdrval, int *const p_interval);
2648 static int st_get_se(struct sip_pvt *, int max);
2649 static enum st_refresher st_get_refresher(struct sip_pvt *);
2650 static enum st_mode st_get_mode(struct sip_pvt *);
2651 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
2652
2653 /*------- RTP Glue functions -------- */
2654 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, int codecs, int nat_active);
2655
2656 /*!--- SIP MWI Subscription support */
2657 static int sip_subscribe_mwi(const char *value, int lineno);
2658 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
2659 static void sip_send_all_mwi_subscriptions(void);
2660 static int sip_subscribe_mwi_do(const void *data);
2661 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
2662
2663 /*! \brief Definition of this channel for PBX channel registration */
2664 static const struct ast_channel_tech sip_tech = {
2665         .type = "SIP",
2666         .description = "Session Initiation Protocol (SIP)",
2667         .capabilities = AST_FORMAT_AUDIO_MASK,  /* all audio formats */
2668         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
2669         .requester = sip_request_call,                  /* called with chan unlocked */
2670         .devicestate = sip_devicestate,                 /* called with chan unlocked (not chan-specific) */
2671         .call = sip_call,                       /* called with chan locked */
2672         .send_html = sip_sendhtml,
2673         .hangup = sip_hangup,                   /* called with chan locked */
2674         .answer = sip_answer,                   /* called with chan locked */
2675         .read = sip_read,                       /* called with chan locked */
2676         .write = sip_write,                     /* called with chan locked */
2677         .write_video = sip_write,               /* called with chan locked */
2678         .write_text = sip_write,
2679         .indicate = sip_indicate,               /* called with chan locked */
2680         .transfer = sip_transfer,               /* called with chan locked */
2681         .fixup = sip_fixup,                     /* called with chan locked */
2682         .send_digit_begin = sip_senddigit_begin,        /* called with chan unlocked */
2683         .send_digit_end = sip_senddigit_end,
2684         .bridge = ast_rtp_instance_bridge,                      /* XXX chan unlocked ? */
2685         .early_bridge = ast_rtp_instance_early_bridge,
2686         .send_text = sip_sendtext,              /* called with chan locked */
2687         .func_channel_read = acf_channel_read,
2688         .setoption = sip_setoption,
2689         .queryoption = sip_queryoption,
2690         .get_pvt_uniqueid = sip_get_callid,
2691 };
2692
2693 /*! \brief This version of the sip channel tech has no send_digit_begin
2694  * callback so that the core knows that the channel does not want
2695  * DTMF BEGIN frames.
2696  * The struct is initialized just before registering the channel driver,
2697  * and is for use with channels using SIP INFO DTMF.
2698  */
2699 static struct ast_channel_tech sip_tech_info;
2700
2701
2702 /*! \brief Working TLS connection configuration */
2703 static struct ast_tls_config sip_tls_cfg;
2704
2705 /*! \brief Default TLS connection configuration */
2706 static struct ast_tls_config default_tls_cfg;
2707
2708 /*! \brief The TCP server definition */
2709 static struct ast_tcptls_session_args sip_tcp_desc = {
2710         .accept_fd = -1,
2711         .master = AST_PTHREADT_NULL,
2712         .tls_cfg = NULL,
2713         .poll_timeout = -1,
2714         .name = "SIP TCP server",
2715         .accept_fn = ast_tcptls_server_root,
2716         .worker_fn = sip_tcp_worker_fn,
2717 };
2718
2719 /*! \brief The TCP/TLS server definition */
2720 static struct ast_tcptls_session_args sip_tls_desc = {
2721         .accept_fd = -1,
2722         .master = AST_PTHREADT_NULL,
2723         .tls_cfg = &sip_tls_cfg,
2724         .poll_timeout = -1,
2725         .name = "SIP TLS server",
2726         .accept_fn = ast_tcptls_server_root,
2727         .worker_fn = sip_tcp_worker_fn,
2728 };
2729
2730 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
2731 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
2732
2733 /*! \brief map from an integer value to a string.
2734  * If no match is found, return errorstring
2735  */
2736 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2737 {
2738         const struct _map_x_s *cur;
2739
2740         for (cur = table; cur->s; cur++)
2741                 if (cur->x == x)
2742                         return cur->s;
2743         return errorstring;
2744 }
2745
2746 /*! \brief map from a string to an integer value, case insensitive.
2747  * If no match is found, return errorvalue.
2748  */
2749 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2750 {
2751         const struct _map_x_s *cur;
2752
2753         for (cur = table; cur->s; cur++)
2754                 if (!strcasecmp(cur->s, s))
2755                         return cur->x;
2756         return errorvalue;
2757 }
2758
2759 /*!
2760  * duplicate a list of channel variables, \return the copy.
2761  */
2762 static struct ast_variable *copy_vars(struct ast_variable *src)
2763 {
2764         struct ast_variable *res = NULL, *tmp, *v = NULL;
2765
2766         for (v = src ; v ; v = v->next) {
2767                 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2768                         tmp->next = res;
2769                         res = tmp;
2770                 }
2771         }
2772         return res;
2773 }
2774
2775 /*! \brief SIP TCP connection handler */
2776 static void *sip_tcp_worker_fn(void *data)
2777 {
2778         struct ast_tcptls_session_instance *tcptls_session = data;
2779
2780         return _sip_tcp_helper_thread(NULL, tcptls_session);
2781 }
2782
2783 /*! \brief SIP TCP thread management function 
2784         This function reads from the socket, parses the packet into a request
2785 */
2786 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
2787 {
2788         int res, cl;
2789         struct sip_request req = { 0, } , reqcpy = { 0, };
2790         struct sip_threadinfo *me;
2791         char buf[1024] = "";
2792
2793         me = ast_calloc(1, sizeof(*me));
2794
2795         if (!me)
2796                 goto cleanup2;
2797
2798         me->threadid = pthread_self();
2799         me->tcptls_session = tcptls_session;
2800         if (tcptls_session->ssl)
2801                 me->type = SIP_TRANSPORT_TLS;
2802         else
2803                 me->type = SIP_TRANSPORT_TCP;
2804
2805         ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2806
2807         AST_LIST_LOCK(&threadl);
2808         AST_LIST_INSERT_TAIL(&threadl, me, list);
2809         AST_LIST_UNLOCK(&threadl);
2810
2811         if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2812                 goto cleanup;
2813         if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2814                 goto cleanup;
2815
2816         for (;;) {
2817                 struct ast_str *str_save;
2818
2819                 str_save = req.data;
2820                 memset(&req, 0, sizeof(req));
2821                 req.data = str_save;
2822                 ast_str_reset(req.data);
2823
2824                 str_save = reqcpy.data;
2825                 memset(&reqcpy, 0, sizeof(reqcpy));
2826                 reqcpy.data = str_save;
2827                 ast_str_reset(reqcpy.data);
2828
2829                 req.socket.fd = tcptls_session->fd;
2830                 if (tcptls_session->ssl) {
2831                         req.socket.type = SIP_TRANSPORT_TLS;
2832                         req.socket.port = htons(ourport_tls);
2833                 } else {
2834                         req.socket.type = SIP_TRANSPORT_TCP;
2835                         req.socket.port = htons(ourport_tcp);
2836                 }
2837                 res = ast_wait_for_input(tcptls_session->fd, -1);
2838                 if (res < 0) {
2839                         ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2840                         goto cleanup;
2841                 }
2842
2843                 /* Read in headers one line at a time */
2844                 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2845                         ast_mutex_lock(&tcptls_session->lock);
2846                         if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2847                                 ast_mutex_unlock(&tcptls_session->lock);
2848                                 goto cleanup;
2849                         }
2850                         ast_mutex_unlock(&tcptls_session->lock);
2851                         if (me->stop) 
2852                                  goto cleanup;
2853                         ast_str_append(&req.data, 0, "%s", buf);
2854                         req.len = req.data->used;
2855                 }
2856                 copy_request(&reqcpy, &req);
2857                 parse_request(&reqcpy);
2858                 /* In order to know how much to read, we need the content-length header */
2859                 if (sscanf(get_header(&reqcpy, "Content-Length"), "%d", &cl)) {
2860                         while (cl > 0) {
2861                                 ast_mutex_lock(&tcptls_session->lock);
2862                                 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, tcptls_session->f)) {
2863                                         ast_mutex_unlock(&tcptls_session->lock);
2864                                         goto cleanup;
2865                                 }
2866                                 ast_mutex_unlock(&tcptls_session->lock);
2867                                 if (me->stop)
2868                                         goto cleanup;
2869                                 cl -= strlen(buf);
2870                                 ast_str_append(&req.data, 0, "%s", buf);
2871                                 req.len = req.data->used;
2872                         }
2873                 }
2874                 /*! \todo XXX If there's no Content-Length or if the content-length and what
2875                                 we receive is not the same - we should generate an error */
2876
2877                 req.socket.tcptls_session = tcptls_session;
2878                 handle_request_do(&req, &tcptls_session->remote_address);
2879         }
2880
2881 cleanup:
2882         AST_LIST_LOCK(&threadl);
2883         AST_LIST_REMOVE(&threadl, me, list);
2884         AST_LIST_UNLOCK(&threadl);
2885         ast_free(me);
2886 cleanup2:
2887         fclose(tcptls_session->f);
2888         tcptls_session->f = NULL;
2889         tcptls_session->fd = -1;
2890         if (reqcpy.data) {
2891                 ast_free(reqcpy.data);
2892         }
2893
2894         if (req.data) {
2895                 ast_free(req.data);
2896                 req.data = NULL;
2897         }
2898
2899         ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2900         
2901
2902         ao2_ref(tcptls_session, -1);
2903         tcptls_session = NULL;
2904
2905         return NULL;
2906 }
2907
2908
2909 /*!
2910  * helper functions to unreference various types of objects.
2911  * By handling them this way, we don't have to declare the
2912  * destructor on each call, which removes the chance of errors.
2913  */
2914 static void *unref_peer(struct sip_peer *peer, char *tag)
2915 {
2916         ao2_t_ref(peer, -1, tag);
2917         return NULL;
2918 }
2919
2920 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2921 {
2922         ao2_t_ref(peer, 1, tag);
2923         return peer;
2924 }
2925
2926 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2927  *
2928  * This function sets pvt's outboundproxy pointer to the one referenced
2929  * by the proxy parameter. Because proxy may be a refcounted object, and
2930  * because pvt's old outboundproxy may also be a refcounted object, we need
2931  * to maintain the proper refcounts.
2932  *
2933  * \param pvt The sip_pvt for which we wish to set the outboundproxy
2934  * \param proxy The sip_proxy which we will point pvt towards.
2935  * \return Returns void
2936  */
2937 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2938 {
2939         struct sip_proxy *old_obproxy = pvt->outboundproxy;
2940         /* The sip_cfg.outboundproxy is statically allocated, and so
2941          * we don't ever need to adjust refcounts for it