Make contactdeny apply to src ip when nat=yes
[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 #include <inttypes.h>
216
217 #include "asterisk/network.h"
218 #include "asterisk/paths.h"     /* need ast_config_AST_SYSTEM_NAME */
219 /*
220    Uncomment the define below,  if you are having refcount related memory leaks.
221    With this uncommented, this module will generate a file, /tmp/refs, which contains
222    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
223    be modified to ao2_t_* calls, and include a tag describing what is happening with
224    enough detail, to make pairing up a reference count increment with its corresponding decrement.
225    The refcounter program in utils/ can be invaluable in highlighting objects that are not
226    balanced, along with the complete history for that object.
227    In normal operation, the macros defined will throw away the tags, so they do not
228    affect the speed of the program at all. They can be considered to be documentation.
229 */
230 /* #define  REF_DEBUG 1 */
231 #include "asterisk/lock.h"
232 #include "asterisk/config.h"
233 #include "asterisk/module.h"
234 #include "asterisk/pbx.h"
235 #include "asterisk/sched.h"
236 #include "asterisk/io.h"
237 #include "asterisk/rtp_engine.h"
238 #include "asterisk/udptl.h"
239 #include "asterisk/acl.h"
240 #include "asterisk/manager.h"
241 #include "asterisk/callerid.h"
242 #include "asterisk/cli.h"
243 #include "asterisk/musiconhold.h"
244 #include "asterisk/dsp.h"
245 #include "asterisk/features.h"
246 #include "asterisk/srv.h"
247 #include "asterisk/astdb.h"
248 #include "asterisk/causes.h"
249 #include "asterisk/utils.h"
250 #include "asterisk/file.h"
251 #include "asterisk/astobj2.h"
252 #include "asterisk/dnsmgr.h"
253 #include "asterisk/devicestate.h"
254 #include "asterisk/monitor.h"
255 #include "asterisk/netsock.h"
256 #include "asterisk/localtime.h"
257 #include "asterisk/abstract_jb.h"
258 #include "asterisk/threadstorage.h"
259 #include "asterisk/translate.h"
260 #include "asterisk/ast_version.h"
261 #include "asterisk/event.h"
262 #include "asterisk/stun.h"
263 #include "asterisk/cel.h"
264 #include "asterisk/aoc.h"
265 #include "sip/include/sip.h"
266 #include "sip/include/globals.h"
267 #include "sip/include/config_parser.h"
268 #include "sip/include/reqresp_parser.h"
269 #include "sip/include/sip_utils.h"
270 #include "sip/include/srtp.h"
271 #include "sip/include/sdp_crypto.h"
272 #include "asterisk/ccss.h"
273 #include "asterisk/xml.h"
274 #include "sip/include/dialog.h"
275 #include "sip/include/dialplan_functions.h"
276
277
278 /*** DOCUMENTATION
279         <application name="SIPDtmfMode" language="en_US">
280                 <synopsis>
281                         Change the dtmfmode for a SIP call.
282                 </synopsis>
283                 <syntax>
284                         <parameter name="mode" required="true">
285                                 <enumlist>
286                                         <enum name="inband" />
287                                         <enum name="info" />
288                                         <enum name="rfc2833" />
289                                 </enumlist>
290                         </parameter>
291                 </syntax>
292                 <description>
293                         <para>Changes the dtmfmode for a SIP call.</para>
294                 </description>
295         </application>
296         <application name="SIPAddHeader" language="en_US">
297                 <synopsis>
298                         Add a SIP header to the outbound call.
299                 </synopsis>
300                 <syntax argsep=":">
301                         <parameter name="Header" required="true" />
302                         <parameter name="Content" required="true" />
303                 </syntax>
304                 <description>
305                         <para>Adds a header to a SIP call placed with DIAL.</para>
306                         <para>Remember to use the X-header if you are adding non-standard SIP
307                         headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
308                         Adding the wrong headers may jeopardize the SIP dialog.</para>
309                         <para>Always returns <literal>0</literal>.</para>
310                 </description>
311         </application>
312         <application name="SIPRemoveHeader" language="en_US">
313                 <synopsis>
314                         Remove SIP headers previously added with SIPAddHeader
315                 </synopsis>
316                 <syntax>
317                         <parameter name="Header" required="false" />
318                 </syntax>
319                 <description>
320                         <para>SIPRemoveHeader() allows you to remove headers which were previously
321                         added with SIPAddHeader(). If no parameter is supplied, all previously added
322                         headers will be removed. If a parameter is supplied, only the matching headers
323                         will be removed.</para>
324                         <para>For example you have added these 2 headers:</para>
325                         <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
326                         <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
327                         <para></para>
328                         <para>// remove all headers</para>
329                         <para>SIPRemoveHeader();</para>
330                         <para>// remove all P- headers</para>
331                         <para>SIPRemoveHeader(P-);</para>
332                         <para>// remove only the PAI header (note the : at the end)</para>
333                         <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
334                         <para></para>
335                         <para>Always returns <literal>0</literal>.</para>
336                 </description>
337         </application>
338         <function name="SIP_HEADER" language="en_US">
339                 <synopsis>
340                         Gets the specified SIP header.
341                 </synopsis>
342                 <syntax>
343                         <parameter name="name" required="true" />
344                         <parameter name="number">
345                                 <para>If not specified, defaults to <literal>1</literal>.</para>
346                         </parameter>
347                 </syntax>
348                 <description>
349                         <para>Since there are several headers (such as Via) which can occur multiple
350                         times, SIP_HEADER takes an optional second argument to specify which header with
351                         that name to retrieve. Headers start at offset <literal>1</literal>.</para>
352                 </description>
353         </function>
354         <function name="SIPPEER" language="en_US">
355                 <synopsis>
356                         Gets SIP peer information.
357                 </synopsis>
358                 <syntax>
359                         <parameter name="peername" required="true" />
360                         <parameter name="item">
361                                 <enumlist>
362                                         <enum name="ip">
363                                                 <para>(default) The ip address.</para>
364                                         </enum>
365                                         <enum name="port">
366                                                 <para>The port number.</para>
367                                         </enum>
368                                         <enum name="mailbox">
369                                                 <para>The configured mailbox.</para>
370                                         </enum>
371                                         <enum name="context">
372                                                 <para>The configured context.</para>
373                                         </enum>
374                                         <enum name="expire">
375                                                 <para>The epoch time of the next expire.</para>
376                                         </enum>
377                                         <enum name="dynamic">
378                                                 <para>Is it dynamic? (yes/no).</para>
379                                         </enum>
380                                         <enum name="callerid_name">
381                                                 <para>The configured Caller ID name.</para>
382                                         </enum>
383                                         <enum name="callerid_num">
384                                                 <para>The configured Caller ID number.</para>
385                                         </enum>
386                                         <enum name="callgroup">
387                                                 <para>The configured Callgroup.</para>
388                                         </enum>
389                                         <enum name="pickupgroup">
390                                                 <para>The configured Pickupgroup.</para>
391                                         </enum>
392                                         <enum name="codecs">
393                                                 <para>The configured codecs.</para>
394                                         </enum>
395                                         <enum name="status">
396                                                 <para>Status (if qualify=yes).</para>
397                                         </enum>
398                                         <enum name="regexten">
399                                                 <para>Registration extension.</para>
400                                         </enum>
401                                         <enum name="limit">
402                                                 <para>Call limit (call-limit).</para>
403                                         </enum>
404                                         <enum name="busylevel">
405                                                 <para>Configured call level for signalling busy.</para>
406                                         </enum>
407                                         <enum name="curcalls">
408                                                 <para>Current amount of calls. Only available if call-limit is set.</para>
409                                         </enum>
410                                         <enum name="language">
411                                                 <para>Default language for peer.</para>
412                                         </enum>
413                                         <enum name="accountcode">
414                                                 <para>Account code for this peer.</para>
415                                         </enum>
416                                         <enum name="useragent">
417                                                 <para>Current user agent id for peer.</para>
418                                         </enum>
419                                         <enum name="chanvar[name]">
420                                                 <para>A channel variable configured with setvar for this peer.</para>
421                                         </enum>
422                                         <enum name="codec[x]">
423                                                 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
424                                         </enum>
425                                 </enumlist>
426                         </parameter>
427                 </syntax>
428                 <description />
429         </function>
430         <function name="SIPCHANINFO" language="en_US">
431                 <synopsis>
432                         Gets the specified SIP parameter from the current channel.
433                 </synopsis>
434                 <syntax>
435                         <parameter name="item" required="true">
436                                 <enumlist>
437                                         <enum name="peerip">
438                                                 <para>The IP address of the peer.</para>
439                                         </enum>
440                                         <enum name="recvip">
441                                                 <para>The source IP address of the peer.</para>
442                                         </enum>
443                                         <enum name="from">
444                                                 <para>The URI from the <literal>From:</literal> header.</para>
445                                         </enum>
446                                         <enum name="uri">
447                                                 <para>The URI from the <literal>Contact:</literal> header.</para>
448                                         </enum>
449                                         <enum name="useragent">
450                                                 <para>The useragent.</para>
451                                         </enum>
452                                         <enum name="peername">
453                                                 <para>The name of the peer.</para>
454                                         </enum>
455                                         <enum name="t38passthrough">
456                                                 <para><literal>1</literal> if T38 is offered or enabled in this channel,
457                                                 otherwise <literal>0</literal>.</para>
458                                         </enum>
459                                 </enumlist>
460                         </parameter>
461                 </syntax>
462                 <description />
463         </function>
464         <function name="CHECKSIPDOMAIN" language="en_US">
465                 <synopsis>
466                         Checks if domain is a local domain.
467                 </synopsis>
468                 <syntax>
469                         <parameter name="domain" required="true" />
470                 </syntax>
471                 <description>
472                         <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
473                         as a local SIP domain that this Asterisk server is configured to handle.
474                         Returns the domain name if it is locally handled, otherwise an empty string.
475                         Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
476                 </description>
477         </function>
478         <manager name="SIPpeers" language="en_US">
479                 <synopsis>
480                         List SIP peers (text format).
481                 </synopsis>
482                 <syntax>
483                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
484                 </syntax>
485                 <description>
486                         <para>Lists SIP peers in text format with details on current status.
487                         Peerlist will follow as separate events, followed by a final event called
488                         PeerlistComplete.</para>
489                 </description>
490         </manager>
491         <manager name="SIPshowpeer" language="en_US">
492                 <synopsis>
493                         show SIP peer (text format).
494                 </synopsis>
495                 <syntax>
496                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
497                         <parameter name="Peer" required="true">
498                                 <para>The peer name you want to check.</para>
499                         </parameter>
500                 </syntax>
501                 <description>
502                         <para>Show one SIP peer with details on current status.</para>
503                 </description>
504         </manager>
505         <manager name="SIPqualifypeer" language="en_US">
506                 <synopsis>
507                         Qualify SIP peers.
508                 </synopsis>
509                 <syntax>
510                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
511                         <parameter name="Peer" required="true">
512                                 <para>The peer name you want to qualify.</para>
513                         </parameter>
514                 </syntax>
515                 <description>
516                         <para>Qualify a SIP peer.</para>
517                 </description>
518         </manager>
519         <manager name="SIPshowregistry" language="en_US">
520                 <synopsis>
521                         Show SIP registrations (text format).
522                 </synopsis>
523                 <syntax>
524                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
525                 </syntax>
526                 <description>
527                         <para>Lists all registration requests and status. Registrations will follow as separate
528                         events. followed by a final event called RegistrationsComplete.</para>
529                 </description>
530         </manager>
531         <manager name="SIPnotify" language="en_US">
532                 <synopsis>
533                         Send a SIP notify.
534                 </synopsis>
535                 <syntax>
536                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
537                         <parameter name="Channel" required="true">
538                                 <para>Peer to receive the notify.</para>
539                         </parameter>
540                         <parameter name="Variable" required="true">
541                                 <para>At least one variable pair must be specified.
542                                 <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
543                         </parameter>
544                 </syntax>
545                 <description>
546                         <para>Sends a SIP Notify event.</para>
547                         <para>All parameters for this event must be specified in the body of this request
548                         via multiple Variable: name=value sequences.</para>
549                 </description>
550         </manager>
551  ***/
552
553 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
554 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
555 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
556 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
557
558 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
559 static struct ast_jb_conf default_jbconf =
560 {
561         .flags = 0,
562         .max_size = -1,
563         .resync_threshold = -1,
564         .impl = "",
565         .target_extra = -1,
566 };
567 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
568
569 static const char config[] = "sip.conf";                /*!< Main configuration file */
570 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
571
572 /*! \brief Readable descriptions of device states.
573  *  \note Should be aligned to above table as index */
574 static const struct invstate2stringtable {
575         const enum invitestates state;
576         const char *desc;
577 } invitestate2string[] = {
578         {INV_NONE,              "None"  },
579         {INV_CALLING,           "Calling (Trying)"},
580         {INV_PROCEEDING,        "Proceeding "},
581         {INV_EARLY_MEDIA,       "Early media"},
582         {INV_COMPLETED,         "Completed (done)"},
583         {INV_CONFIRMED,         "Confirmed (up)"},
584         {INV_TERMINATED,        "Done"},
585         {INV_CANCELLED,         "Cancelled"}
586 };
587
588 /*! \brief Subscription types that we support. We support
589  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
590  * - SIMPLE presence used for device status
591  * - Voicemail notification subscriptions
592  */
593 static const struct cfsubscription_types {
594         enum subscriptiontype type;
595         const char * const event;
596         const char * const mediatype;
597         const char * const text;
598 } subscription_types[] = {
599         { NONE,            "-",        "unknown",                    "unknown" },
600         /* RFC 4235: SIP Dialog event package */
601         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
602         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
603         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
604         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
605         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
606 };
607
608 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
609  *  structure and then route the messages according to the type.
610  *
611  *  \note Note that sip_methods[i].id == i must hold or the code breaks
612  */
613 static const struct  cfsip_methods {
614         enum sipmethod id;
615         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
616         char * const text;
617         enum can_create_dialog can_create;
618 } sip_methods[] = {
619         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
620         { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
621         { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
622         { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
623         { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
624         { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
625         { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
626         { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
627         { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
628         { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
629         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
630         { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
631         { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
632         { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
633         { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
634         { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
635         { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
636 };
637
638 /*! \brief List of well-known SIP options. If we get this in a require,
639    we should check the list and answer accordingly. */
640 static const struct cfsip_options {
641         int id;             /*!< Bitmap ID */
642         int supported;      /*!< Supported by Asterisk ? */
643         char * const text;  /*!< Text id, as in standard */
644 } sip_options[] = {     /* XXX used in 3 places */
645         /* RFC3262: PRACK 100% reliability */
646         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },
647         /* RFC3959: SIP Early session support */
648         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
649         /* SIMPLE events:  RFC4662 */
650         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
651         /* RFC 4916- Connected line ID updates */
652         { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED,  "from-change" },
653         /* GRUU: Globally Routable User Agent URI's */
654         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
655         /* RFC4244 History info */
656         { SIP_OPT_HISTINFO,     NOT_SUPPORTED,  "histinfo" },
657         /* RFC3911: SIP Join header support */
658         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
659         /* Disable the REFER subscription, RFC 4488 */
660         { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED,  "norefersub" },
661         /* SIP outbound - the final NAT battle - draft-sip-outbound */
662         { SIP_OPT_OUTBOUND,     NOT_SUPPORTED,  "outbound" },
663         /* RFC3327: Path support */
664         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
665         /* RFC3840: Callee preferences */
666         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
667         /* RFC3312: Precondition support */
668         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
669         /* RFC3323: Privacy with proxies*/
670         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
671         /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
672         { SIP_OPT_RECLISTINV,   NOT_SUPPORTED,  "recipient-list-invite" },
673         /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
674         { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED,  "recipient-list-subscribe" },
675         /* RFC3891: Replaces: header for transfer */
676         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },
677         /* One version of Polycom firmware has the wrong label */
678         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },
679         /* RFC4412 Resource priorities */
680         { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED,  "resource-priority" },
681         /* RFC3329: Security agreement mechanism */
682         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
683         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
684         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
685         /* RFC4028: SIP Session-Timers */
686         { SIP_OPT_TIMER,        SUPPORTED,      "timer" },
687         /* RFC4538: Target-dialog */
688         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "tdialog" },
689 };
690
691 /*! \brief Diversion header reasons
692  *
693  * The core defines a bunch of constants used to define
694  * redirecting reasons. This provides a translation table
695  * between those and the strings which may be present in
696  * a SIP Diversion header
697  */
698 static const struct sip_reasons {
699         enum AST_REDIRECTING_REASON code;
700         char * const text;
701 } sip_reason_table[] = {
702         { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
703         { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
704         { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
705         { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
706         { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
707         { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
708         { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
709         { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
710         { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
711         { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
712         { AST_REDIRECTING_REASON_AWAY, "away" },
713         { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
714 };
715
716
717 /*! \name DefaultSettings
718         Default setttings are used as a channel setting and as a default when
719         configuring devices
720 */
721 /*@{*/
722 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
723 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
724 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
725 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
726 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
727 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
728 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
729 static int default_qualify;                        /*!< Default Qualify= setting */
730 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
731 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
732                                                     *   a bridged channel on hold */
733 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
734 static char default_engine[256];                   /*!< Default RTP engine */
735 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
736 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
737 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
738 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
739 /*@}*/
740
741 static struct sip_settings sip_cfg;             /*!< SIP configuration data.
742                                         \note in the future we could have multiple of these (per domain, per device group etc) */
743
744 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
745 #define SIP_PEDANTIC_DECODE(str)        \
746         if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {     \
747                 ast_uri_decode(str);    \
748         }       \
749
750 static unsigned int chan_idx;       /*!< used in naming sip channel */
751 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
752
753 static int global_relaxdtmf;        /*!< Relax DTMF */
754 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
755 static int global_rtptimeout;       /*!< Time out call if no RTP */
756 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
757 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
758 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
759 static int global_regattempts_max;  /*!< Registration attempts before giving up */
760 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
761 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
762                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
763                                      *   with just a boolean flag in the device structure */
764 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
765 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
766 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
767 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
768 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
769 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
770 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
771 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
772 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
773 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
774 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
775 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
776 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
777 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
778 static int global_t1;           /*!< T1 time */
779 static int global_t1min;        /*!< T1 roundtrip time minimum */
780 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
781 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
782 static int global_qualifyfreq;          /*!< Qualify frequency */
783 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
784 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
785
786 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
787 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
788 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
789 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
790
791 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
792 /*@}*/
793
794 /*!
795  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
796  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
797  * event package. This variable is set at module load time and may be checked at runtime to determine
798  * if XML parsing support was found.
799  */
800 static int can_parse_xml;
801
802 /*! \name Object counters @{
803  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
804  *  should be used to modify these values. */
805 static int speerobjs = 0;     /*!< Static peers */
806 static int rpeerobjs = 0;     /*!< Realtime peers */
807 static int apeerobjs = 0;     /*!< Autocreated peer objects */
808 static int regobjs = 0;       /*!< Registry objects */
809 /* }@ */
810
811 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
812 static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
813
814 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
815
816 AST_MUTEX_DEFINE_STATIC(netlock);
817
818 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
819    when it's doing something critical. */
820 AST_MUTEX_DEFINE_STATIC(monlock);
821
822 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
823
824 /*! \brief This is the thread for the monitor which checks for input on the channels
825    which are not currently in use.  */
826 static pthread_t monitor_thread = AST_PTHREADT_NULL;
827
828 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
829 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
830
831 struct sched_context *sched;     /*!< The scheduling context */
832 static struct io_context *io;           /*!< The IO context */
833 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
834 struct sip_pkt;
835 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
836
837 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
838
839 static enum sip_debug_e sipdebug;
840
841 /*! \brief extra debugging for 'text' related events.
842  *  At the moment this is set together with sip_debug_console.
843  *  \note It should either go away or be implemented properly.
844  */
845 static int sipdebug_text;
846
847 static const struct _map_x_s referstatusstrings[] = {
848         { REFER_IDLE,      "<none>" },
849         { REFER_SENT,      "Request sent" },
850         { REFER_RECEIVED,  "Request received" },
851         { REFER_CONFIRMED, "Confirmed" },
852         { REFER_ACCEPTED,  "Accepted" },
853         { REFER_RINGING,   "Target ringing" },
854         { REFER_200OK,     "Done" },
855         { REFER_FAILED,    "Failed" },
856         { REFER_NOAUTH,    "Failed - auth failure" },
857         { -1,               NULL} /* terminator */
858 };
859
860 /* --- Hash tables of various objects --------*/
861 #ifdef LOW_MEMORY
862 static const int HASH_PEER_SIZE = 17;
863 static const int HASH_DIALOG_SIZE = 17;
864 #else
865 static const int HASH_PEER_SIZE = 563;  /*!< Size of peer hash table, prime number preferred! */
866 static const int HASH_DIALOG_SIZE = 563;
867 #endif
868
869 static const struct {
870         enum ast_cc_service_type service;
871         const char *service_string;
872 } sip_cc_service_map [] = {
873         [AST_CC_NONE] = { AST_CC_NONE, "" },
874         [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
875         [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
876         [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
877 };
878
879 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
880 {
881         enum ast_cc_service_type service;
882         for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
883                 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
884                         return service;
885                 }
886         }
887         return AST_CC_NONE;
888 }
889
890 static const struct {
891         enum sip_cc_notify_state state;
892         const char *state_string;
893 } sip_cc_notify_state_map [] = {
894         [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
895         [CC_READY] = {CC_READY, "cc-state: ready"},
896 };
897
898 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
899
900 static int sip_epa_register(const struct epa_static_data *static_data)
901 {
902         struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
903
904         if (!backend) {
905                 return -1;
906         }
907
908         backend->static_data = static_data;
909
910         AST_LIST_LOCK(&epa_static_data_list);
911         AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
912         AST_LIST_UNLOCK(&epa_static_data_list);
913         return 0;
914 }
915
916 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
917
918 static void cc_epa_destructor(void *data)
919 {
920         struct sip_epa_entry *epa_entry = data;
921         struct cc_epa_entry *cc_entry = epa_entry->instance_data;
922         ast_free(cc_entry);
923 }
924
925 static const struct epa_static_data cc_epa_static_data  = {
926         .event = CALL_COMPLETION,
927         .name = "call-completion",
928         .handle_error = cc_handle_publish_error,
929         .destructor = cc_epa_destructor,
930 };
931
932 static const struct epa_static_data *find_static_data(const char * const event_package)
933 {
934         const struct epa_backend *backend = NULL;
935
936         AST_LIST_LOCK(&epa_static_data_list);
937         AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
938                 if (!strcmp(backend->static_data->name, event_package)) {
939                         break;
940                 }
941         }
942         AST_LIST_UNLOCK(&epa_static_data_list);
943         return backend ? backend->static_data : NULL;
944 }
945
946 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
947 {
948         struct sip_epa_entry *epa_entry;
949         const struct epa_static_data *static_data;
950
951         if (!(static_data = find_static_data(event_package))) {
952                 return NULL;
953         }
954
955         if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
956                 return NULL;
957         }
958
959         epa_entry->static_data = static_data;
960         ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
961         return epa_entry;
962 }
963
964 /*!
965  * Used to create new entity IDs by ESCs.
966  */
967 static int esc_etag_counter;
968 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
969
970 #ifdef HAVE_LIBXML2
971 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
972
973 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
974         .initial_handler = cc_esc_publish_handler,
975         .modify_handler = cc_esc_publish_handler,
976 };
977 #endif
978
979 /*!
980  * \brief The Event State Compositors
981  *
982  * An Event State Compositor is an entity which
983  * accepts PUBLISH requests and acts appropriately
984  * based on these requests.
985  *
986  * The actual event_state_compositor structure is simply
987  * an ao2_container of sip_esc_entrys. When an incoming
988  * PUBLISH is received, we can match the appropriate sip_esc_entry
989  * using the entity ID of the incoming PUBLISH.
990  */
991 static struct event_state_compositor {
992         enum subscriptiontype event;
993         const char * name;
994         const struct sip_esc_publish_callbacks *callbacks;
995         struct ao2_container *compositor;
996 } event_state_compositors [] = {
997 #ifdef HAVE_LIBXML2
998         {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
999 #endif
1000 };
1001
1002 static const int ESC_MAX_BUCKETS = 37;
1003
1004 static void esc_entry_destructor(void *obj)
1005 {
1006         struct sip_esc_entry *esc_entry = obj;
1007         if (esc_entry->sched_id > -1) {
1008                 AST_SCHED_DEL(sched, esc_entry->sched_id);
1009         }
1010 }
1011
1012 static int esc_hash_fn(const void *obj, const int flags)
1013 {
1014         const struct sip_esc_entry *entry = obj;
1015         return ast_str_hash(entry->entity_tag);
1016 }
1017
1018 static int esc_cmp_fn(void *obj, void *arg, int flags)
1019 {
1020         struct sip_esc_entry *entry1 = obj;
1021         struct sip_esc_entry *entry2 = arg;
1022
1023         return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1024 }
1025
1026 static struct event_state_compositor *get_esc(const char * const event_package) {
1027         int i;
1028         for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1029                 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1030                         return &event_state_compositors[i];
1031                 }
1032         }
1033         return NULL;
1034 }
1035
1036 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1037         struct sip_esc_entry *entry;
1038         struct sip_esc_entry finder;
1039
1040         ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1041
1042         entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1043
1044         return entry;
1045 }
1046
1047 static int publish_expire(const void *data)
1048 {
1049         struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1050         struct event_state_compositor *esc = get_esc(esc_entry->event);
1051
1052         ast_assert(esc != NULL);
1053
1054         ao2_unlink(esc->compositor, esc_entry);
1055         ao2_ref(esc_entry, -1);
1056         return 0;
1057 }
1058
1059 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1060 {
1061         int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1062         struct event_state_compositor *esc = get_esc(esc_entry->event);
1063
1064         ast_assert(esc != NULL);
1065         if (is_linked) {
1066                 ao2_unlink(esc->compositor, esc_entry);
1067         }
1068         snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1069         ao2_link(esc->compositor, esc_entry);
1070 }
1071
1072 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1073 {
1074         struct sip_esc_entry *esc_entry;
1075         int expires_ms;
1076
1077         if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1078                 return NULL;
1079         }
1080
1081         esc_entry->event = esc->name;
1082
1083         expires_ms = expires * 1000;
1084         /* Bump refcount for scheduler */
1085         ao2_ref(esc_entry, +1);
1086         esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1087
1088         /* Note: This links the esc_entry into the ESC properly */
1089         create_new_sip_etag(esc_entry, 0);
1090
1091         return esc_entry;
1092 }
1093
1094 static int initialize_escs(void)
1095 {
1096         int i, res = 0;
1097         for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1098                 if (!((event_state_compositors[i].compositor) =
1099                                         ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1100                         res = -1;
1101                 }
1102         }
1103         return res;
1104 }
1105
1106 static void destroy_escs(void)
1107 {
1108         int i;
1109         for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1110                 ao2_ref(event_state_compositors[i].compositor, -1);
1111         }
1112 }
1113
1114 /*! \brief
1115  * Here we implement the container for dialogs (sip_pvt), defining
1116  * generic wrapper functions to ease the transition from the current
1117  * implementation (a single linked list) to a different container.
1118  * In addition to a reference to the container, we need functions to lock/unlock
1119  * the container and individual items, and functions to add/remove
1120  * references to the individual items.
1121  */
1122 static struct ao2_container *dialogs;
1123 #define sip_pvt_lock(x) ao2_lock(x)
1124 #define sip_pvt_trylock(x) ao2_trylock(x)
1125 #define sip_pvt_unlock(x) ao2_unlock(x)
1126
1127 /*! \brief  The table of TCP threads */
1128 static struct ao2_container *threadt;
1129
1130 /*! \brief  The peer list: Users, Peers and Friends */
1131 static struct ao2_container *peers;
1132 static struct ao2_container *peers_by_ip;
1133
1134 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1135 static struct ast_register_list {
1136         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1137         int recheck;
1138 } regl;
1139
1140 /*! \brief  The MWI subscription list */
1141 static struct ast_subscription_mwi_list {
1142         ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1143 } submwil;
1144 static int temp_pvt_init(void *);
1145 static void temp_pvt_cleanup(void *);
1146
1147 /*! \brief A per-thread temporary pvt structure */
1148 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1149
1150 /*! \brief Authentication list for realm authentication
1151  * \todo Move the sip_auth list to AST_LIST */
1152 static struct sip_auth *authl = NULL;
1153
1154 /* --- Sockets and networking --------------*/
1155
1156 /*! \brief Main socket for UDP SIP communication.
1157  *
1158  * sipsock is shared between the SIP manager thread (which handles reload
1159  * requests), the udp io handler (sipsock_read()) and the user routines that
1160  * issue udp writes (using __sip_xmit()).
1161  * The socket is -1 only when opening fails (this is a permanent condition),
1162  * or when we are handling a reload() that changes its address (this is
1163  * a transient situation during which we might have a harmless race, see
1164  * below). Because the conditions for the race to be possible are extremely
1165  * rare, we don't want to pay the cost of locking on every I/O.
1166  * Rather, we remember that when the race may occur, communication is
1167  * bound to fail anyways, so we just live with this event and let
1168  * the protocol handle this above us.
1169  */
1170 static int sipsock  = -1;
1171
1172 struct sockaddr_in bindaddr;    /*!< UDP: The address we bind to */
1173
1174 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1175  *  internip is initialized picking a suitable address from one of the
1176  * interfaces, and the same port number we bind to. It is used as the
1177  * default address/port in SIP messages, and as the default address
1178  * (but not port) in SDP messages.
1179  */
1180 static struct sockaddr_in internip;
1181
1182 /*! \brief our external IP address/port for SIP sessions.
1183  * externip.sin_addr is only set when we know we might be behind
1184  * a NAT, and this is done using a variety of (mutually exclusive)
1185  * ways from the config file:
1186  *
1187  * + with "externip = host[:port]" we specify the address/port explicitly.
1188  *   The address is looked up only once when (re)loading the config file;
1189  *
1190  * + with "externhost = host[:port]" we do a similar thing, but the
1191  *   hostname is stored in externhost, and the hostname->IP mapping
1192  *   is refreshed every 'externrefresh' seconds;
1193  *
1194  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1195  *   to the specified server, and store the result in externip.
1196  *
1197  * Other variables (externhost, externexpire, externrefresh) are used
1198  * to support the above functions.
1199  */
1200 static struct sockaddr_in externip;       /*!< External IP address if we are behind NAT */
1201 static struct sockaddr_in media_address;  /*!< External RTP IP address if we are behind NAT */
1202
1203 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1204 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1205 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1206 static struct sockaddr_in stunaddr;     /*!< stun server address */
1207 static uint16_t externtcpport;          /*!< external tcp port */ 
1208 static uint16_t externtlsport;          /*!< external tls port */
1209
1210 /*! \brief  List of local networks
1211  * We store "localnet" addresses from the config file into an access list,
1212  * marked as 'DENY', so the call to ast_apply_ha() will return
1213  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1214  * (i.e. presumably public) addresses.
1215  */
1216 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1217
1218 static int ourport_tcp;             /*!< The port used for TCP connections */
1219 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1220 static struct sockaddr_in debugaddr;
1221
1222 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
1223
1224 /*! some list management macros. */
1225
1226 #define UNLINK(element, head, prev) do {        \
1227         if (prev)                               \
1228                 (prev)->next = (element)->next; \
1229         else                                    \
1230                 (head) = (element)->next;       \
1231         } while (0)
1232
1233 /*---------------------------- Forward declarations of functions in chan_sip.c */
1234 /* Note: This is added to help splitting up chan_sip.c into several files
1235         in coming releases. */
1236
1237 /*--- PBX interface functions */
1238 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1239 static int sip_devicestate(void *data);
1240 static int sip_sendtext(struct ast_channel *ast, const char *text);
1241 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1242 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1243 static int sip_hangup(struct ast_channel *ast);
1244 static int sip_answer(struct ast_channel *ast);
1245 static struct ast_frame *sip_read(struct ast_channel *ast);
1246 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1247 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1248 static int sip_transfer(struct ast_channel *ast, const char *dest);
1249 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1250 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1251 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1252 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1253 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1254 static const char *sip_get_callid(struct ast_channel *chan);
1255
1256 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1257 static int sip_standard_port(enum sip_transport type, int port);
1258 static int sip_prepare_socket(struct sip_pvt *p);
1259
1260 /*--- Transmitting responses and requests */
1261 static int sipsock_read(int *id, int fd, short events, void *ignore);
1262 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1263 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1264 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1265 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1266 static int retrans_pkt(const void *data);
1267 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);
1268 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1269 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1270 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1271 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);
1272 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1273 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);
1274 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1275 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1276 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1277 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1278 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1279 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1280 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1281 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1282 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1283 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1284 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1285 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1286 static int transmit_refer(struct sip_pvt *p, const char *dest);
1287 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1288 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1289 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1290 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1291 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1292 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1293 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1294 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1295 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1296 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1297
1298 /* Misc dialog routines */
1299 static int __sip_autodestruct(const void *data);
1300 static void *registry_unref(struct sip_registry *reg, char *tag);
1301 static int update_call_counter(struct sip_pvt *fup, int event);
1302 static int auto_congest(const void *arg);
1303 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1304 static void free_old_route(struct sip_route *route);
1305 static void list_route(struct sip_route *route);
1306 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1307 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1308                                               struct sip_request *req, const char *uri);
1309 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1310 static void check_pendings(struct sip_pvt *p);
1311 static void *sip_park_thread(void *stuff);
1312 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1313 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1314 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1315
1316 /*--- Codec handling / SDP */
1317 static void try_suggested_sip_codec(struct sip_pvt *p);
1318 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1319 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1320 static int find_sdp(struct sip_request *req);
1321 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1322 static int process_sdp_o(const char *o, struct sip_pvt *p);
1323 static int process_sdp_c(const char *c, struct ast_hostent *hp);
1324 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1325 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1326 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1327 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1328 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1329 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1330                              struct ast_str **m_buf, struct ast_str **a_buf,
1331                              int debug, int *min_packet_size);
1332 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1333                                 struct ast_str **m_buf, struct ast_str **a_buf,
1334                                 int debug);
1335 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1336 static void do_setnat(struct sip_pvt *p);
1337 static void stop_media_flows(struct sip_pvt *p);
1338
1339 /*--- Authentication stuff */
1340 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1341 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1342 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1343                                          const char *secret, const char *md5secret, int sipmethod,
1344                                          const char *uri, enum xmittype reliable, int ignore);
1345 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1346                                               int sipmethod, const char *uri, enum xmittype reliable,
1347                                               struct sockaddr_in *sin, struct sip_peer **authpeer);
1348 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1349
1350 /*--- Domain handling */
1351 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1352 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1353 static void clear_sip_domains(void);
1354
1355 /*--- SIP realm authentication */
1356 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1357 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
1358 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1359
1360 /*--- Misc functions */
1361 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1362 static int sip_do_reload(enum channelreloadreason reason);
1363 static int reload_config(enum channelreloadreason reason);
1364 static int expire_register(const void *data);
1365 static void *do_monitor(void *data);
1366 static int restart_monitor(void);
1367 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1368 static struct ast_variable *copy_vars(struct ast_variable *src);
1369 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1370 static int sip_refer_allocate(struct sip_pvt *p);
1371 static int sip_notify_allocate(struct sip_pvt *p);
1372 static void ast_quiet_chan(struct ast_channel *chan);
1373 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1374 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1375
1376 /*--- Device monitoring and Device/extension state/event handling */
1377 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1378 static int sip_devicestate(void *data);
1379 static int sip_poke_noanswer(const void *data);
1380 static int sip_poke_peer(struct sip_peer *peer, int force);
1381 static void sip_poke_all_peers(void);
1382 static void sip_peer_hold(struct sip_pvt *p, int hold);
1383 static void mwi_event_cb(const struct ast_event *, void *);
1384
1385 /*--- Applications, functions, CLI and manager command helpers */
1386 static const char *sip_nat_mode(const struct sip_pvt *p);
1387 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1388 static char *transfermode2str(enum transfermodes mode) attribute_const;
1389 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1390 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1391 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1392 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1393 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1394 static void  print_group(int fd, ast_group_t group, int crlf);
1395 static const char *dtmfmode2str(int mode) attribute_const;
1396 static int str2dtmfmode(const char *str) attribute_unused;
1397 static const char *insecure2str(int mode) attribute_const;
1398 static void cleanup_stale_contexts(char *new, char *old);
1399 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1400 static const char *domain_mode_to_text(const enum domain_mode mode);
1401 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1402 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1403 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1404 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1405 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1406 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1407 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1408 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1409 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1410 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1411 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1412 static char *complete_sip_peer(const char *word, int state, int flags2);
1413 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1414 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1415 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1416 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1417 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1418 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1419 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1420 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1421 static char *sip_do_debug_ip(int fd, const char *arg);
1422 static char *sip_do_debug_peer(int fd, const char *arg);
1423 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1424 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1425 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1426 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1427 static int sip_addheader(struct ast_channel *chan, const char *data);
1428 static int sip_do_reload(enum channelreloadreason reason);
1429 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1430
1431 /*--- Debugging
1432         Functions for enabling debug per IP or fully, or enabling history logging for
1433         a SIP dialog
1434 */
1435 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to debuglog at end of dialog, before destroying data */
1436 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1437 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1438 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1439 static void sip_dump_history(struct sip_pvt *dialog);
1440
1441 /*--- Device object handling */
1442 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1443 static int update_call_counter(struct sip_pvt *fup, int event);
1444 static void sip_destroy_peer(struct sip_peer *peer);
1445 static void sip_destroy_peer_fn(void *peer);
1446 static void set_peer_defaults(struct sip_peer *peer);
1447 static struct sip_peer *temp_peer(const char *name);
1448 static void register_peer_exten(struct sip_peer *peer, int onoff);
1449 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
1450 static int sip_poke_peer_s(const void *data);
1451 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1452 static void reg_source_db(struct sip_peer *peer);
1453 static void destroy_association(struct sip_peer *peer);
1454 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1455 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1456 static void set_socket_transport(struct sip_socket *socket, int transport);
1457
1458 /* Realtime device support */
1459 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);
1460 static void update_peer(struct sip_peer *p, int expire);
1461 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1462 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1463 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1464 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1465
1466 /*--- Internal UA client handling (outbound registrations) */
1467 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
1468 static void sip_registry_destroy(struct sip_registry *reg);
1469 static int sip_register(const char *value, int lineno);
1470 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1471 static int sip_reregister(const void *data);
1472 static int __sip_do_register(struct sip_registry *r);
1473 static int sip_reg_timeout(const void *data);
1474 static void sip_send_all_registers(void);
1475 static int sip_reinvite_retry(const void *data);
1476
1477 /*--- Parsing SIP requests and responses */
1478 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
1479 static int determine_firstline_parts(struct sip_request *req);
1480 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1481 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1482 static int find_sip_method(const char *msg);
1483 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1484 static unsigned int parse_allowed_methods(struct sip_request *req);
1485 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1486 static int parse_request(struct sip_request *req);
1487 static const char *get_header(const struct sip_request *req, const char *name);
1488 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1489 static int method_match(enum sipmethod id, const char *name);
1490 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1491 static const char *find_alias(const char *name, const char *_default);
1492 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1493 static int lws2sws(char *msgbuf, int len);
1494 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1495 static char *remove_uri_parameters(char *uri);
1496 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1497 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1498 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1499 static int set_address_from_contact(struct sip_pvt *pvt);
1500 static void check_via(struct sip_pvt *p, struct sip_request *req);
1501 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1502 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1503 static int get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1504 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1505 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1506 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1507 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1508 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);
1509 static int get_domain(const char *str, char *domain, int len);
1510 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1511
1512 /*-- TCP connection handling ---*/
1513 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1514 static void *sip_tcp_worker_fn(void *);
1515
1516 /*--- Constructing requests and responses */
1517 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1518 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1519 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1520 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1521 static int init_resp(struct sip_request *resp, const char *msg);
1522 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1523 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1524 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1525 static void build_via(struct sip_pvt *p);
1526 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1527 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog, struct sockaddr_in *remote_address);
1528 static char *generate_random_string(char *buf, size_t size);
1529 static void build_callid_pvt(struct sip_pvt *pvt);
1530 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1531 static void make_our_tag(char *tagbuf, size_t len);
1532 static int add_header(struct sip_request *req, const char *var, const char *value);
1533 static int add_header_contentLength(struct sip_request *req, int len);
1534 static int add_line(struct sip_request *req, const char *line);
1535 static int add_text(struct sip_request *req, const char *text);
1536 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1537 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1538 static int add_vidupdate(struct sip_request *req);
1539 static void add_route(struct sip_request *req, struct sip_route *route);
1540 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1541 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1542 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1543 static void set_destination(struct sip_pvt *p, char *uri);
1544 static void append_date(struct sip_request *req);
1545 static void build_contact(struct sip_pvt *p);
1546
1547 /*------Request handling functions */
1548 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1549 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1550 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);
1551 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1552 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1553 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, const char *e);
1554 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1555 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1556 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1557 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1558 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1559 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
1560 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1561 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1562
1563 /*------Response handling functions */
1564 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1565 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1566 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1567 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1568 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1569 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1570 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1571
1572 /*------ SRTP Support -------- */
1573 static int setup_srtp(struct sip_srtp **srtp);
1574 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1575
1576 /*------ T38 Support --------- */
1577 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1578 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1579 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1580 static void change_t38_state(struct sip_pvt *p, int state);
1581
1582 /*------ Session-Timers functions --------- */
1583 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1584 static int  proc_session_timer(const void *vp);
1585 static void stop_session_timer(struct sip_pvt *p);
1586 static void start_session_timer(struct sip_pvt *p);
1587 static void restart_session_timer(struct sip_pvt *p);
1588 static const char *strefresher2str(enum st_refresher r);
1589 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1590 static int parse_minse(const char *p_hdrval, int *const p_interval);
1591 static int st_get_se(struct sip_pvt *, int max);
1592 static enum st_refresher st_get_refresher(struct sip_pvt *);
1593 static enum st_mode st_get_mode(struct sip_pvt *);
1594 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1595
1596 /*------- RTP Glue functions -------- */
1597 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, format_t codecs, int nat_active);
1598
1599 /*!--- SIP MWI Subscription support */
1600 static int sip_subscribe_mwi(const char *value, int lineno);
1601 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1602 static void sip_send_all_mwi_subscriptions(void);
1603 static int sip_subscribe_mwi_do(const void *data);
1604 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1605
1606 /*! \brief Definition of this channel for PBX channel registration */
1607 const struct ast_channel_tech sip_tech = {
1608         .type = "SIP",
1609         .description = "Session Initiation Protocol (SIP)",
1610         .capabilities = AST_FORMAT_AUDIO_MASK,  /* all audio formats */
1611         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1612         .requester = sip_request_call,                  /* called with chan unlocked */
1613         .devicestate = sip_devicestate,                 /* called with chan unlocked (not chan-specific) */
1614         .call = sip_call,                       /* called with chan locked */
1615         .send_html = sip_sendhtml,
1616         .hangup = sip_hangup,                   /* called with chan locked */
1617         .answer = sip_answer,                   /* called with chan locked */
1618         .read = sip_read,                       /* called with chan locked */
1619         .write = sip_write,                     /* called with chan locked */
1620         .write_video = sip_write,               /* called with chan locked */
1621         .write_text = sip_write,
1622         .indicate = sip_indicate,               /* called with chan locked */
1623         .transfer = sip_transfer,               /* called with chan locked */
1624         .fixup = sip_fixup,                     /* called with chan locked */
1625         .send_digit_begin = sip_senddigit_begin,        /* called with chan unlocked */
1626         .send_digit_end = sip_senddigit_end,
1627         .bridge = ast_rtp_instance_bridge,                      /* XXX chan unlocked ? */
1628         .early_bridge = ast_rtp_instance_early_bridge,
1629         .send_text = sip_sendtext,              /* called with chan locked */
1630         .func_channel_read = sip_acf_channel_read,
1631         .setoption = sip_setoption,
1632         .queryoption = sip_queryoption,
1633         .get_pvt_uniqueid = sip_get_callid,
1634 };
1635
1636 /*! \brief This version of the sip channel tech has no send_digit_begin
1637  * callback so that the core knows that the channel does not want
1638  * DTMF BEGIN frames.
1639  * The struct is initialized just before registering the channel driver,
1640  * and is for use with channels using SIP INFO DTMF.
1641  */
1642 struct ast_channel_tech sip_tech_info;
1643
1644 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1645 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1646 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1647 static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1648 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1649 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1650 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1651 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1652
1653 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1654         .type = "SIP",
1655         .init = sip_cc_agent_init,
1656         .start_offer_timer = sip_cc_agent_start_offer_timer,
1657         .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1658         .ack = sip_cc_agent_ack,
1659         .status_request = sip_cc_agent_status_request,
1660         .start_monitoring = sip_cc_agent_start_monitoring,
1661         .callee_available = sip_cc_agent_recall,
1662         .destructor = sip_cc_agent_destructor,
1663 };
1664
1665 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1666 {
1667         struct ast_cc_agent *agent = obj;
1668         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1669         const char *uri = arg;
1670
1671         return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1672 }
1673
1674 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1675 {
1676         struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1677         return agent;
1678 }
1679
1680 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1681 {
1682         struct ast_cc_agent *agent = obj;
1683         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1684         const char *uri = arg;
1685
1686         return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1687 }
1688
1689 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1690 {
1691         struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1692         return agent;
1693 }
1694
1695 static int find_by_callid_helper(void *obj, void *arg, int flags)
1696 {
1697         struct ast_cc_agent *agent = obj;
1698         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1699         struct sip_pvt *call_pvt = arg;
1700
1701         return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1702 }
1703
1704 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1705 {
1706         struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1707         return agent;
1708 }
1709
1710 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1711 {
1712         struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1713         struct sip_pvt *call_pvt = chan->tech_pvt;
1714
1715         if (!agent_pvt) {
1716                 return -1;
1717         }
1718
1719         ast_assert(!strcmp(chan->tech->type, "SIP"));
1720
1721         ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1722         ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1723         agent_pvt->offer_timer_id = -1;
1724         agent->private_data = agent_pvt;
1725         sip_pvt_lock(call_pvt);
1726         ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1727         sip_pvt_unlock(call_pvt);
1728         return 0;
1729 }
1730
1731 static int sip_offer_timer_expire(const void *data)
1732 {
1733         struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1734         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1735
1736         agent_pvt->offer_timer_id = -1;
1737
1738         return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1739 }
1740
1741 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1742 {
1743         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1744         int when;
1745
1746         when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1747         agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1748         return 0;
1749 }
1750
1751 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1752 {
1753         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1754
1755         AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1756         return 0;
1757 }
1758
1759 static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1760 {
1761         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1762
1763         sip_pvt_lock(agent_pvt->subscribe_pvt);
1764         ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1765         transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1766         transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1767         sip_pvt_unlock(agent_pvt->subscribe_pvt);
1768         agent_pvt->is_available = TRUE;
1769 }
1770
1771 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1772 {
1773         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1774         enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1775         return ast_cc_agent_status_response(agent->core_id, state);
1776 }
1777
1778 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1779 {
1780         /* To start monitoring just means to wait for an incoming PUBLISH
1781          * to tell us that the caller has become available again. No special
1782          * action is needed
1783          */
1784         return 0;
1785 }
1786
1787 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1788 {
1789         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1790         /* If we have received a PUBLISH beforehand stating that the caller in question
1791          * is not available, we can save ourself a bit of effort here and just report
1792          * the caller as busy
1793          */
1794         if (!agent_pvt->is_available) {
1795                 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1796                                 agent->device_name);
1797         }
1798         /* Otherwise, we transmit a NOTIFY to the caller and await either
1799          * a PUBLISH or an INVITE
1800          */
1801         sip_pvt_lock(agent_pvt->subscribe_pvt);
1802         transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1803         sip_pvt_unlock(agent_pvt->subscribe_pvt);
1804         return 0;
1805 }
1806
1807 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1808 {
1809         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1810
1811         if (!agent_pvt) {
1812                 /* The agent constructor probably failed. */
1813                 return;
1814         }
1815
1816         sip_cc_agent_stop_offer_timer(agent);
1817         if (agent_pvt->subscribe_pvt) {
1818                 sip_pvt_lock(agent_pvt->subscribe_pvt);
1819                 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1820                         /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1821                          * the subscriber know something went wrong
1822                          */
1823                         transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1824                 }
1825                 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1826                 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1827         }
1828         ast_free(agent_pvt);
1829 }
1830
1831 struct ao2_container *sip_monitor_instances;
1832
1833 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1834 {
1835         const struct sip_monitor_instance *monitor_instance = obj;
1836         return monitor_instance->core_id;
1837 }
1838
1839 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1840 {
1841         struct sip_monitor_instance *monitor_instance1 = obj;
1842         struct sip_monitor_instance *monitor_instance2 = arg;
1843
1844         return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1845 }
1846
1847 static void sip_monitor_instance_destructor(void *data)
1848 {
1849         struct sip_monitor_instance *monitor_instance = data;
1850         if (monitor_instance->subscription_pvt) {
1851                 sip_pvt_lock(monitor_instance->subscription_pvt);
1852                 monitor_instance->subscription_pvt->expiry = 0;
1853                 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1854                 sip_pvt_unlock(monitor_instance->subscription_pvt);
1855                 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1856         }
1857         if (monitor_instance->suspension_entry) {
1858                 monitor_instance->suspension_entry->body[0] = '\0';
1859                 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1860                 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1861         }
1862         ast_string_field_free_memory(monitor_instance);
1863 }
1864
1865 static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
1866 {
1867         struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1868
1869         if (!monitor_instance) {
1870                 return NULL;
1871         }
1872
1873         if (ast_string_field_init(monitor_instance, 256)) {
1874                 ao2_ref(monitor_instance, -1);
1875                 return NULL;
1876         }
1877
1878         ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1879         ast_string_field_set(monitor_instance, peername, peername);
1880         ast_string_field_set(monitor_instance, device_name, device_name);
1881         monitor_instance->core_id = core_id;
1882         ao2_link(sip_monitor_instances, monitor_instance);
1883         return monitor_instance;
1884 }
1885
1886 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1887 {
1888         struct sip_monitor_instance *monitor_instance = obj;
1889         return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1890 }
1891
1892 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1893 {
1894         struct sip_monitor_instance *monitor_instance = obj;
1895         return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1896 }
1897
1898 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1899 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1900 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1901 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1902 static void sip_cc_monitor_destructor(void *private_data);
1903
1904 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1905         .type = "SIP",
1906         .request_cc = sip_cc_monitor_request_cc,
1907         .suspend = sip_cc_monitor_suspend,
1908         .unsuspend = sip_cc_monitor_unsuspend,
1909         .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1910         .destructor = sip_cc_monitor_destructor,
1911 };
1912
1913 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1914 {
1915         struct sip_monitor_instance *monitor_instance = monitor->private_data;
1916         enum ast_cc_service_type service = monitor->service_offered;
1917         int when;
1918
1919         if (!monitor_instance) {
1920                 return -1;
1921         }
1922
1923         if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1924                 return -1;
1925         }
1926
1927         when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1928                 ast_get_ccnr_available_timer(monitor->interface->config_params);
1929
1930         sip_pvt_lock(monitor_instance->subscription_pvt);
1931         create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1932         ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa.sin_addr, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1933         monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1934         monitor_instance->subscription_pvt->expiry = when;
1935
1936         transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1937         sip_pvt_unlock(monitor_instance->subscription_pvt);
1938
1939         ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1940         *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1941         return 0;
1942 }
1943
1944 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1945 {
1946         struct ast_str *body = ast_str_alloca(size);
1947         char tuple_id[32];
1948
1949         generate_random_string(tuple_id, sizeof(tuple_id));
1950
1951         /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1952          * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1953          */
1954         ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1955         /* XXX The entity attribute is currently set to the peer name associated with the
1956          * dialog. This is because we currently only call this function for call-completion
1957          * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1958          * event packages, it may be crucial to have a proper URI as the presentity so this
1959          * should be revisited as support is expanded.
1960          */
1961         ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1962         ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1963         ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1964         ast_str_append(&body, 0, "</tuple>\n");
1965         ast_str_append(&body, 0, "</presence>\n");
1966         ast_copy_string(pidf_body, ast_str_buffer(body), size);
1967         return 0;
1968 }
1969
1970 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1971 {
1972         struct sip_monitor_instance *monitor_instance = monitor->private_data;
1973         enum sip_publish_type publish_type;
1974         struct cc_epa_entry *cc_entry;
1975
1976         if (!monitor_instance) {
1977                 return -1;
1978         }
1979
1980         if (!monitor_instance->suspension_entry) {
1981                 /* We haven't yet allocated the suspension entry, so let's give it a shot */
1982                 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1983                         ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1984                         ao2_ref(monitor_instance, -1);
1985                         return -1;
1986                 }
1987                 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1988                         ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1989                         ao2_ref(monitor_instance, -1);
1990                         return -1;
1991                 }
1992                 cc_entry->core_id = monitor->core_id;
1993                 monitor_instance->suspension_entry->instance_data = cc_entry;
1994                 publish_type = SIP_PUBLISH_INITIAL;
1995         } else {
1996                 publish_type = SIP_PUBLISH_MODIFY;
1997                 cc_entry = monitor_instance->suspension_entry->instance_data;
1998         }
1999
2000         cc_entry->current_state = CC_CLOSED;
2001
2002         if (ast_strlen_zero(monitor_instance->notify_uri)) {
2003                 /* If we have no set notify_uri, then what this means is that we have
2004                  * not received a NOTIFY from this destination stating that he is
2005                  * currently available.
2006                  *
2007                  * This situation can arise when the core calls the suspend callbacks
2008                  * of multiple destinations. If one of the other destinations aside
2009                  * from this one notified Asterisk that he is available, then there
2010                  * is no reason to take any suspension action on this device. Rather,
2011                  * we should return now and if we receive a NOTIFY while monitoring
2012                  * is still "suspended" then we can immediately respond with the
2013                  * proper PUBLISH to let this endpoint know what is going on.
2014                  */
2015                 return 0;
2016         }
2017         construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2018         return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2019 }
2020
2021 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2022 {
2023         struct sip_monitor_instance *monitor_instance = monitor->private_data;
2024         struct cc_epa_entry *cc_entry;
2025
2026         if (!monitor_instance) {
2027                 return -1;
2028         }
2029
2030         ast_assert(monitor_instance->suspension_entry != NULL);
2031
2032         cc_entry = monitor_instance->suspension_entry->instance_data;
2033         cc_entry->current_state = CC_OPEN;
2034         if (ast_strlen_zero(monitor_instance->notify_uri)) {
2035                 /* This means we are being asked to unsuspend a call leg we never
2036                  * sent a PUBLISH on. As such, there is no reason to send another
2037                  * PUBLISH at this point either. We can just return instead.
2038                  */
2039                 return 0;
2040         }
2041         construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2042         return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2043 }
2044
2045 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2046 {
2047         if (*sched_id != -1) {
2048                 AST_SCHED_DEL(sched, *sched_id);
2049                 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2050         }
2051         return 0;
2052 }
2053
2054 static void sip_cc_monitor_destructor(void *private_data)
2055 {
2056         struct sip_monitor_instance *monitor_instance = private_data;
2057         ao2_unlink(sip_monitor_instances, monitor_instance);
2058         ast_module_unref(ast_module_info->self);
2059 }
2060
2061 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2062 {
2063         char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2064         char *uri;
2065         char *purpose;
2066         char *service_str;
2067         static const char cc_purpose[] = "purpose=call-completion";
2068         static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2069
2070         if (ast_strlen_zero(call_info)) {
2071                 /* No Call-Info present. Definitely no CC offer */
2072                 return -1;
2073         }
2074
2075         uri = strsep(&call_info, ";");
2076
2077         while ((purpose = strsep(&call_info, ";"))) {
2078                 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2079                         break;
2080                 }
2081         }
2082         if (!purpose) {
2083                 /* We didn't find the appropriate purpose= parameter. Oh well */
2084                 return -1;
2085         }
2086
2087         /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2088         while ((service_str = strsep(&call_info, ";"))) {
2089                 if (!strncmp(service_str, "m=", 2)) {
2090                         break;
2091                 }
2092         }
2093         if (!service_str) {
2094                 /* So they didn't offer a particular service, We'll just go with CCBS since it really
2095                  * doesn't matter anyway
2096                  */
2097                 service_str = "BS";
2098         } else {
2099                 /* We already determined that there is an "m=" so no need to check
2100                  * the result of this strsep
2101                  */
2102                 strsep(&service_str, "=");
2103         }
2104
2105         if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2106                 /* Invalid service offered */
2107                 return -1;
2108         }
2109
2110         ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2111
2112         return 0;
2113 }
2114
2115 /*
2116  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2117  *
2118  * After taking care of some formalities to be sure that this call is eligible for CC,
2119  * we first try to see if we can make use of native CC. We grab the information from
2120  * the passed-in sip_request (which is always a response to an INVITE). If we can
2121  * use native CC monitoring for the call, then so be it.
2122  *
2123  * If native cc monitoring is not possible or not supported, then we will instead attempt
2124  * to use generic monitoring. Falling back to generic from a failed attempt at using native
2125  * monitoring will only work if the monitor policy of the endpoint is "always"
2126  *
2127  * \param pvt The current dialog. Contains CC parameters for the endpoint
2128  * \param req The response to the INVITE we want to inspect
2129  * \param service The service to use if generic monitoring is to be used. For native
2130  * monitoring, we get the service from the SIP response itself
2131  */
2132 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2133 {
2134         enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2135         int core_id;
2136         char interface_name[AST_CHANNEL_NAME];
2137
2138         if (monitor_policy == AST_CC_MONITOR_NEVER) {
2139                 /* Don't bother, just return */
2140                 return;
2141         }
2142
2143         if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2144                 /* For some reason, CC is invalid, so don't try it! */
2145                 return;
2146         }
2147
2148         ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2149
2150         if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2151                 char subscribe_uri[SIPBUFSIZE];
2152                 char device_name[AST_CHANNEL_NAME];
2153                 enum ast_cc_service_type offered_service;
2154                 struct sip_monitor_instance *monitor_instance;
2155                 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2156                         /* If CC isn't being offered to us, or for some reason the CC offer is
2157                          * not formatted correctly, then it may still be possible to use generic
2158                          * call completion since the monitor policy may be "always"
2159                          */
2160                         goto generic;
2161                 }
2162                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2163                 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2164                         /* Same deal. We can try using generic still */
2165                         goto generic;
2166                 }
2167                 /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2168                  * will have a reference to callbacks in this module. We decrement the module
2169                  * refcount once the monitor destructor is called
2170                  */
2171                 ast_module_ref(ast_module_info->self);
2172                 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2173                 ao2_ref(monitor_instance, -1);
2174                 return;
2175         }
2176
2177 generic:
2178         if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2179                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2180         }
2181 }
2182
2183 /*! \brief Working TLS connection configuration */
2184 static struct ast_tls_config sip_tls_cfg;
2185
2186 /*! \brief Default TLS connection configuration */
2187 static struct ast_tls_config default_tls_cfg;
2188
2189 /*! \brief The TCP server definition */
2190 static struct ast_tcptls_session_args sip_tcp_desc = {
2191         .accept_fd = -1,
2192         .master = AST_PTHREADT_NULL,
2193         .tls_cfg = NULL,
2194         .poll_timeout = -1,
2195         .name = "SIP TCP server",
2196         .accept_fn = ast_tcptls_server_root,
2197         .worker_fn = sip_tcp_worker_fn,
2198 };
2199
2200 /*! \brief The TCP/TLS server definition */
2201 static struct ast_tcptls_session_args sip_tls_desc = {
2202         .accept_fd = -1,
2203         .master = AST_PTHREADT_NULL,
2204         .tls_cfg = &sip_tls_cfg,
2205         .poll_timeout = -1,
2206         .name = "SIP TLS server",
2207         .accept_fn = ast_tcptls_server_root,
2208         .worker_fn = sip_tcp_worker_fn,
2209 };
2210
2211 /*! \brief Append to SIP dialog history
2212         \return Always returns 0 */
2213 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
2214
2215 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2216 {
2217         if (p)
2218 #ifdef REF_DEBUG
2219                 __ao2_ref_debug(p, 1, tag, file, line, func);
2220 #else
2221                 ao2_ref(p, 1);
2222 #endif
2223         else
2224                 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2225         return p;
2226 }
2227
2228 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2229 {
2230         if (p)
2231 #ifdef REF_DEBUG
2232                 __ao2_ref_debug(p, -1, tag, file, line, func);
2233 #else
2234                 ao2_ref(p, -1);
2235 #endif
2236         return NULL;
2237 }
2238
2239 /*! \brief map from an integer value to a string.
2240  * If no match is found, return errorstring
2241  */
2242 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2243 {
2244         const struct _map_x_s *cur;
2245
2246         for (cur = table; cur->s; cur++)
2247                 if (cur->x == x)
2248                         return cur->s;
2249         return errorstring;
2250 }
2251
2252 /*! \brief map from a string to an integer value, case insensitive.
2253  * If no match is found, return errorvalue.
2254  */
2255 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2256 {
2257         const struct _map_x_s *cur;
2258
2259         for (cur = table; cur->s; cur++)
2260                 if (!strcasecmp(cur->s, s))
2261                         return cur->x;
2262         return errorvalue;
2263 }
2264
2265 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2266 {
2267         enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2268         int i;
2269
2270         for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2271                 if (!strcasecmp(text, sip_reason_table[i].text)) {
2272                         ast = sip_reason_table[i].code;
2273                         break;
2274                 }
2275         }
2276
2277         return ast;
2278 }
2279
2280 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2281 {
2282         if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2283                 return sip_reason_table[code].text;
2284         }
2285
2286         return "unknown";
2287 }
2288
2289 /*!
2290  * \brief generic function for determining if a correct transport is being
2291  * used to contact a peer
2292  *
2293  * this is done as a macro so that the "tmpl" var can be passed either a
2294  * sip_request or a sip_peer
2295  */
2296 #define check_request_transport(peer, tmpl) ({ \
2297         int ret = 0; \
2298         if (peer->socket.type == tmpl->socket.type) \
2299                 ; \
2300         else if (!(peer->transports & tmpl->socket.type)) {\
2301                 ast_log(LOG_ERROR, \
2302                         "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2303                         get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2304                         ); \
2305                 ret = 1; \
2306         } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2307                 ast_log(LOG_WARNING, \
2308                         "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2309                         peer->name, get_transport(tmpl->socket.type) \
2310                 ); \
2311         } else { \
2312                 ast_debug(1, \
2313                         "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2314                         peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2315                 ); \
2316         }\
2317         (ret); \
2318 })
2319
2320 /*! \brief
2321  * duplicate a list of channel variables, \return the copy.
2322  */
2323 static struct ast_variable *copy_vars(struct ast_variable *src)
2324 {
2325         struct ast_variable *res = NULL, *tmp, *v = NULL;
2326
2327         for (v = src ; v ; v = v->next) {
2328                 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2329                         tmp->next = res;
2330                         res = tmp;
2331                 }
2332         }
2333         return res;
2334 }
2335
2336 static void tcptls_packet_destructor(void *obj)
2337 {
2338         struct tcptls_packet *packet = obj;
2339
2340         ast_free(packet->data);
2341 }
2342
2343 static void sip_tcptls_client_args_destructor(void *obj)
2344 {
2345         struct ast_tcptls_session_args *args = obj;
2346         if (args->tls_cfg) {
2347                 ast_free(args->tls_cfg->certfile);
2348                 ast_free(args->tls_cfg->pvtfile);
2349                 ast_free(args->tls_cfg->cipher);
2350                 ast_free(args->tls_cfg->cafile);
2351                 ast_free(args->tls_cfg->capath);
2352         }
2353         ast_free(args->tls_cfg);
2354         ast_free((char *) args->name);
2355 }
2356
2357 static void sip_threadinfo_destructor(void *obj)
2358 {
2359         struct sip_threadinfo *th = obj;
2360         struct tcptls_packet *packet;
2361         if (th->alert_pipe[1] > -1) {
2362                 close(th->alert_pipe[0]);
2363         }
2364         if (th->alert_pipe[1] > -1) {
2365                 close(th->alert_pipe[1]);
2366         }
2367         th->alert_pipe[0] = th->alert_pipe[1] = -1;
2368
2369         while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2370                 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2371         }
2372
2373         if (th->tcptls_session) {
2374                 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2375         }
2376 }
2377
2378 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2379 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2380 {
2381         struct sip_threadinfo *th;
2382
2383         if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2384                 return NULL;
2385         }
2386
2387         th->alert_pipe[0] = th->alert_pipe[1] = -1;
2388
2389         if (pipe(th->alert_pipe) == -1) {
2390                 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2391                 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2392                 return NULL;
2393         }
2394         ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2395         th->tcptls_session = tcptls_session;
2396         th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2397         ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2398         ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2399         return th;
2400 }
2401
2402 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2403 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2404 {
2405         int res = len;
2406         struct sip_threadinfo *th = NULL;
2407         struct tcptls_packet *packet = NULL;
2408         struct sip_threadinfo tmp = {
2409                 .tcptls_session = tcptls_session,
2410         };
2411         enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2412
2413         if (!tcptls_session) {
2414                 return XMIT_ERROR;
2415         }
2416
2417         ast_mutex_lock(&tcptls_session->lock);
2418
2419         if ((tcptls_session->fd == -1) ||
2420                 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2421                 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2422                 !(packet->data = ast_str_create(len))) {
2423                 goto tcptls_write_setup_error;
2424         }
2425
2426         /* goto tcptls_write_error should _NOT_ be used beyond this point */
2427         ast_str_set(&packet->data, 0, "%s", (char *) buf);
2428         packet->len = len;
2429
2430         /* alert tcptls thread handler that there is a packet to be sent.
2431          * must lock the thread info object to guarantee control of the
2432          * packet queue */
2433         ao2_lock(th);
2434         if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2435                 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2436                 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2437                 packet = NULL;
2438                 res = XMIT_ERROR;
2439         } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2440                 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2441         }
2442         ao2_unlock(th);
2443
2444         ast_mutex_unlock(&tcptls_session->lock);
2445         ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2446         return res;
2447
2448 tcptls_write_setup_error:
2449         if (th) {
2450                 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2451         }
2452         if (packet) {
2453                 ao2_t_ref(packet, -1, "could not allocate packet's data");
2454         }
2455         ast_mutex_unlock(&tcptls_session->lock);
2456
2457         return XMIT_ERROR;
2458 }
2459
2460 /*! \brief SIP TCP connection handler */
2461 static void *sip_tcp_worker_fn(void *data)
2462 {
2463         struct ast_tcptls_session_instance *tcptls_session = data;
2464
2465         return _sip_tcp_helper_thread(NULL, tcptls_session);
2466 }
2467
2468 /*! \brief SIP TCP thread management function
2469         This function reads from the socket, parses the packet into a request
2470 */
2471 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2472 {
2473         int res, cl;
2474         struct sip_request req = { 0, } , reqcpy = { 0, };
2475         struct sip_threadinfo *me = NULL;
2476         char buf[1024] = "";
2477         struct pollfd fds[2] = { { 0 }, { 0 }, };
2478         struct ast_tcptls_session_args *ca = NULL;
2479
2480         /* If this is a server session, then the connection has already been setup,
2481          * simply create the threadinfo object so we can access this thread for writing.
2482          * 
2483          * if this is a client connection more work must be done.
2484          * 1. We own the parent session args for a client connection.  This pointer needs
2485          *    to be held on to so we can decrement it's ref count on thread destruction.
2486          * 2. The threadinfo object was created before this thread was launched, however
2487          *    it must be found within the threadt table.
2488          * 3. Last, the tcptls_session must be started.
2489          */
2490         if (!tcptls_session->client) {
2491                 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2492                         goto cleanup;
2493                 }
2494                 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2495         } else {
2496                 struct sip_threadinfo tmp = {
2497                         .tcptls_session = tcptls_session,
2498                 };
2499
2500                 if ((!(ca = tcptls_session->parent)) ||
2501                         (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2502                         (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2503                         goto cleanup;
2504                 }
2505         }
2506
2507         me->threadid = pthread_self();
2508         ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2509
2510         /* set up pollfd to watch for reads on both the socket and the alert_pipe */
2511         fds[0].fd = tcptls_session->fd;
2512         fds[1].fd = me->alert_pipe[0];
2513         fds[0].events = fds[1].events = POLLIN | POLLPRI;
2514
2515         if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2516                 goto cleanup;
2517         if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2518                 goto cleanup;
2519
2520         for (;;) {
2521                 struct ast_str *str_save;
2522
2523                 res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2524                 if (res < 0) {
2525                         ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2526                         goto cleanup;
2527                 }
2528
2529                 /* handle the socket event, check for both reads from the socket fd,
2530                  * and writes from alert_pipe fd */
2531                 if (fds[0].revents) { /* there is data on the socket to be read */
2532
2533                         fds[0].revents = 0;
2534
2535                         /* clear request structure */
2536                         str_save = req.data;
2537                         memset(&req, 0, sizeof(req));
2538                         req.data = str_save;
2539                         ast_str_reset(req.data);
2540
2541                         str_save = reqcpy.data;
2542                         memset(&reqcpy, 0, sizeof(reqcpy));
2543                         reqcpy.data = str_save;
2544                         ast_str_reset(reqcpy.data);
2545
2546                         memset(buf, 0, sizeof(buf));
2547
2548                         if (tcptls_session->ssl) {
2549                                 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2550                                 req.socket.port = htons(ourport_tls);
2551                         } else {
2552                                 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2553                                 req.socket.port = htons(ourport_tcp);
2554                         }
2555                         req.socket.fd = tcptls_session->fd;
2556
2557                         /* Read in headers one line at a time */
2558                         while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2559                                 ast_mutex_lock(&tcptls_session->lock);
2560                                 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2561                                         ast_mutex_unlock(&tcptls_session->lock);
2562                                         goto cleanup;
2563                                 }
2564                                 ast_mutex_unlock(&tcptls_session->lock);
2565                                 if (me->stop)
2566                                          goto cleanup;
2567                                 ast_str_append(&req.data, 0, "%s", buf);
2568                                 req.len = req.data->used;
2569                         }
2570                         copy_request(&reqcpy, &req);
2571                         parse_request(&reqcpy);
2572                         /* In order to know how much to read, we need the content-length header */
2573                         if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2574                                 while (cl > 0) {
2575                                         size_t bytes_read;
2576                                         ast_mutex_lock(&tcptls_session->lock);
2577                                         if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2578                                                 ast_mutex_unlock(&tcptls_session->lock);
2579                                                 goto cleanup;
2580                                         }
2581                                         buf[bytes_read] = '\0';
2582                                         ast_mutex_unlock(&tcptls_session->lock);
2583                                         if (me->stop)
2584                                                 goto cleanup;
2585                                         cl -= strlen(buf);
2586                                         ast_str_append(&req.data, 0, "%s", buf);
2587                                         req.len = req.data->used;
2588                                 }
2589                         }
2590                         /*! \todo XXX If there's no Content-Length or if the content-length and what
2591                                         we receive is not the same - we should generate an error */
2592
2593                         req.socket.tcptls_session = tcptls_session;
2594                         handle_request_do(&req, &tcptls_session->remote_address);
2595                 }
2596
2597                 if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2598                         enum sip_tcptls_alert alert;
2599                         struct tcptls_packet *packet;
2600
2601                         fds[1].revents = 0;
2602
2603                         if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2604                                 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2605                                 continue;
2606                         }
2607
2608                         switch (alert) {
2609                         case TCPTLS_ALERT_STOP:
2610                                 goto cleanup;
2611                         case TCPTLS_ALERT_DATA:
2612                                 ao2_lock(me);
2613                                 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2614                                         ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2615                                 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2616                                         ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2617                                 }
2618
2619                                 if (packet) {
2620                                         ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2621                                 }
2622                                 ao2_unlock(me);
2623                                 break;
2624                         default:
2625                                 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2626                         }
2627                 }
2628         }
2629
2630         ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2631
2632 cleanup:
2633         if (me) {
2634                 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2635                 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2636         }
2637         if (reqcpy.data) {
2638                 ast_free(reqcpy.data);
2639         }
2640
2641         if (req.data) {
2642                 ast_free(req.data);
2643                 req.data = NULL;
2644         }
2645
2646         /* if client, we own the parent session arguments and must decrement ref */
2647         if (ca) {
2648                 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2649         }
2650
2651         if (tcptls_session) {
2652                 ast_mutex_lock(&tcptls_session->lock);
2653                 if (tcptls_session->f) {
2654                         fclose(tcptls_session->f);
2655                         tcptls_session->f = NULL;
2656                 }
2657                 if (tcptls_session->fd != -1) {
2658                         close(tcptls_session->fd);
2659                         tcptls_session->fd = -1;
2660                 }
2661                 tcptls_session->parent = NULL;
2662                 ast_mutex_unlock(&tcptls_session->lock);
2663
2664                 ao2_ref(tcptls_session, -1);
2665                 tcptls_session = NULL;
2666         }
2667         return NULL;
2668 }
2669
2670
2671 /*!
2672  * helper functions to unreference various types of objects.
2673  * By handling them this way, we don't have to declare the
2674  * destructor on each call, which removes the chance of errors.
2675  */
2676 static void *unref_peer(struct sip_peer *peer, char *tag)
2677 {
2678         ao2_t_ref(peer, -1, tag);
2679         return NULL;
2680 }
2681
2682 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2683 {
2684         ao2_t_ref(peer, 1, tag);
2685         return peer;
2686 }
2687
2688 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2689  *
2690  * This function sets pvt's outboundproxy pointer to the one referenced
2691  * by the proxy parameter. Because proxy may be a refcounted object, and
2692  * because pvt's old outboundproxy may also be a refcounted object, we need
2693  * to maintain the proper refcounts.
2694  *
2695  * \param pvt The sip_pvt for which we wish to set the outboundproxy
2696  * \param proxy The sip_proxy which we will point pvt towards.
2697  * \return Returns void
2698  */
2699 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2700 {
2701         struct sip_proxy *old_obproxy = pvt->outboundproxy;
2702         /* The sip_cfg.outboundproxy is statically allocated, and so
2703          * we don't ever need to adjust refcounts for it
2704          */
2705         if (proxy && proxy != &sip_cfg.outboundproxy) {
2706                 ao2_ref(proxy, +1);
2707         }
2708         pvt->outboundproxy = proxy;
2709         if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2710                 ao2_ref(old_obproxy, -1);
2711         }
2712 }
2713
2714 /*!
2715  * \brief Unlink a dialog from the dialogs container, as well as any other places
2716  * that it may be currently stored.
2717  *
2718  * \note A reference to the dialog must be held before calling this function, and this
2719  * function does not release that reference.
2720  */
2721 void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2722 {
2723         struct sip_pkt *cp;
2724
2725         dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2726
2727         ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2728
2729         /* Unlink us from the owner (channel) if we have one */
2730         if (dialog->owner) {
2731                 if (lockowner)
2732                         ast_channel_lock(dialog->owner);
2733                 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2734                 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2735                 if (lockowner)
2736                         ast_channel_unlock(dialog->owner);
2737         }
2738         if (dialog->registry) {
2739                 if (dialog->registry->call == dialog)
2740                         dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2741                 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2742         }
2743         if (dialog->stateid > -1) {
2744                 ast_extension_state_del(dialog->stateid, NULL);
2745                 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2746                 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2747         }
2748         /* Remove link from peer to subscription of MWI */
2749         if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2750                 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2751         if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2752                 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2753
2754         /* remove all current packets in this dialog */
2755         while((cp = dialog->packets)) {
2756                 dialog->packets = dialog->packets->next;
2757                 AST_SCHED_DEL(sched, cp->retransid);
2758                 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2759                 if (cp->data) {
2760                         ast_free(cp->data);
2761                 }
2762                 ast_free(cp);
2763         }
2764
2765         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"));
2766
2767         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"));
2768         
2769         if (dialog->autokillid > -1)
2770                 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"));
2771
2772         if (dialog->request_queue_sched_id > -1) {
2773                 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"));
2774         }
2775
2776         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"));
2777
2778         if (dialog->t38id > -1) {
2779                 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"));
2780         }
2781
2782         dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2783         return NULL;
2784 }
2785
2786 void *registry_unref(struct sip_registry *reg, char *tag)
2787 {
2788         ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2789         ASTOBJ_UNREF(reg, sip_registry_destroy);
2790         return NULL;
2791 }
2792
2793 /*! \brief Add object reference to SIP registry */
2794 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2795 {
2796         ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2797         return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2798 }
2799
2800 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2801 static struct ast_udptl_protocol sip_udptl = {
2802         type: "SIP",
2803         get_udptl_info: sip_get_udptl_peer,
2804         set_udptl_peer: sip_set_udptl_peer,
2805 };
2806
2807 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2808         __attribute__((format(printf, 2, 3)));
2809
2810
2811 /*! \brief Convert transfer status to string */
2812 static const char *referstatus2str(enum referstatus rstatus)
2813 {
2814         return map_x_s(referstatusstrings, rstatus, "");
2815 }
2816
2817 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2818 {
2819         append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2820         pvt->needdestroy = 1;
2821 }
2822
2823 /*! \brief Initialize the initital request packet in the pvt structure.
2824         This packet is used for creating replies and future requests in
2825         a dialog */
2826 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2827 {
2828         if (p->initreq.headers)
2829                 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2830         else
2831                 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2832         /* Use this as the basis */
2833         copy_request(&p->initreq, req);
2834         parse_request(&p->initreq);
2835         if (req->debug)
2836                 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2837 }
2838
2839 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2840 static void sip_alreadygone(struct sip_pvt *dialog)
2841 {
2842         ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2843         dialog->alreadygone = 1;
2844 }
2845
2846 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2847 static int proxy_update(struct sip_proxy *proxy)
2848 {
2849         /* if it's actually an IP address and not a name,
2850            there's no need for a managed lookup */
2851         if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2852                 /* Ok, not an IP address, then let's check if it's a domain or host */
2853                 /* XXX Todo - if we have proxy port, don't do SRV */
2854                 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2855                         ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2856                         return FALSE;
2857                 }
2858         }
2859         proxy->last_dnsupdate = time(NULL);
2860         return TRUE;
2861 }
2862
2863 /*! \brief converts ascii port to int representation. If no
2864  *  pt buffer is provided or the pt has errors when being converted
2865  *  to an int value, the port provided as the standard is used.
2866  */
2867 unsigned int port_str2int(const char *pt, unsigned int standard)
2868 {
2869         int port = standard;
2870         if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2871                 port = standard;
2872         }
2873
2874         return port;
2875 }
2876
2877 /*! \brief Allocate and initialize sip proxy */
2878 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2879 {
2880         struct sip_proxy *proxy;
2881
2882         if (ast_strlen_zero(name)) {
2883                 return NULL;
2884         }
2885
2886         proxy = ao2_alloc(sizeof(*proxy), NULL);
2887         if (!proxy)
2888                 return NULL;
2889         proxy->force = force;
2890         ast_copy_string(proxy->name, name, sizeof(proxy->name));
2891         proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
2892         proxy->ip.sin_family = AF_INET;
2893         proxy_update(proxy);
2894         return proxy;
2895 }
2896
2897 /*! \brief Get default outbound proxy or global proxy */
2898 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2899 {
2900         if (peer && peer->outboundproxy) {
2901                 if (sipdebug)
2902                         ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2903                 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2904                 return peer->outboundproxy;
2905         }
2906         if (sip_cfg.outboundproxy.name[0]) {
2907                 if (sipdebug)
2908                         ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2909                 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2910                 return &sip_cfg.outboundproxy;
2911         }
2912         if (sipdebug)
2913                 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2914         return NULL;
2915 }
2916
2917 /*! \brief returns true if 'name' (with optional trailing whitespace)
2918  * matches the sip method 'id'.
2919  * Strictly speaking, SIP methods are case SENSITIVE, but we do
2920  * a case-insensitive comparison to be more tolerant.
2921  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2922  */
2923 static int method_match(enum sipmethod id, const char *name)
2924 {
2925         int len = strlen(sip_methods[id].text);
2926         int l_name = name ? strlen(name) : 0;
2927         /* true if the string is long enough, and ends with whitespace, and matches */
2928         return (l_name >= len && name[len] < 33 &&
2929                 !strncasecmp(sip_methods[id].text, name, len));
2930 }
2931
2932 /*! \brief  find_sip_method: Find SIP method from header */
2933 static int find_sip_method(const char *msg)
2934 {
2935         int i, res = 0;
2936         
2937         if (ast_strlen_zero(msg))
2938                 return 0;
2939         for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2940                 if (method_match(i, msg))
2941                         res = sip_methods[i].id;
2942         }
2943         return res;
2944 }
2945
2946 /*! \brief Parse supported header in incoming packet */
2947 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2948 {
2949         char *next, *sep;
2950         char *temp;
2951         unsigned int profile = 0;
2952         int i, found;
2953
2954         if (ast_strlen_zero(supported) )
2955                 return 0;
2956         temp = ast_strdupa(supported);
2957
2958         if (sipdebug)
2959                 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2960
2961         for (next = temp; next; next = sep) {
2962                 found = FALSE;
2963                 if ( (sep = strchr(next, ',')) != NULL)
2964                         *sep++ = '\0';
2965                 next = ast_skip_blanks(next);
2966                 if (sipdebug)
2967                         ast_debug(3, "Found SIP option: -%s-\n", next);
2968                 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2969                         if (!strcasecmp(next, sip_options[i].text)) {
2970                                 profile |= sip_options[i].id;
2971                                 found = TRUE;
2972                                 if (sipdebug)
2973                                         ast_debug(3, "Matched SIP option: %s\n", next);
2974                                 break;
2975                         }
2976                 }
2977
2978                 /* This function is used to parse both Suported: and Require: headers.
2979                 Let the caller of this function know that an unknown option tag was
2980                 encountered, so that if the UAC requires it then the request can be
2981                 rejected with a 420 response. */
2982                 if (!found)
2983                         profile |= SIP_OPT_UNKNOWN;
2984
2985                 if (!found && sipdebug) {
2986                         if (!strncasecmp(next, "x-", 2))
2987                                 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2988                         else
2989                                 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2990                 }
2991         }
2992
2993         if (pvt)
2994                 pvt->sipoptions = profile;
2995         return profile;
2996 }
2997
2998 /*! \brief See if we pass debug IP filter */
2999 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
3000 {
3001         if (!sipdebug)
3002                 return 0;
3003         if (debugaddr.sin_addr.s_addr) {
3004                 if (((ntohs(debugaddr.sin_port) != 0)
3005                         && (debugaddr.sin_port != addr->sin_port))
3006                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
3007                         return 0;
3008         }
3009         return 1;
3010 }
3011
3012 /*! \brief The real destination address for a write */
3013 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
3014 {
3015         if (p->outboundproxy)
3016                 return &p->outboundproxy->ip;
3017
3018         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;
3019 }
3020
3021 /*! \brief Display SIP nat mode */
3022 static const char *sip_nat_mode(const struct sip_pvt *p)
3023 {
3024         return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3025 }
3026
3027 /*! \brief Test PVT for debugging output */
3028 static inline int sip_debug_test_pvt(struct sip_pvt *p)
3029 {
3030         if (!sipdebug)
3031                 return 0;
3032         return sip_debug_test_addr(sip_real_dst(p));
3033 }
3034
3035 /*! \brief Return int representing a bit field of transport types found in const char *transport */
3036 static int get_transport_str2enum(const char *transport)
3037 {
3038         int res = 0;
3039
3040         if (ast_strlen_zero(transport)) {
3041                 return res;
3042         }
3043
3044         if (!strcasecmp(transport, "udp")) {
3045                 res |= SIP_TRANSPORT_UDP;
3046         }
3047         if (!strcasecmp(transport, "tcp")) {
3048                 res |= SIP_TRANSPORT_TCP;
3049         }
3050         if (!strcasecmp(transport, "tls")) {
3051                 res |= SIP_TRANSPORT_TLS;
3052         }
3053
3054         return res;
3055 }
3056
3057 /*! \brief Return configuration of transports for a device */
3058 static inline const char *get_transport_list(unsigned int transports) {
3059         switch (transports) {
3060                 case SIP_TRANSPORT_UDP:
3061                         return "UDP";
3062                 case SIP_TRANSPORT_TCP:
3063                         return "TCP";
3064                 case SIP_TRANSPORT_TLS:
3065                         return "TLS";
3066                 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3067                         return "TCP,UDP";
3068                 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3069                         return "TLS,UDP";
3070                 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3071                         return "TLS,TCP";
3072                 default:
3073                         return transports ?
3074                                 "TLS,TCP,UDP" : "UNKNOWN";      
3075         }
3076 }
3077
3078 /*! \brief Return transport as string */
3079 static inline const char *get_transport(enum sip_transport t)
3080 {
3081         switch (t) {
3082         case SIP_TRANSPORT_UDP:
3083                 return "UDP";
3084         case SIP_TRANSPORT_TCP:
3085                 return "TCP";
3086         case SIP_TRANSPORT_TLS:
3087                 return "TLS";
3088         }
3089
3090         return "UNKNOWN";
3091 }
3092
3093 /*! \brief Return transport of dialog.
3094         \note this is based on a false assumption. We don't always use the
3095         outbound proxy for all requests in a dialog. It depends on the
3096         "force" parameter. The FIRST request is always sent to the ob proxy.
3097         \todo Fix this function to work correctly
3098 */
3099 static inline const char *get_transport_pvt(struct sip_pvt *p)
3100 {
3101         if (p->outboundproxy && p->outboundproxy->transport) {
3102                 set_socket_transport(&p->socket, p->outboundproxy->transport);
3103         }
3104
3105         return get_transport(p->socket.type);
3106 }
3107
3108 /*! \brief Transmit SIP message
3109         Sends a SIP request or response on a given socket (in the pvt)
3110         Called by retrans_pkt, send_request, send_response and
3111         __sip_reliable_xmit
3112         \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3113 */
3114 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3115 {
3116         int res = 0;
3117         const struct sockaddr_in *dst = sip_real_dst(p);
3118
3119         ast_debug(2, "T