2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
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
37 * ******** General TODO:s
38 * \todo Better support of forking
39 * \todo VIA branch tag transaction checking
40 * \todo Transaction support
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
47 * \ingroup channel_drivers
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)
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"
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.
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.
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.
83 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
87 * Outbound calls are set up by the PBX through the sip_request_call()
88 * function. After that, they are activated by sip_call().
91 * The PBX issues a hangup on both incoming and outgoing calls through
92 * the sip_hangup() function
96 * \page sip_tcp_tls SIP TCP and TLS support
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
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.
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.
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.
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
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.
165 <depend>chan_local</depend>
168 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
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).
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"]
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:
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.
208 #include "asterisk.h"
210 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
213 #include <sys/signal.h>
215 #include <inttypes.h>
217 #include "asterisk/network.h"
218 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
220 Uncomment the define below, if you are having refcount related memory leaks.
221 With this uncommented, this module will generate a file, /tmp/refs, which contains
222 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
223 be modified to ao2_t_* calls, and include a tag describing what is happening with
224 enough detail, to make pairing up a reference count increment with its corresponding decrement.
225 The refcounter program in utils/ can be invaluable in highlighting objects that are not
226 balanced, along with the complete history for that object.
227 In normal operation, the macros defined will throw away the tags, so they do not
228 affect the speed of the program at all. They can be considered to be documentation.
230 /* #define REF_DEBUG 1 */
231 #include "asterisk/lock.h"
232 #include "asterisk/config.h"
233 #include "asterisk/module.h"
234 #include "asterisk/pbx.h"
235 #include "asterisk/sched.h"
236 #include "asterisk/io.h"
237 #include "asterisk/rtp_engine.h"
238 #include "asterisk/udptl.h"
239 #include "asterisk/acl.h"
240 #include "asterisk/manager.h"
241 #include "asterisk/callerid.h"
242 #include "asterisk/cli.h"
243 #include "asterisk/musiconhold.h"
244 #include "asterisk/dsp.h"
245 #include "asterisk/features.h"
246 #include "asterisk/srv.h"
247 #include "asterisk/astdb.h"
248 #include "asterisk/causes.h"
249 #include "asterisk/utils.h"
250 #include "asterisk/file.h"
251 #include "asterisk/astobj2.h"
252 #include "asterisk/dnsmgr.h"
253 #include "asterisk/devicestate.h"
254 #include "asterisk/monitor.h"
255 #include "asterisk/netsock.h"
256 #include "asterisk/localtime.h"
257 #include "asterisk/abstract_jb.h"
258 #include "asterisk/threadstorage.h"
259 #include "asterisk/translate.h"
260 #include "asterisk/ast_version.h"
261 #include "asterisk/event.h"
262 #include "asterisk/stun.h"
263 #include "asterisk/cel.h"
264 #include "sip/include/sip.h"
265 #include "sip/include/globals.h"
266 #include "sip/include/config_parser.h"
267 #include "sip/include/reqresp_parser.h"
268 #include "sip/include/sip_utils.h"
269 #include "asterisk/ccss.h"
270 #include "asterisk/xml.h"
271 #include "sip/include/dialog.h"
272 #include "sip/include/dialplan_functions.h"
275 <application name="SIPDtmfMode" language="en_US">
277 Change the dtmfmode for a SIP call.
280 <parameter name="mode" required="true">
282 <enum name="inband" />
284 <enum name="rfc2833" />
289 <para>Changes the dtmfmode for a SIP call.</para>
292 <application name="SIPAddHeader" language="en_US">
294 Add a SIP header to the outbound call.
297 <parameter name="Header" required="true" />
298 <parameter name="Content" required="true" />
301 <para>Adds a header to a SIP call placed with DIAL.</para>
302 <para>Remember to use the X-header if you are adding non-standard SIP
303 headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
304 Adding the wrong headers may jeopardize the SIP dialog.</para>
305 <para>Always returns <literal>0</literal>.</para>
308 <application name="SIPRemoveHeader" language="en_US">
310 Remove SIP headers previously added with SIPAddHeader
313 <parameter name="Header" required="false" />
316 <para>SIPRemoveHeader() allows you to remove headers which were previously
317 added with SIPAddHeader(). If no parameter is supplied, all previously added
318 headers will be removed. If a parameter is supplied, only the matching headers
319 will be removed.</para>
320 <para>For example you have added these 2 headers:</para>
321 <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
322 <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
324 <para>// remove all headers</para>
325 <para>SIPRemoveHeader();</para>
326 <para>// remove all P- headers</para>
327 <para>SIPRemoveHeader(P-);</para>
328 <para>// remove only the PAI header (note the : at the end)</para>
329 <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
331 <para>Always returns <literal>0</literal>.</para>
334 <function name="SIP_HEADER" language="en_US">
336 Gets the specified SIP header.
339 <parameter name="name" required="true" />
340 <parameter name="number">
341 <para>If not specified, defaults to <literal>1</literal>.</para>
345 <para>Since there are several headers (such as Via) which can occur multiple
346 times, SIP_HEADER takes an optional second argument to specify which header with
347 that name to retrieve. Headers start at offset <literal>1</literal>.</para>
350 <function name="SIPPEER" language="en_US">
352 Gets SIP peer information.
355 <parameter name="peername" required="true" />
356 <parameter name="item">
359 <para>(default) The ip address.</para>
362 <para>The port number.</para>
364 <enum name="mailbox">
365 <para>The configured mailbox.</para>
367 <enum name="context">
368 <para>The configured context.</para>
371 <para>The epoch time of the next expire.</para>
373 <enum name="dynamic">
374 <para>Is it dynamic? (yes/no).</para>
376 <enum name="callerid_name">
377 <para>The configured Caller ID name.</para>
379 <enum name="callerid_num">
380 <para>The configured Caller ID number.</para>
382 <enum name="callgroup">
383 <para>The configured Callgroup.</para>
385 <enum name="pickupgroup">
386 <para>The configured Pickupgroup.</para>
389 <para>The configured codecs.</para>
392 <para>Status (if qualify=yes).</para>
394 <enum name="regexten">
395 <para>Registration extension.</para>
398 <para>Call limit (call-limit).</para>
400 <enum name="busylevel">
401 <para>Configured call level for signalling busy.</para>
403 <enum name="curcalls">
404 <para>Current amount of calls. Only available if call-limit is set.</para>
406 <enum name="language">
407 <para>Default language for peer.</para>
409 <enum name="accountcode">
410 <para>Account code for this peer.</para>
412 <enum name="useragent">
413 <para>Current user agent id for peer.</para>
415 <enum name="chanvar[name]">
416 <para>A channel variable configured with setvar for this peer.</para>
418 <enum name="codec[x]">
419 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
426 <function name="SIPCHANINFO" language="en_US">
428 Gets the specified SIP parameter from the current channel.
431 <parameter name="item" required="true">
434 <para>The IP address of the peer.</para>
437 <para>The source IP address of the peer.</para>
440 <para>The URI from the <literal>From:</literal> header.</para>
443 <para>The URI from the <literal>Contact:</literal> header.</para>
445 <enum name="useragent">
446 <para>The useragent.</para>
448 <enum name="peername">
449 <para>The name of the peer.</para>
451 <enum name="t38passthrough">
452 <para><literal>1</literal> if T38 is offered or enabled in this channel,
453 otherwise <literal>0</literal>.</para>
460 <function name="CHECKSIPDOMAIN" language="en_US">
462 Checks if domain is a local domain.
465 <parameter name="domain" required="true" />
468 <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
469 as a local SIP domain that this Asterisk server is configured to handle.
470 Returns the domain name if it is locally handled, otherwise an empty string.
471 Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
474 <manager name="SIPpeers" language="en_US">
476 List SIP peers (text format).
479 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
482 <para>Lists SIP peers in text format with details on current status.
483 Peerlist will follow as separate events, followed by a final event called
484 PeerlistComplete.</para>
487 <manager name="SIPshowpeer" language="en_US">
489 show SIP peer (text format).
492 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
493 <parameter name="Peer" required="true">
494 <para>The peer name you want to check.</para>
498 <para>Show one SIP peer with details on current status.</para>
501 <manager name="SIPqualifypeer" language="en_US">
506 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
507 <parameter name="Peer" required="true">
508 <para>The peer name you want to qualify.</para>
512 <para>Qualify a SIP peer.</para>
515 <manager name="SIPshowregistry" language="en_US">
517 Show SIP registrations (text format).
520 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
523 <para>Lists all registration requests and status. Registrations will follow as separate
524 events. followed by a final event called RegistrationsComplete.</para>
527 <manager name="SIPnotify" language="en_US">
532 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
533 <parameter name="Channel" required="true">
534 <para>Peer to receive the notify.</para>
536 <parameter name="Variable" required="true">
537 <para>At least one variable pair must be specified.
538 <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
542 <para>Sends a SIP Notify event.</para>
543 <para>All parameters for this event must be specified in the body of this request
544 via multiple Variable: name=value sequences.</para>
549 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
550 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
551 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
552 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
554 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
555 static struct ast_jb_conf default_jbconf =
559 .resync_threshold = -1,
563 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
565 static const char config[] = "sip.conf"; /*!< Main configuration file */
566 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
568 /*! \brief Readable descriptions of device states.
569 * \note Should be aligned to above table as index */
570 static const struct invstate2stringtable {
571 const enum invitestates state;
573 } invitestate2string[] = {
575 {INV_CALLING, "Calling (Trying)"},
576 {INV_PROCEEDING, "Proceeding "},
577 {INV_EARLY_MEDIA, "Early media"},
578 {INV_COMPLETED, "Completed (done)"},
579 {INV_CONFIRMED, "Confirmed (up)"},
580 {INV_TERMINATED, "Done"},
581 {INV_CANCELLED, "Cancelled"}
584 /*! \brief Subscription types that we support. We support
585 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
586 * - SIMPLE presence used for device status
587 * - Voicemail notification subscriptions
589 static const struct cfsubscription_types {
590 enum subscriptiontype type;
591 const char * const event;
592 const char * const mediatype;
593 const char * const text;
594 } subscription_types[] = {
595 { NONE, "-", "unknown", "unknown" },
596 /* RFC 4235: SIP Dialog event package */
597 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
598 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
599 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
600 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
601 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
604 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
605 * structure and then route the messages according to the type.
607 * \note Note that sip_methods[i].id == i must hold or the code breaks
609 static const struct cfsip_methods {
611 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
613 enum can_create_dialog can_create;
615 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
616 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
617 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
618 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
619 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
620 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
621 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
622 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
623 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
624 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
625 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
626 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
627 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
628 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
629 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
630 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
631 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
634 /*! \brief List of well-known SIP options. If we get this in a require,
635 we should check the list and answer accordingly. */
636 static const struct cfsip_options {
637 int id; /*!< Bitmap ID */
638 int supported; /*!< Supported by Asterisk ? */
639 char * const text; /*!< Text id, as in standard */
640 } sip_options[] = { /* XXX used in 3 places */
641 /* RFC3262: PRACK 100% reliability */
642 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
643 /* RFC3959: SIP Early session support */
644 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
645 /* SIMPLE events: RFC4662 */
646 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
647 /* RFC 4916- Connected line ID updates */
648 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
649 /* GRUU: Globally Routable User Agent URI's */
650 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
651 /* RFC4244 History info */
652 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
653 /* RFC3911: SIP Join header support */
654 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
655 /* Disable the REFER subscription, RFC 4488 */
656 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
657 /* SIP outbound - the final NAT battle - draft-sip-outbound */
658 { SIP_OPT_OUTBOUND, NOT_SUPPORTED, "outbound" },
659 /* RFC3327: Path support */
660 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
661 /* RFC3840: Callee preferences */
662 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
663 /* RFC3312: Precondition support */
664 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
665 /* RFC3323: Privacy with proxies*/
666 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
667 /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
668 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
669 /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
670 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
671 /* RFC3891: Replaces: header for transfer */
672 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
673 /* One version of Polycom firmware has the wrong label */
674 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
675 /* RFC4412 Resource priorities */
676 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
677 /* RFC3329: Security agreement mechanism */
678 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
679 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
680 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
681 /* RFC4028: SIP Session-Timers */
682 { SIP_OPT_TIMER, SUPPORTED, "timer" },
683 /* RFC4538: Target-dialog */
684 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
687 /*! \brief Diversion header reasons
689 * The core defines a bunch of constants used to define
690 * redirecting reasons. This provides a translation table
691 * between those and the strings which may be present in
692 * a SIP Diversion header
694 static const struct sip_reasons {
695 enum AST_REDIRECTING_REASON code;
697 } sip_reason_table[] = {
698 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
699 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
700 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
701 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
702 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
703 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
704 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
705 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
706 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
707 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
708 { AST_REDIRECTING_REASON_AWAY, "away" },
709 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
713 /*! \name DefaultSettings
714 Default setttings are used as a channel setting and as a default when
718 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
719 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
720 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
721 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
722 static int default_fromdomainport; /*!< Default domain port on outbound messages */
723 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
724 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
725 static int default_qualify; /*!< Default Qualify= setting */
726 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
727 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
728 * a bridged channel on hold */
729 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
730 static char default_engine[256]; /*!< Default RTP engine */
731 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
732 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
733 static unsigned int default_transports; /*!< Default Transports (enum sip_transport) that are acceptable */
734 static unsigned int default_primary_transport; /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
737 static struct sip_settings sip_cfg; /*!< SIP configuration data.
738 \note in the future we could have multiple of these (per domain, per device group etc) */
740 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
741 #define SIP_PEDANTIC_DECODE(str) \
742 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
743 ast_uri_decode(str); \
746 static unsigned int chan_idx; /*!< used in naming sip channel */
747 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
749 static int global_relaxdtmf; /*!< Relax DTMF */
750 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
751 static int global_rtptimeout; /*!< Time out call if no RTP */
752 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
753 static int global_rtpkeepalive; /*!< Send RTP keepalives */
754 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
755 static int global_regattempts_max; /*!< Registration attempts before giving up */
756 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
757 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
758 * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
759 * with just a boolean flag in the device structure */
760 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
761 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
762 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
763 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
764 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
765 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
766 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
767 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
768 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
769 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
770 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
771 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
772 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
773 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
774 static int global_t1; /*!< T1 time */
775 static int global_t1min; /*!< T1 roundtrip time minimum */
776 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
777 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
778 static int global_qualifyfreq; /*!< Qualify frequency */
779 static int global_qualify_gap; /*!< Time between our group of peer pokes */
780 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
782 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
783 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
784 static int global_min_se; /*!< Lowest threshold for session refresh interval */
785 static int global_max_se; /*!< Highest threshold for session refresh interval */
787 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
791 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
792 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
793 * event package. This variable is set at module load time and may be checked at runtime to determine
794 * if XML parsing support was found.
796 static int can_parse_xml;
798 /*! \name Object counters @{
799 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
800 * should be used to modify these values. */
801 static int speerobjs = 0; /*!< Static peers */
802 static int rpeerobjs = 0; /*!< Realtime peers */
803 static int apeerobjs = 0; /*!< Autocreated peer objects */
804 static int regobjs = 0; /*!< Registry objects */
807 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
808 static int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
810 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
812 AST_MUTEX_DEFINE_STATIC(netlock);
814 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
815 when it's doing something critical. */
816 AST_MUTEX_DEFINE_STATIC(monlock);
818 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
820 /*! \brief This is the thread for the monitor which checks for input on the channels
821 which are not currently in use. */
822 static pthread_t monitor_thread = AST_PTHREADT_NULL;
824 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
825 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
827 struct sched_context *sched; /*!< The scheduling context */
828 static struct io_context *io; /*!< The IO context */
829 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
831 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
833 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
835 static enum sip_debug_e sipdebug;
837 /*! \brief extra debugging for 'text' related events.
838 * At the moment this is set together with sip_debug_console.
839 * \note It should either go away or be implemented properly.
841 static int sipdebug_text;
843 static const struct _map_x_s referstatusstrings[] = {
844 { REFER_IDLE, "<none>" },
845 { REFER_SENT, "Request sent" },
846 { REFER_RECEIVED, "Request received" },
847 { REFER_CONFIRMED, "Confirmed" },
848 { REFER_ACCEPTED, "Accepted" },
849 { REFER_RINGING, "Target ringing" },
850 { REFER_200OK, "Done" },
851 { REFER_FAILED, "Failed" },
852 { REFER_NOAUTH, "Failed - auth failure" },
853 { -1, NULL} /* terminator */
856 /* --- Hash tables of various objects --------*/
858 static const int HASH_PEER_SIZE = 17;
859 static const int HASH_DIALOG_SIZE = 17;
861 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
862 static const int HASH_DIALOG_SIZE = 563;
865 static const struct {
866 enum ast_cc_service_type service;
867 const char *service_string;
868 } sip_cc_service_map [] = {
869 [AST_CC_NONE] = { AST_CC_NONE, "" },
870 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
871 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
872 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
875 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
877 enum ast_cc_service_type service;
878 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
879 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
886 static const struct {
887 enum sip_cc_notify_state state;
888 const char *state_string;
889 } sip_cc_notify_state_map [] = {
890 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
891 [CC_READY] = {CC_READY, "cc-state: ready"},
894 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
896 static int sip_epa_register(const struct epa_static_data *static_data)
898 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
904 backend->static_data = static_data;
906 AST_LIST_LOCK(&epa_static_data_list);
907 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
908 AST_LIST_UNLOCK(&epa_static_data_list);
912 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
914 static void cc_epa_destructor(void *data)
916 struct sip_epa_entry *epa_entry = data;
917 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
921 static const struct epa_static_data cc_epa_static_data = {
922 .event = CALL_COMPLETION,
923 .name = "call-completion",
924 .handle_error = cc_handle_publish_error,
925 .destructor = cc_epa_destructor,
928 static const struct epa_static_data *find_static_data(const char * const event_package)
930 const struct epa_backend *backend = NULL;
932 AST_LIST_LOCK(&epa_static_data_list);
933 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
934 if (!strcmp(backend->static_data->name, event_package)) {
938 AST_LIST_UNLOCK(&epa_static_data_list);
939 return backend ? backend->static_data : NULL;
942 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
944 struct sip_epa_entry *epa_entry;
945 const struct epa_static_data *static_data;
947 if (!(static_data = find_static_data(event_package))) {
951 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
955 epa_entry->static_data = static_data;
956 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
961 * Used to create new entity IDs by ESCs.
963 static int esc_etag_counter;
964 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
967 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
969 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
970 .initial_handler = cc_esc_publish_handler,
971 .modify_handler = cc_esc_publish_handler,
976 * \brief The Event State Compositors
978 * An Event State Compositor is an entity which
979 * accepts PUBLISH requests and acts appropriately
980 * based on these requests.
982 * The actual event_state_compositor structure is simply
983 * an ao2_container of sip_esc_entrys. When an incoming
984 * PUBLISH is received, we can match the appropriate sip_esc_entry
985 * using the entity ID of the incoming PUBLISH.
987 static struct event_state_compositor {
988 enum subscriptiontype event;
990 const struct sip_esc_publish_callbacks *callbacks;
991 struct ao2_container *compositor;
992 } event_state_compositors [] = {
994 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
998 static const int ESC_MAX_BUCKETS = 37;
1000 static void esc_entry_destructor(void *obj)
1002 struct sip_esc_entry *esc_entry = obj;
1003 if (esc_entry->sched_id > -1) {
1004 AST_SCHED_DEL(sched, esc_entry->sched_id);
1008 static int esc_hash_fn(const void *obj, const int flags)
1010 const struct sip_esc_entry *entry = obj;
1011 return ast_str_hash(entry->entity_tag);
1014 static int esc_cmp_fn(void *obj, void *arg, int flags)
1016 struct sip_esc_entry *entry1 = obj;
1017 struct sip_esc_entry *entry2 = arg;
1019 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1022 static struct event_state_compositor *get_esc(const char * const event_package) {
1024 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1025 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1026 return &event_state_compositors[i];
1032 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1033 struct sip_esc_entry *entry;
1034 struct sip_esc_entry finder;
1036 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1038 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1043 static int publish_expire(const void *data)
1045 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1046 struct event_state_compositor *esc = get_esc(esc_entry->event);
1048 ast_assert(esc != NULL);
1050 ao2_unlink(esc->compositor, esc_entry);
1051 ao2_ref(esc_entry, -1);
1055 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1057 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1058 struct event_state_compositor *esc = get_esc(esc_entry->event);
1060 ast_assert(esc != NULL);
1062 ao2_unlink(esc->compositor, esc_entry);
1064 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1065 ao2_link(esc->compositor, esc_entry);
1068 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1070 struct sip_esc_entry *esc_entry;
1073 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1077 esc_entry->event = esc->name;
1079 expires_ms = expires * 1000;
1080 /* Bump refcount for scheduler */
1081 ao2_ref(esc_entry, +1);
1082 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1084 /* Note: This links the esc_entry into the ESC properly */
1085 create_new_sip_etag(esc_entry, 0);
1090 static int initialize_escs(void)
1093 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1094 if (!((event_state_compositors[i].compositor) =
1095 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1102 static void destroy_escs(void)
1105 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1106 ao2_ref(event_state_compositors[i].compositor, -1);
1111 * Here we implement the container for dialogs (sip_pvt), defining
1112 * generic wrapper functions to ease the transition from the current
1113 * implementation (a single linked list) to a different container.
1114 * In addition to a reference to the container, we need functions to lock/unlock
1115 * the container and individual items, and functions to add/remove
1116 * references to the individual items.
1118 static struct ao2_container *dialogs;
1119 #define sip_pvt_lock(x) ao2_lock(x)
1120 #define sip_pvt_trylock(x) ao2_trylock(x)
1121 #define sip_pvt_unlock(x) ao2_unlock(x)
1123 /*! \brief The table of TCP threads */
1124 static struct ao2_container *threadt;
1126 /*! \brief The peer list: Users, Peers and Friends */
1127 static struct ao2_container *peers;
1128 static struct ao2_container *peers_by_ip;
1130 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
1131 static struct ast_register_list {
1132 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1136 /*! \brief The MWI subscription list */
1137 static struct ast_subscription_mwi_list {
1138 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1140 static int temp_pvt_init(void *);
1141 static void temp_pvt_cleanup(void *);
1143 /*! \brief A per-thread temporary pvt structure */
1144 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1146 /*! \brief Authentication list for realm authentication
1147 * \todo Move the sip_auth list to AST_LIST */
1148 static struct sip_auth *authl = NULL;
1150 /* --- Sockets and networking --------------*/
1152 /*! \brief Main socket for UDP SIP communication.
1154 * sipsock is shared between the SIP manager thread (which handles reload
1155 * requests), the udp io handler (sipsock_read()) and the user routines that
1156 * issue udp writes (using __sip_xmit()).
1157 * The socket is -1 only when opening fails (this is a permanent condition),
1158 * or when we are handling a reload() that changes its address (this is
1159 * a transient situation during which we might have a harmless race, see
1160 * below). Because the conditions for the race to be possible are extremely
1161 * rare, we don't want to pay the cost of locking on every I/O.
1162 * Rather, we remember that when the race may occur, communication is
1163 * bound to fail anyways, so we just live with this event and let
1164 * the protocol handle this above us.
1166 static int sipsock = -1;
1168 struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
1170 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1171 * internip is initialized picking a suitable address from one of the
1172 * interfaces, and the same port number we bind to. It is used as the
1173 * default address/port in SIP messages, and as the default address
1174 * (but not port) in SDP messages.
1176 static struct sockaddr_in internip;
1178 /*! \brief our external IP address/port for SIP sessions.
1179 * externip.sin_addr is only set when we know we might be behind
1180 * a NAT, and this is done using a variety of (mutually exclusive)
1181 * ways from the config file:
1183 * + with "externip = host[:port]" we specify the address/port explicitly.
1184 * The address is looked up only once when (re)loading the config file;
1186 * + with "externhost = host[:port]" we do a similar thing, but the
1187 * hostname is stored in externhost, and the hostname->IP mapping
1188 * is refreshed every 'externrefresh' seconds;
1190 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1191 * to the specified server, and store the result in externip.
1193 * Other variables (externhost, externexpire, externrefresh) are used
1194 * to support the above functions.
1196 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1197 static struct sockaddr_in media_address; /*!< External RTP IP address if we are behind NAT */
1199 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1200 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1201 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
1202 static struct sockaddr_in stunaddr; /*!< stun server address */
1203 static uint16_t externtcpport; /*!< external tcp port */
1204 static uint16_t externtlsport; /*!< external tls port */
1206 /*! \brief List of local networks
1207 * We store "localnet" addresses from the config file into an access list,
1208 * marked as 'DENY', so the call to ast_apply_ha() will return
1209 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1210 * (i.e. presumably public) addresses.
1212 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1214 static int ourport_tcp; /*!< The port used for TCP connections */
1215 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1216 static struct sockaddr_in debugaddr;
1218 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
1220 /*! some list management macros. */
1222 #define UNLINK(element, head, prev) do { \
1224 (prev)->next = (element)->next; \
1226 (head) = (element)->next; \
1229 /*---------------------------- Forward declarations of functions in chan_sip.c */
1230 /* Note: This is added to help splitting up chan_sip.c into several files
1231 in coming releases. */
1233 /*--- PBX interface functions */
1234 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1235 static int sip_devicestate(void *data);
1236 static int sip_sendtext(struct ast_channel *ast, const char *text);
1237 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1238 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1239 static int sip_hangup(struct ast_channel *ast);
1240 static int sip_answer(struct ast_channel *ast);
1241 static struct ast_frame *sip_read(struct ast_channel *ast);
1242 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1243 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1244 static int sip_transfer(struct ast_channel *ast, const char *dest);
1245 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1246 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1247 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1248 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1249 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1250 static const char *sip_get_callid(struct ast_channel *chan);
1252 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1253 static int sip_standard_port(enum sip_transport type, int port);
1254 static int sip_prepare_socket(struct sip_pvt *p);
1256 /*--- Transmitting responses and requests */
1257 static int sipsock_read(int *id, int fd, short events, void *ignore);
1258 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1259 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1260 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1261 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1262 static int retrans_pkt(const void *data);
1263 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);
1264 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1265 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1266 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1267 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);
1268 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1269 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);
1270 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1271 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1272 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1273 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1274 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1275 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1276 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1277 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1278 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1279 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1280 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1281 static int transmit_refer(struct sip_pvt *p, const char *dest);
1282 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1283 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1284 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1285 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1286 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1287 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1288 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1289 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1290 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1291 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1293 /* Misc dialog routines */
1294 static int __sip_autodestruct(const void *data);
1295 static void *registry_unref(struct sip_registry *reg, char *tag);
1296 static int update_call_counter(struct sip_pvt *fup, int event);
1297 static int auto_congest(const void *arg);
1298 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1299 static void free_old_route(struct sip_route *route);
1300 static void list_route(struct sip_route *route);
1301 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1302 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1303 struct sip_request *req, const char *uri);
1304 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1305 static void check_pendings(struct sip_pvt *p);
1306 static void *sip_park_thread(void *stuff);
1307 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1308 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1309 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1311 /*--- Codec handling / SDP */
1312 static void try_suggested_sip_codec(struct sip_pvt *p);
1313 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1314 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1315 static int find_sdp(struct sip_request *req);
1316 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1317 static int process_sdp_o(const char *o, struct sip_pvt *p);
1318 static int process_sdp_c(const char *c, struct ast_hostent *hp);
1319 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1320 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1321 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1322 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);
1323 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1324 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1325 struct ast_str **m_buf, struct ast_str **a_buf,
1326 int debug, int *min_packet_size);
1327 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1328 struct ast_str **m_buf, struct ast_str **a_buf,
1330 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1331 static void do_setnat(struct sip_pvt *p);
1332 static void stop_media_flows(struct sip_pvt *p);
1334 /*--- Authentication stuff */
1335 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1336 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1337 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1338 const char *secret, const char *md5secret, int sipmethod,
1339 const char *uri, enum xmittype reliable, int ignore);
1340 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1341 int sipmethod, const char *uri, enum xmittype reliable,
1342 struct sockaddr_in *sin, struct sip_peer **authpeer);
1343 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1345 /*--- Domain handling */
1346 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1347 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1348 static void clear_sip_domains(void);
1350 /*--- SIP realm authentication */
1351 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1352 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1353 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1355 /*--- Misc functions */
1356 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1357 static int sip_do_reload(enum channelreloadreason reason);
1358 static int reload_config(enum channelreloadreason reason);
1359 static int expire_register(const void *data);
1360 static void *do_monitor(void *data);
1361 static int restart_monitor(void);
1362 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1363 static struct ast_variable *copy_vars(struct ast_variable *src);
1364 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1365 static int sip_refer_allocate(struct sip_pvt *p);
1366 static int sip_notify_allocate(struct sip_pvt *p);
1367 static void ast_quiet_chan(struct ast_channel *chan);
1368 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1369 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1371 /*--- Device monitoring and Device/extension state/event handling */
1372 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1373 static int sip_devicestate(void *data);
1374 static int sip_poke_noanswer(const void *data);
1375 static int sip_poke_peer(struct sip_peer *peer, int force);
1376 static void sip_poke_all_peers(void);
1377 static void sip_peer_hold(struct sip_pvt *p, int hold);
1378 static void mwi_event_cb(const struct ast_event *, void *);
1380 /*--- Applications, functions, CLI and manager command helpers */
1381 static const char *sip_nat_mode(const struct sip_pvt *p);
1382 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1383 static char *transfermode2str(enum transfermodes mode) attribute_const;
1384 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1385 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1387 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1388 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1389 static void print_group(int fd, ast_group_t group, int crlf);
1390 static const char *dtmfmode2str(int mode) attribute_const;
1391 static int str2dtmfmode(const char *str) attribute_unused;
1392 static const char *insecure2str(int mode) attribute_const;
1393 static void cleanup_stale_contexts(char *new, char *old);
1394 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1395 static const char *domain_mode_to_text(const enum domain_mode mode);
1396 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1397 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1398 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1399 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1400 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1401 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1402 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1403 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1404 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1405 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1406 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1407 static char *complete_sip_peer(const char *word, int state, int flags2);
1408 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1409 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1410 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1411 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1412 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1413 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1414 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1415 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1416 static char *sip_do_debug_ip(int fd, const char *arg);
1417 static char *sip_do_debug_peer(int fd, const char *arg);
1418 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1419 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1420 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1421 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1422 static int sip_addheader(struct ast_channel *chan, const char *data);
1423 static int sip_do_reload(enum channelreloadreason reason);
1424 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1427 Functions for enabling debug per IP or fully, or enabling history logging for
1430 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1431 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1432 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1433 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1434 static void sip_dump_history(struct sip_pvt *dialog);
1436 /*--- Device object handling */
1437 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1438 static int update_call_counter(struct sip_pvt *fup, int event);
1439 static void sip_destroy_peer(struct sip_peer *peer);
1440 static void sip_destroy_peer_fn(void *peer);
1441 static void set_peer_defaults(struct sip_peer *peer);
1442 static struct sip_peer *temp_peer(const char *name);
1443 static void register_peer_exten(struct sip_peer *peer, int onoff);
1444 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
1445 static int sip_poke_peer_s(const void *data);
1446 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1447 static void reg_source_db(struct sip_peer *peer);
1448 static void destroy_association(struct sip_peer *peer);
1449 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1450 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1451 static void set_socket_transport(struct sip_socket *socket, int transport);
1453 /* Realtime device support */
1454 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);
1455 static void update_peer(struct sip_peer *p, int expire);
1456 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1457 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1458 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1459 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1461 /*--- Internal UA client handling (outbound registrations) */
1462 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
1463 static void sip_registry_destroy(struct sip_registry *reg);
1464 static int sip_register(const char *value, int lineno);
1465 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1466 static int sip_reregister(const void *data);
1467 static int __sip_do_register(struct sip_registry *r);
1468 static int sip_reg_timeout(const void *data);
1469 static void sip_send_all_registers(void);
1470 static int sip_reinvite_retry(const void *data);
1472 /*--- Parsing SIP requests and responses */
1473 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1474 static int determine_firstline_parts(struct sip_request *req);
1475 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1476 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1477 static int find_sip_method(const char *msg);
1478 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1479 static unsigned int parse_allowed_methods(struct sip_request *req);
1480 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1481 static int parse_request(struct sip_request *req);
1482 static const char *get_header(const struct sip_request *req, const char *name);
1483 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1484 static int method_match(enum sipmethod id, const char *name);
1485 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1486 static const char *find_alias(const char *name, const char *_default);
1487 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1488 static int lws2sws(char *msgbuf, int len);
1489 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1490 static char *remove_uri_parameters(char *uri);
1491 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1492 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1493 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1494 static int set_address_from_contact(struct sip_pvt *pvt);
1495 static void check_via(struct sip_pvt *p, struct sip_request *req);
1496 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1497 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1498 static int get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1499 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1500 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1501 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1502 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1503 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);
1504 static int get_domain(const char *str, char *domain, int len);
1505 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1507 /*-- TCP connection handling ---*/
1508 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1509 static void *sip_tcp_worker_fn(void *);
1511 /*--- Constructing requests and responses */
1512 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1513 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1514 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1515 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1516 static int init_resp(struct sip_request *resp, const char *msg);
1517 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1518 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1519 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1520 static void build_via(struct sip_pvt *p);
1521 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1522 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog, struct sockaddr_in *remote_address);
1523 static char *generate_random_string(char *buf, size_t size);
1524 static void build_callid_pvt(struct sip_pvt *pvt);
1525 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1526 static void make_our_tag(char *tagbuf, size_t len);
1527 static int add_header(struct sip_request *req, const char *var, const char *value);
1528 static int add_header_contentLength(struct sip_request *req, int len);
1529 static int add_line(struct sip_request *req, const char *line);
1530 static int add_text(struct sip_request *req, const char *text);
1531 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1532 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1533 static int add_vidupdate(struct sip_request *req);
1534 static void add_route(struct sip_request *req, struct sip_route *route);
1535 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1536 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1537 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1538 static void set_destination(struct sip_pvt *p, char *uri);
1539 static void append_date(struct sip_request *req);
1540 static void build_contact(struct sip_pvt *p);
1542 /*------Request handling functions */
1543 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1544 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1545 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);
1546 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1547 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1548 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, const char *e);
1549 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1550 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1551 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1552 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1553 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1554 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
1555 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1556 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1558 /*------Response handling functions */
1559 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1560 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1561 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1562 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1563 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1564 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1565 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1567 /*------ T38 Support --------- */
1568 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1569 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1570 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1571 static void change_t38_state(struct sip_pvt *p, int state);
1573 /*------ Session-Timers functions --------- */
1574 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1575 static int proc_session_timer(const void *vp);
1576 static void stop_session_timer(struct sip_pvt *p);
1577 static void start_session_timer(struct sip_pvt *p);
1578 static void restart_session_timer(struct sip_pvt *p);
1579 static const char *strefresher2str(enum st_refresher r);
1580 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1581 static int parse_minse(const char *p_hdrval, int *const p_interval);
1582 static int st_get_se(struct sip_pvt *, int max);
1583 static enum st_refresher st_get_refresher(struct sip_pvt *);
1584 static enum st_mode st_get_mode(struct sip_pvt *);
1585 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1587 /*------- RTP Glue functions -------- */
1588 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);
1590 /*!--- SIP MWI Subscription support */
1591 static int sip_subscribe_mwi(const char *value, int lineno);
1592 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1593 static void sip_send_all_mwi_subscriptions(void);
1594 static int sip_subscribe_mwi_do(const void *data);
1595 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1597 /*! \brief Definition of this channel for PBX channel registration */
1598 const struct ast_channel_tech sip_tech = {
1600 .description = "Session Initiation Protocol (SIP)",
1601 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
1602 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1603 .requester = sip_request_call, /* called with chan unlocked */
1604 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1605 .call = sip_call, /* called with chan locked */
1606 .send_html = sip_sendhtml,
1607 .hangup = sip_hangup, /* called with chan locked */
1608 .answer = sip_answer, /* called with chan locked */
1609 .read = sip_read, /* called with chan locked */
1610 .write = sip_write, /* called with chan locked */
1611 .write_video = sip_write, /* called with chan locked */
1612 .write_text = sip_write,
1613 .indicate = sip_indicate, /* called with chan locked */
1614 .transfer = sip_transfer, /* called with chan locked */
1615 .fixup = sip_fixup, /* called with chan locked */
1616 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1617 .send_digit_end = sip_senddigit_end,
1618 .bridge = ast_rtp_instance_bridge, /* XXX chan unlocked ? */
1619 .early_bridge = ast_rtp_instance_early_bridge,
1620 .send_text = sip_sendtext, /* called with chan locked */
1621 .func_channel_read = sip_acf_channel_read,
1622 .setoption = sip_setoption,
1623 .queryoption = sip_queryoption,
1624 .get_pvt_uniqueid = sip_get_callid,
1627 /*! \brief This version of the sip channel tech has no send_digit_begin
1628 * callback so that the core knows that the channel does not want
1629 * DTMF BEGIN frames.
1630 * The struct is initialized just before registering the channel driver,
1631 * and is for use with channels using SIP INFO DTMF.
1633 struct ast_channel_tech sip_tech_info;
1635 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1636 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1637 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1638 static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1639 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1640 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1641 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1642 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1644 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1646 .init = sip_cc_agent_init,
1647 .start_offer_timer = sip_cc_agent_start_offer_timer,
1648 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1649 .ack = sip_cc_agent_ack,
1650 .status_request = sip_cc_agent_status_request,
1651 .start_monitoring = sip_cc_agent_start_monitoring,
1652 .callee_available = sip_cc_agent_recall,
1653 .destructor = sip_cc_agent_destructor,
1656 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1658 struct ast_cc_agent *agent = obj;
1659 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1660 const char *uri = arg;
1662 return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1665 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1667 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1671 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1673 struct ast_cc_agent *agent = obj;
1674 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1675 const char *uri = arg;
1677 return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1680 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1682 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1686 static int find_by_callid_helper(void *obj, void *arg, int flags)
1688 struct ast_cc_agent *agent = obj;
1689 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1690 struct sip_pvt *call_pvt = arg;
1692 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1695 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1697 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1701 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1703 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1704 struct sip_pvt *call_pvt = chan->tech_pvt;
1710 ast_assert(!strcmp(chan->tech->type, "SIP"));
1712 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1713 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1714 agent_pvt->offer_timer_id = -1;
1715 agent->private_data = agent_pvt;
1716 sip_pvt_lock(call_pvt);
1717 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1718 sip_pvt_unlock(call_pvt);
1722 static int sip_offer_timer_expire(const void *data)
1724 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1725 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1727 agent_pvt->offer_timer_id = -1;
1729 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1732 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1734 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1737 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1738 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1742 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1744 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1746 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1750 static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1752 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1754 sip_pvt_lock(agent_pvt->subscribe_pvt);
1755 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1756 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1757 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1758 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1759 agent_pvt->is_available = TRUE;
1762 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1764 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1765 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1766 return ast_cc_agent_status_response(agent->core_id, state);
1769 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1771 /* To start monitoring just means to wait for an incoming PUBLISH
1772 * to tell us that the caller has become available again. No special
1778 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1780 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1781 /* If we have received a PUBLISH beforehand stating that the caller in question
1782 * is not available, we can save ourself a bit of effort here and just report
1783 * the caller as busy
1785 if (!agent_pvt->is_available) {
1786 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1787 agent->device_name);
1789 /* Otherwise, we transmit a NOTIFY to the caller and await either
1790 * a PUBLISH or an INVITE
1792 sip_pvt_lock(agent_pvt->subscribe_pvt);
1793 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1794 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1798 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1800 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1803 /* The agent constructor probably failed. */
1807 sip_cc_agent_stop_offer_timer(agent);
1808 if (agent_pvt->subscribe_pvt) {
1809 sip_pvt_lock(agent_pvt->subscribe_pvt);
1810 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1811 /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1812 * the subscriber know something went wrong
1814 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1816 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1817 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1819 ast_free(agent_pvt);
1822 struct ao2_container *sip_monitor_instances;
1824 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1826 const struct sip_monitor_instance *monitor_instance = obj;
1827 return monitor_instance->core_id;
1830 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1832 struct sip_monitor_instance *monitor_instance1 = obj;
1833 struct sip_monitor_instance *monitor_instance2 = arg;
1835 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1838 static void sip_monitor_instance_destructor(void *data)
1840 struct sip_monitor_instance *monitor_instance = data;
1841 if (monitor_instance->subscription_pvt) {
1842 sip_pvt_lock(monitor_instance->subscription_pvt);
1843 monitor_instance->subscription_pvt->expiry = 0;
1844 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1845 sip_pvt_unlock(monitor_instance->subscription_pvt);
1846 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1848 if (monitor_instance->suspension_entry) {
1849 monitor_instance->suspension_entry->body[0] = '\0';
1850 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1851 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1853 ast_string_field_free_memory(monitor_instance);
1856 static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
1858 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1860 if (!monitor_instance) {
1864 if (ast_string_field_init(monitor_instance, 256)) {
1865 ao2_ref(monitor_instance, -1);
1869 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1870 ast_string_field_set(monitor_instance, peername, peername);
1871 ast_string_field_set(monitor_instance, device_name, device_name);
1872 monitor_instance->core_id = core_id;
1873 ao2_link(sip_monitor_instances, monitor_instance);
1874 return monitor_instance;
1877 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1879 struct sip_monitor_instance *monitor_instance = obj;
1880 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1883 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1885 struct sip_monitor_instance *monitor_instance = obj;
1886 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1889 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1890 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1891 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1892 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1893 static void sip_cc_monitor_destructor(void *private_data);
1895 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1897 .request_cc = sip_cc_monitor_request_cc,
1898 .suspend = sip_cc_monitor_suspend,
1899 .unsuspend = sip_cc_monitor_unsuspend,
1900 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1901 .destructor = sip_cc_monitor_destructor,
1904 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1906 struct sip_monitor_instance *monitor_instance = monitor->private_data;
1907 enum ast_cc_service_type service = monitor->service_offered;
1910 if (!monitor_instance) {
1914 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1918 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1919 ast_get_ccnr_available_timer(monitor->interface->config_params);
1921 sip_pvt_lock(monitor_instance->subscription_pvt);
1922 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1923 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa.sin_addr, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1924 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1925 monitor_instance->subscription_pvt->expiry = when;
1927 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1928 sip_pvt_unlock(monitor_instance->subscription_pvt);
1930 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1931 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1935 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1937 struct ast_str *body = ast_str_alloca(size);
1940 generate_random_string(tuple_id, sizeof(tuple_id));
1942 /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1943 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1945 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1946 /* XXX The entity attribute is currently set to the peer name associated with the
1947 * dialog. This is because we currently only call this function for call-completion
1948 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1949 * event packages, it may be crucial to have a proper URI as the presentity so this
1950 * should be revisited as support is expanded.
1952 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1953 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1954 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1955 ast_str_append(&body, 0, "</tuple>\n");
1956 ast_str_append(&body, 0, "</presence>\n");
1957 ast_copy_string(pidf_body, ast_str_buffer(body), size);
1961 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1963 struct sip_monitor_instance *monitor_instance = monitor->private_data;
1964 enum sip_publish_type publish_type;
1965 struct cc_epa_entry *cc_entry;
1967 if (!monitor_instance) {
1971 if (!monitor_instance->suspension_entry) {
1972 /* We haven't yet allocated the suspension entry, so let's give it a shot */
1973 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1974 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1975 ao2_ref(monitor_instance, -1);
1978 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1979 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1980 ao2_ref(monitor_instance, -1);
1983 cc_entry->core_id = monitor->core_id;
1984 monitor_instance->suspension_entry->instance_data = cc_entry;
1985 publish_type = SIP_PUBLISH_INITIAL;
1987 publish_type = SIP_PUBLISH_MODIFY;
1988 cc_entry = monitor_instance->suspension_entry->instance_data;
1991 cc_entry->current_state = CC_CLOSED;
1993 if (ast_strlen_zero(monitor_instance->notify_uri)) {
1994 /* If we have no set notify_uri, then what this means is that we have
1995 * not received a NOTIFY from this destination stating that he is
1996 * currently available.
1998 * This situation can arise when the core calls the suspend callbacks
1999 * of multiple destinations. If one of the other destinations aside
2000 * from this one notified Asterisk that he is available, then there
2001 * is no reason to take any suspension action on this device. Rather,
2002 * we should return now and if we receive a NOTIFY while monitoring
2003 * is still "suspended" then we can immediately respond with the
2004 * proper PUBLISH to let this endpoint know what is going on.
2008 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2009 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2012 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2014 struct sip_monitor_instance *monitor_instance = monitor->private_data;
2015 struct cc_epa_entry *cc_entry;
2017 if (!monitor_instance) {
2021 ast_assert(monitor_instance->suspension_entry != NULL);
2023 cc_entry = monitor_instance->suspension_entry->instance_data;
2024 cc_entry->current_state = CC_OPEN;
2025 if (ast_strlen_zero(monitor_instance->notify_uri)) {
2026 /* This means we are being asked to unsuspend a call leg we never
2027 * sent a PUBLISH on. As such, there is no reason to send another
2028 * PUBLISH at this point either. We can just return instead.
2032 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2033 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2036 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2038 if (*sched_id != -1) {
2039 AST_SCHED_DEL(sched, *sched_id);
2040 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2045 static void sip_cc_monitor_destructor(void *private_data)
2047 struct sip_monitor_instance *monitor_instance = private_data;
2048 ao2_unlink(sip_monitor_instances, monitor_instance);
2049 ast_module_unref(ast_module_info->self);
2052 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2054 char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2058 static const char cc_purpose[] = "purpose=call-completion";
2059 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2061 if (ast_strlen_zero(call_info)) {
2062 /* No Call-Info present. Definitely no CC offer */
2066 uri = strsep(&call_info, ";");
2068 while ((purpose = strsep(&call_info, ";"))) {
2069 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2074 /* We didn't find the appropriate purpose= parameter. Oh well */
2078 /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2079 while ((service_str = strsep(&call_info, ";"))) {
2080 if (!strncmp(service_str, "m=", 2)) {
2085 /* So they didn't offer a particular service, We'll just go with CCBS since it really
2086 * doesn't matter anyway
2090 /* We already determined that there is an "m=" so no need to check
2091 * the result of this strsep
2093 strsep(&service_str, "=");
2096 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2097 /* Invalid service offered */
2101 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2107 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2109 * After taking care of some formalities to be sure that this call is eligible for CC,
2110 * we first try to see if we can make use of native CC. We grab the information from
2111 * the passed-in sip_request (which is always a response to an INVITE). If we can
2112 * use native CC monitoring for the call, then so be it.
2114 * If native cc monitoring is not possible or not supported, then we will instead attempt
2115 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2116 * monitoring will only work if the monitor policy of the endpoint is "always"
2118 * \param pvt The current dialog. Contains CC parameters for the endpoint
2119 * \param req The response to the INVITE we want to inspect
2120 * \param service The service to use if generic monitoring is to be used. For native
2121 * monitoring, we get the service from the SIP response itself
2123 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2125 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2127 char interface_name[AST_CHANNEL_NAME];
2129 if (monitor_policy == AST_CC_MONITOR_NEVER) {
2130 /* Don't bother, just return */
2134 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2135 /* For some reason, CC is invalid, so don't try it! */
2139 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2141 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2142 char subscribe_uri[SIPBUFSIZE];
2143 char device_name[AST_CHANNEL_NAME];
2144 enum ast_cc_service_type offered_service;
2145 struct sip_monitor_instance *monitor_instance;
2146 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2147 /* If CC isn't being offered to us, or for some reason the CC offer is
2148 * not formatted correctly, then it may still be possible to use generic
2149 * call completion since the monitor policy may be "always"
2153 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2154 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2155 /* Same deal. We can try using generic still */
2158 /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2159 * will have a reference to callbacks in this module. We decrement the module
2160 * refcount once the monitor destructor is called
2162 ast_module_ref(ast_module_info->self);
2163 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2164 ao2_ref(monitor_instance, -1);
2169 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2170 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2174 /*! \brief Working TLS connection configuration */
2175 static struct ast_tls_config sip_tls_cfg;
2177 /*! \brief Default TLS connection configuration */
2178 static struct ast_tls_config default_tls_cfg;
2180 /*! \brief The TCP server definition */
2181 static struct ast_tcptls_session_args sip_tcp_desc = {
2183 .master = AST_PTHREADT_NULL,
2186 .name = "SIP TCP server",
2187 .accept_fn = ast_tcptls_server_root,
2188 .worker_fn = sip_tcp_worker_fn,
2191 /*! \brief The TCP/TLS server definition */
2192 static struct ast_tcptls_session_args sip_tls_desc = {
2194 .master = AST_PTHREADT_NULL,
2195 .tls_cfg = &sip_tls_cfg,
2197 .name = "SIP TLS server",
2198 .accept_fn = ast_tcptls_server_root,
2199 .worker_fn = sip_tcp_worker_fn,
2202 /*! \brief Append to SIP dialog history
2203 \return Always returns 0 */
2204 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2206 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2210 __ao2_ref_debug(p, 1, tag, file, line, func);
2215 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2219 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2223 __ao2_ref_debug(p, -1, tag, file, line, func);
2230 /*! \brief map from an integer value to a string.
2231 * If no match is found, return errorstring
2233 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2235 const struct _map_x_s *cur;
2237 for (cur = table; cur->s; cur++)
2243 /*! \brief map from a string to an integer value, case insensitive.
2244 * If no match is found, return errorvalue.
2246 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2248 const struct _map_x_s *cur;
2250 for (cur = table; cur->s; cur++)
2251 if (!strcasecmp(cur->s, s))
2256 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2258 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2261 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2262 if (!strcasecmp(text, sip_reason_table[i].text)) {
2263 ast = sip_reason_table[i].code;
2271 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2273 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2274 return sip_reason_table[code].text;
2281 * \brief generic function for determining if a correct transport is being
2282 * used to contact a peer
2284 * this is done as a macro so that the "tmpl" var can be passed either a
2285 * sip_request or a sip_peer
2287 #define check_request_transport(peer, tmpl) ({ \
2289 if (peer->socket.type == tmpl->socket.type) \
2291 else if (!(peer->transports & tmpl->socket.type)) {\
2292 ast_log(LOG_ERROR, \
2293 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2294 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2297 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2298 ast_log(LOG_WARNING, \
2299 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2300 peer->name, get_transport(tmpl->socket.type) \
2304 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2305 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2312 * duplicate a list of channel variables, \return the copy.
2314 static struct ast_variable *copy_vars(struct ast_variable *src)
2316 struct ast_variable *res = NULL, *tmp, *v = NULL;
2318 for (v = src ; v ; v = v->next) {
2319 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2327 static void tcptls_packet_destructor(void *obj)
2329 struct tcptls_packet *packet = obj;
2331 ast_free(packet->data);
2334 static void sip_tcptls_client_args_destructor(void *obj)
2336 struct ast_tcptls_session_args *args = obj;
2337 if (args->tls_cfg) {
2338 ast_free(args->tls_cfg->certfile);
2339 ast_free(args->tls_cfg->pvtfile);
2340 ast_free(args->tls_cfg->cipher);
2341 ast_free(args->tls_cfg->cafile);
2342 ast_free(args->tls_cfg->capath);
2344 ast_free(args->tls_cfg);
2345 ast_free((char *) args->name);
2348 static void sip_threadinfo_destructor(void *obj)
2350 struct sip_threadinfo *th = obj;
2351 struct tcptls_packet *packet;
2352 if (th->alert_pipe[1] > -1) {
2353 close(th->alert_pipe[0]);
2355 if (th->alert_pipe[1] > -1) {
2356 close(th->alert_pipe[1]);
2358 th->alert_pipe[0] = th->alert_pipe[1] = -1;
2360 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2361 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2364 if (th->tcptls_session) {
2365 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2369 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2370 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2372 struct sip_threadinfo *th;
2374 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2378 th->alert_pipe[0] = th->alert_pipe[1] = -1;
2380 if (pipe(th->alert_pipe) == -1) {
2381 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2382 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2385 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2386 th->tcptls_session = tcptls_session;
2387 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2388 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2389 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2393 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2394 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2397 struct sip_threadinfo *th = NULL;
2398 struct tcptls_packet *packet = NULL;
2399 struct sip_threadinfo tmp = {
2400 .tcptls_session = tcptls_session,
2402 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2404 if (!tcptls_session) {
2408 ast_mutex_lock(&tcptls_session->lock);
2410 if ((tcptls_session->fd == -1) ||
2411 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2412 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2413 !(packet->data = ast_str_create(len))) {
2414 goto tcptls_write_setup_error;
2417 /* goto tcptls_write_error should _NOT_ be used beyond this point */
2418 ast_str_set(&packet->data, 0, "%s", (char *) buf);
2421 /* alert tcptls thread handler that there is a packet to be sent.
2422 * must lock the thread info object to guarantee control of the
2425 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2426 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2427 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2430 } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2431 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2435 ast_mutex_unlock(&tcptls_session->lock);
2436 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2439 tcptls_write_setup_error:
2441 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2444 ao2_t_ref(packet, -1, "could not allocate packet's data");
2446 ast_mutex_unlock(&tcptls_session->lock);
2451 /*! \brief SIP TCP connection handler */
2452 static void *sip_tcp_worker_fn(void *data)
2454 struct ast_tcptls_session_instance *tcptls_session = data;
2456 return _sip_tcp_helper_thread(NULL, tcptls_session);
2459 /*! \brief SIP TCP thread management function
2460 This function reads from the socket, parses the packet into a request
2462 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2465 struct sip_request req = { 0, } , reqcpy = { 0, };
2466 struct sip_threadinfo *me = NULL;
2467 char buf[1024] = "";
2468 struct pollfd fds[2] = { { 0 }, { 0 }, };
2469 struct ast_tcptls_session_args *ca = NULL;
2471 /* If this is a server session, then the connection has already been setup,
2472 * simply create the threadinfo object so we can access this thread for writing.
2474 * if this is a client connection more work must be done.
2475 * 1. We own the parent session args for a client connection. This pointer needs
2476 * to be held on to so we can decrement it's ref count on thread destruction.
2477 * 2. The threadinfo object was created before this thread was launched, however
2478 * it must be found within the threadt table.
2479 * 3. Last, the tcptls_session must be started.
2481 if (!tcptls_session->client) {
2482 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2485 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2487 struct sip_threadinfo tmp = {
2488 .tcptls_session = tcptls_session,
2491 if ((!(ca = tcptls_session->parent)) ||
2492 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2493 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2498 me->threadid = pthread_self();
2499 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2501 /* set up pollfd to watch for reads on both the socket and the alert_pipe */
2502 fds[0].fd = tcptls_session->fd;
2503 fds[1].fd = me->alert_pipe[0];
2504 fds[0].events = fds[1].events = POLLIN | POLLPRI;
2506 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2508 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2512 struct ast_str *str_save;
2514 res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2516 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2520 /* handle the socket event, check for both reads from the socket fd,
2521 * and writes from alert_pipe fd */
2522 if (fds[0].revents) { /* there is data on the socket to be read */
2526 /* clear request structure */
2527 str_save = req.data;
2528 memset(&req, 0, sizeof(req));
2529 req.data = str_save;
2530 ast_str_reset(req.data);
2532 str_save = reqcpy.data;
2533 memset(&reqcpy, 0, sizeof(reqcpy));
2534 reqcpy.data = str_save;
2535 ast_str_reset(reqcpy.data);
2537 memset(buf, 0, sizeof(buf));
2539 if (tcptls_session->ssl) {
2540 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2541 req.socket.port = htons(ourport_tls);
2543 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2544 req.socket.port = htons(ourport_tcp);
2546 req.socket.fd = tcptls_session->fd;
2548 /* Read in headers one line at a time */
2549 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
2550 ast_mutex_lock(&tcptls_session->lock);
2551 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2552 ast_mutex_unlock(&tcptls_session->lock);
2555 ast_mutex_unlock(&tcptls_session->lock);
2558 ast_str_append(&req.data, 0, "%s", buf);
2559 req.len = req.data->used;
2561 copy_request(&reqcpy, &req);
2562 parse_request(&reqcpy);
2563 /* In order to know how much to read, we need the content-length header */
2564 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2567 ast_mutex_lock(&tcptls_session->lock);
2568 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2569 ast_mutex_unlock(&tcptls_session->lock);
2572 buf[bytes_read] = '\0';
2573 ast_mutex_unlock(&tcptls_session->lock);
2577 ast_str_append(&req.data, 0, "%s", buf);
2578 req.len = req.data->used;
2581 /*! \todo XXX If there's no Content-Length or if the content-length and what
2582 we receive is not the same - we should generate an error */
2584 req.socket.tcptls_session = tcptls_session;
2585 handle_request_do(&req, &tcptls_session->remote_address);
2588 if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2589 enum sip_tcptls_alert alert;
2590 struct tcptls_packet *packet;
2594 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2595 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2600 case TCPTLS_ALERT_STOP:
2602 case TCPTLS_ALERT_DATA:
2604 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2605 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2606 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2607 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2611 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2616 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2621 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2625 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2626 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2629 ast_free(reqcpy.data);
2637 /* if client, we own the parent session arguments and must decrement ref */
2639 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2642 if (tcptls_session) {
2643 ast_mutex_lock(&tcptls_session->lock);
2644 if (tcptls_session->f) {
2645 fclose(tcptls_session->f);
2646 tcptls_session->f = NULL;
2648 if (tcptls_session->fd != -1) {
2649 close(tcptls_session->fd);
2650 tcptls_session->fd = -1;
2652 tcptls_session->parent = NULL;
2653 ast_mutex_unlock(&tcptls_session->lock);
2655 ao2_ref(tcptls_session, -1);
2656 tcptls_session = NULL;
2663 * helper functions to unreference various types of objects.
2664 * By handling them this way, we don't have to declare the
2665 * destructor on each call, which removes the chance of errors.
2667 static void *unref_peer(struct sip_peer *peer, char *tag)
2669 ao2_t_ref(peer, -1, tag);
2673 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2675 ao2_t_ref(peer, 1, tag);
2679 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2681 * This function sets pvt's outboundproxy pointer to the one referenced
2682 * by the proxy parameter. Because proxy may be a refcounted object, and
2683 * because pvt's old outboundproxy may also be a refcounted object, we need
2684 * to maintain the proper refcounts.
2686 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2687 * \param proxy The sip_proxy which we will point pvt towards.
2688 * \return Returns void
2690 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2692 struct sip_proxy *old_obproxy = pvt->outboundproxy;
2693 /* The sip_cfg.outboundproxy is statically allocated, and so
2694 * we don't ever need to adjust refcounts for it
2696 if (proxy && proxy != &sip_cfg.outboundproxy) {
2699 pvt->outboundproxy = proxy;
2700 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2701 ao2_ref(old_obproxy, -1);
2706 * \brief Unlink a dialog from the dialogs container, as well as any other places
2707 * that it may be currently stored.
2709 * \note A reference to the dialog must be held before calling this function, and this
2710 * function does not release that reference.
2712 void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2716 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2718 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2720 /* Unlink us from the owner (channel) if we have one */
2721 if (dialog->owner) {
2723 ast_channel_lock(dialog->owner);
2724 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2725 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2727 ast_channel_unlock(dialog->owner);
2729 if (dialog->registry) {
2730 if (dialog->registry->call == dialog)
2731 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2732 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2734 if (dialog->stateid > -1) {
2735 ast_extension_state_del(dialog->stateid, NULL);
2736 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2737 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2739 /* Remove link from peer to subscription of MWI */
2740 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2741 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2742 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2743 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2745 /* remove all current packets in this dialog */
2746 while((cp = dialog->packets)) {
2747 dialog->packets = dialog->packets->next;
2748 AST_SCHED_DEL(sched, cp->retransid);
2749 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2756 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"));
2758 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"));
2760 if (dialog->autokillid > -1)
2761 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"));
2763 if (dialog->request_queue_sched_id > -1) {
2764 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"));
2767 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"));
2769 if (dialog->t38id > -1) {
2770 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"));
2773 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2777 void *registry_unref(struct sip_registry *reg, char *tag)
2779 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2780 ASTOBJ_UNREF(reg, sip_registry_destroy);
2784 /*! \brief Add object reference to SIP registry */
2785 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2787 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2788 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2791 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2792 static struct ast_udptl_protocol sip_udptl = {
2794 get_udptl_info: sip_get_udptl_peer,
2795 set_udptl_peer: sip_set_udptl_peer,
2798 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2799 __attribute__((format(printf, 2, 3)));
2802 /*! \brief Convert transfer status to string */
2803 static const char *referstatus2str(enum referstatus rstatus)
2805 return map_x_s(referstatusstrings, rstatus, "");
2808 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2810 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2811 pvt->needdestroy = 1;
2814 /*! \brief Initialize the initital request packet in the pvt structure.
2815 This packet is used for creating replies and future requests in
2817 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2819 if (p->initreq.headers)
2820 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2822 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2823 /* Use this as the basis */
2824 copy_request(&p->initreq, req);
2825 parse_request(&p->initreq);
2827 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2830 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2831 static void sip_alreadygone(struct sip_pvt *dialog)
2833 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2834 dialog->alreadygone = 1;
2837 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2838 static int proxy_update(struct sip_proxy *proxy)
2840 /* if it's actually an IP address and not a name,
2841 there's no need for a managed lookup */
2842 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2843 /* Ok, not an IP address, then let's check if it's a domain or host */
2844 /* XXX Todo - if we have proxy port, don't do SRV */
2845 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2846 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2850 proxy->last_dnsupdate = time(NULL);
2854 /*! \brief converts ascii port to int representation. If no
2855 * pt buffer is provided or the pt has errors when being converted
2856 * to an int value, the port provided as the standard is used.
2858 unsigned int port_str2int(const char *pt, unsigned int standard)
2860 int port = standard;
2861 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2868 /*! \brief Allocate and initialize sip proxy */
2869 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2871 struct sip_proxy *proxy;
2873 if (ast_strlen_zero(name)) {
2877 proxy = ao2_alloc(sizeof(*proxy), NULL);
2880 proxy->force = force;
2881 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2882 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
2883 proxy->ip.sin_family = AF_INET;
2884 proxy_update(proxy);
2888 /*! \brief Get default outbound proxy or global proxy */
2889 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2891 if (peer && peer->outboundproxy) {
2893 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2894 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2895 return peer->outboundproxy;
2897 if (sip_cfg.outboundproxy.name[0]) {
2899 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2900 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2901 return &sip_cfg.outboundproxy;
2904 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2908 /*! \brief returns true if 'name' (with optional trailing whitespace)
2909 * matches the sip method 'id'.
2910 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2911 * a case-insensitive comparison to be more tolerant.
2912 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2914 static int method_match(enum sipmethod id, const char *name)
2916 int len = strlen(sip_methods[id].text);
2917 int l_name = name ? strlen(name) : 0;
2918 /* true if the string is long enough, and ends with whitespace, and matches */
2919 return (l_name >= len && name[len] < 33 &&
2920 !strncasecmp(sip_methods[id].text, name, len));
2923 /*! \brief find_sip_method: Find SIP method from header */
2924 static int find_sip_method(const char *msg)
2928 if (ast_strlen_zero(msg))
2930 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2931 if (method_match(i, msg))
2932 res = sip_methods[i].id;
2937 /*! \brief Parse supported header in incoming packet */
2938 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2942 unsigned int profile = 0;
2945 if (ast_strlen_zero(supported) )
2947 temp = ast_strdupa(supported);
2950 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2952 for (next = temp; next; next = sep) {
2954 if ( (sep = strchr(next, ',')) != NULL)
2956 next = ast_skip_blanks(next);
2958 ast_debug(3, "Found SIP option: -%s-\n", next);
2959 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2960 if (!strcasecmp(next, sip_options[i].text)) {
2961 profile |= sip_options[i].id;
2964 ast_debug(3, "Matched SIP option: %s\n", next);
2969 /* This function is used to parse both Suported: and Require: headers.
2970 Let the caller of this function know that an unknown option tag was
2971 encountered, so that if the UAC requires it then the request can be
2972 rejected with a 420 response. */
2974 profile |= SIP_OPT_UNKNOWN;
2976 if (!found && sipdebug) {
2977 if (!strncasecmp(next, "x-", 2))
2978 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2980 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2985 pvt->sipoptions = profile;
2989 /*! \brief See if we pass debug IP filter */
2990 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2994 if (debugaddr.sin_addr.s_addr) {
2995 if (((ntohs(debugaddr.sin_port) != 0)
2996 && (debugaddr.sin_port != addr->sin_port))
2997 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
3003 /*! \brief The real destination address for a write */
3004 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
3006 if (p->outboundproxy)
3007 return &p->outboundproxy->ip;
3009 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;
3012 /*! \brief Display SIP nat mode */
3013 static const char *sip_nat_mode(const struct sip_pvt *p)
3015 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3018 /*! \brief Test PVT for debugging output */
3019 static inline int sip_debug_test_pvt(struct sip_pvt *p)
3023 return sip_debug_test_addr(sip_real_dst(p));
3026 /*! \brief Return int representing a bit field of transport types found in const char *transport */
3027 static int get_transport_str2enum(const char *transport)
3031 if (ast_strlen_zero(transport)) {
3035 if (!strcasecmp(transport, "udp")) {
3036 res |= SIP_TRANSPORT_UDP;
3038 if (!strcasecmp(transport, "tcp")) {
3039 res |= SIP_TRANSPORT_TCP;
3041 if (!strcasecmp(transport, "tls")) {
3042 res |= SIP_TRANSPORT_TLS;
3048 /*! \brief Return configuration of transports for a device */
3049 static inline const char *get_transport_list(unsigned int transports) {
3050 switch (transports) {
3051 case SIP_TRANSPORT_UDP:
3053 case SIP_TRANSPORT_TCP:
3055 case SIP_TRANSPORT_TLS:
3057 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
3059 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
3061 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
3065 "TLS,TCP,UDP" : "UNKNOWN";
3069 /*! \brief Return transport as string */
3070 static inline const char *get_transport(enum sip_transport t)
3073 case SIP_TRANSPORT_UDP:
3075 case SIP_TRANSPORT_TCP:
3077 case SIP_TRANSPORT_TLS:
3084 /*! \brief Return transport of dialog.
3085 \note this is based on a false assumption. We don't always use the
3086 outbound proxy for all requests in a dialog. It depends on the
3087 "force" parameter. The FIRST request is always sent to the ob proxy.
3088 \todo Fix this function to work correctly
3090 static inline const char *get_transport_pvt(struct sip_pvt *p)
3092 if (p->outboundproxy && p->outboundproxy->transport) {
3093 set_socket_transport(&p->socket, p->outboundproxy->transport);
3096 return get_transport(p->socket.type);
3099 /*! \brief Transmit SIP message
3100 Sends a SIP request or response on a given socket (in the pvt)
3101 Called by retrans_pkt, send_request, send_response and
3103 \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3105 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3108 const struct sockaddr_in *dst = sip_real_dst(p);
3110 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));
3112 if (sip_prepare_socket(p) < 0)
3115 if (p->socket.type == SIP_TRANSPORT_UDP) {
3116 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
3117 } else if (p->socket.tcptls_session) {
3118 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3120 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3126 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3127 case EHOSTUNREACH: /* Host can't be reached */
3128 case ENETDOWN: /* Interface down */
3129 case ENETUNREACH: /* Network failure */
3130 case ECONNREFUSED: /* ICMP port unreachable */
3131 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
3135 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));
3140 /*! \brief Build a Via header for a request */
3141 static void build_via(struct sip_pvt *p)
3143 /* Work around buggy UNIDEN UIP200 firmware */
3144 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3146 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3147 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
3148 get_transport_pvt(p),
3149 ast_inet_ntoa(p->ourip.sin_addr),
3150 ntohs(p->ourip.sin_port), (int) p->branch, rport);
3153 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
3155 * Using the localaddr structure built up with localnet statements in sip.conf
3156 * apply it to their address to see if we need to substitute our
3157 * externip or can get away with our internal bindaddr
3158 * 'us' is always overwritten.
3160 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
3162 struct sockaddr_in theirs;
3163 /* Set want_remap to non-zero if we want to remap 'us' to an externally
3164 * reachable IP address and port. This is done if:
3165 * 1. we have a localaddr list (containing 'internal' addresses marked
3166 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3167 * and AST_SENSE_ALLOW on 'external' ones);
3168 * 2. either stunaddr or externip is set, so we know what to use as the
3169 * externally visible address;
3170 * 3. the remote address, 'them', is external;
3171 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3172 * when passed to ast_apply_ha() so it does need to be remapped.
3173 * This fourth condition is checked later.
3177 *us = internip; /* starting guess for the internal address */
3178 /* now ask the system what would it use to talk to 'them' */
3179 ast_ouraddrfor(them, &us->sin_addr);
3180 theirs.sin_addr = *them;
3182 want_remap = localaddr &&
3183 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
3184 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3187 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
3188 /* if we used externhost or stun, see if it is time to refresh the info */
3189 if (externexpire && time(NULL) >= externexpire) {
3190 if (stunaddr.sin_addr.s_addr) {
3191 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
3193 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
3194 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3196 externexpire = time(NULL) + externrefresh;
3198 if (externip.sin_addr.s_addr) {
3200 switch (p->socket.type) {
3201 case SIP_TRANSPORT_TCP:
3202 us->sin_port = htons(externtcpport);
3204 case SIP_TRANSPORT_TLS:
3205 us->sin_port = htons(externtlsport);
3207 case SIP_TRANSPORT_UDP:
3208 break; /* fall through */
3210 us->sin_port = htons(STANDARD_SIP_PORT); /* we should never get here */
3214 ast_log(LOG_WARNING, "stun failed\n");
3215 ast_debug(1, "Target address %s is not local, substituting externip\n",
3216 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
3218 /* no remapping, but we bind to a specific address, so use it. */
3219 switch (p->socket.type) {
3220 case SIP_TRANSPORT_TCP:
3221 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
3222 *us = sip_tcp_desc.local_address;
3224 us->sin_port = sip_tcp_desc.local_address.sin_port;
3227 case SIP_TRANSPORT_TLS:
3228 if (sip_tls_desc.local_address.sin_addr.s_addr) {
3229 *us = sip_tls_desc.local_address;
3231 us->sin_port = sip_tls_desc.local_address.sin_port;
3234 case SIP_TRANSPORT_UDP:
3235 /* fall through on purpose */
3237 if (bindaddr.sin_addr.s_addr) {
3241 } else if (bindaddr.sin_addr.s_addr) {
3244 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));
3247 /*! \brief Append to SIP dialog history with arg list */
3248 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3250 char buf[80], *c = buf; /* max history length */
3251 struct sip_history *hist;
3254 vsnprintf(buf, sizeof(buf), fmt, ap);
3255 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3256 l = strlen(buf) + 1;
3257 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
3259 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3263 memcpy(hist->event, buf, l);
3264 if (p->history_entries == MAX_HISTORY_ENTRIES) {
3265 struct sip_history *oldest;
3266 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3267 p->history_entries--;
3270 AST_LIST_INSERT_TAIL(p->history, hist, list);
3271 p->history_entries++;
3274 /*! \brief Append to SIP dialog history with arg list */
3275 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3282 if (!p->do_history && !recordhistory && !dumphistory)
3286 append_history_va(p, fmt, ap);
3292 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3293 static int retrans_pkt(const void *data)
3295 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3296 int reschedule = DEFAULT_RETRANS;
3299 /* Lock channel PVT */
3300 sip_pvt_lock(pkt->owner);
3302 if (pkt->retrans < MAX_RETRANS) {
3304 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
3306 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);
3311 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
3315 pkt->timer_a = 2 * pkt->timer_a;
3317 /* For non-invites, a maximum of 4 secs */
3318 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
3319 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
3322 /* Reschedule re-transmit */
3323 reschedule = siptimer_a;
3324 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);
3327 if (sip_debug_test_pvt(pkt->owner)) {
3328 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
3329 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
3330 pkt->retrans, sip_nat_mode(pkt->owner),
3331 ast_inet_ntoa(dst->sin_addr),
3332 ntohs(dst->sin_port), pkt->data->str);
3335 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3336 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3337 sip_pvt_unlock(pkt->owner);
3338 if (xmitres == XMIT_ERROR)
3339 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
3343 /* Too many retries */
3344 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3345 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
3346 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
3347 pkt->owner->callid, pkt->seqno,
3348 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
3349 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
3350 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3353 if (xmitres == XMIT_ERROR) {
3354 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3355 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3357 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3359 pkt->retransid = -1;
3361 if (pkt->is_fatal) {
3362 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3363 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
3365 sip_pvt_lock(pkt->owner);
3368 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
3369 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3371 if (pkt->owner->owner) {
3372 sip_alreadygone(pkt->owner);
3373 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3374 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3375 ast_channel_unlock(pkt->owner->owner);
3377 /* If no channel owner, destroy now */
3379 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3380 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3381 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3382 sip_alreadygone(pkt->owner);
3383 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3388 if (pkt->method == SIP_BYE) {
3389 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
3390 if (pkt->owner->owner)
3391 ast_channel_unlock(pkt->owner->owner);
3392 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3393 pvt_set_needdestroy(pkt->owner, "no response to BYE");
3396 /* Remove the packet */
3397 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3399 UNLINK(cur, pkt->owner->packets, prev);
3400 sip_pvt_unlock(pkt->owner);
3402 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3404 ast_free(pkt->data);
3411 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3412 sip_pvt_unlock(pkt->owner);
3416 /*! \brief Transmit packet with retransmits
3417 \return 0 on success, -1 on failure to allocate packet
3419 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)
3421 struct sip_pkt *pkt = NULL;
3422 int siptimer_a = DEFAULT_RETRANS;
3426 if (sipmethod == SIP_INVITE) {
3427 /* Note this is a pending invite */
3428 p->pendinginvite = seqno;
3431 /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3432 /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3433 /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3434 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3435 xmitres = __sip_xmit(p, data, len); /* Send packet */
3436 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3437 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3444 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3446 /* copy data, add a terminator and save length */
3447 if (!(pkt->data = ast_str_create(len))) {
3451 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3452 pkt->packetlen = len;
3453 /* copy other parameters from the caller */
3454 pkt->method = sipmethod;
3456 pkt->is_resp = resp;
3457 pkt->is_fatal = fatal;
3458 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3459 pkt->next = p->packets;
3460 p->packets = pkt; /* Add it to the queue */
3462 /* Parse out the response code */
3463 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3464 pkt->response_code = respid;
3467 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
3468 pkt->retransid = -1;
3470 siptimer_a = pkt->timer_t1 * 2;
3472 /* Schedule retransmission */
3473 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3475 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
3477 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
3479 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3480 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3481 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3482 AST_SCHED_DEL(sched, pkt->retransid);
3483 p->packets = pkt->next;
3484 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3485 ast_free(pkt->data);
3493 /*! \brief Kill a SIP dialog (called only by the scheduler)
3494 * The scheduler has a reference to this dialog when p->autokillid != -1,
3495 * and we are called using that reference. So if the event is not
3496 * rescheduled, we need to call dialog_unref().
3498 static int __sip_autodestruct(const void *data)
3500 struct sip_pvt *p = (struct sip_pvt *)data;
3502 /* If this is a subscription, tell the phone that we got a timeout */
3503 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3504 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
3505 p->subscribed = NONE;
3506 append_history(p, "Subscribestatus", "timeout");
3507 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3508 return 10000; /* Reschedule this destruction so that we know that it's gone */
3511 /* If there are packets still waiting for delivery, delay the destruction */
3513 if (!p->needdestroy) {
3514 char method_str[31];
3515 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3516 append_history(p, "ReliableXmit", "timeout");
3517 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3518 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3519 pvt_set_needdestroy(p, "autodestruct");
3524 /* They've had their chance to respond. Time to bail */
3525 __sip_pretend_ack(p);
3529 if (p->subscribed == MWI_NOTIFICATION) {
3530 if (p->relatedpeer) {
3531 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) */
3535 /* Reset schedule ID */
3539 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3540 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3541 } else if (p->refer && !p->alreadygone) {
3542 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3543 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3544 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3545 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3547 append_history(p, "AutoDestroy", "%s", p->callid);
3548 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3549 dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3550 /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3551 /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is&nb