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