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