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