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 <use type="module">res_crypto</use>
166 <depend>chan_local</depend>
167 <support_level>core</support_level>
170 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
172 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
173 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
174 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
175 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
176 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
177 that do not support Session-Timers).
179 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
180 per-peer settings override the global settings. The following new parameters have been
181 added to the sip.conf file.
182 session-timers=["accept", "originate", "refuse"]
183 session-expires=[integer]
184 session-minse=[integer]
185 session-refresher=["uas", "uac"]
187 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
188 Asterisk. The Asterisk can be configured in one of the following three modes:
190 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
191 made by remote end-points. A remote end-point can request Asterisk to engage
192 session-timers by either sending it an INVITE request with a "Supported: timer"
193 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
194 Session-Expires: header in it. In this mode, the Asterisk server does not
195 request session-timers from remote end-points. This is the default mode.
196 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
197 end-points to activate session-timers in addition to honoring such requests
198 made by the remote end-pints. In order to get as much protection as possible
199 against hanging SIP channels due to network or end-point failures, Asterisk
200 resends periodic re-INVITEs even if a remote end-point does not support
201 the session-timers feature.
202 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
203 timers for inbound or outbound requests. If a remote end-point requests
204 session-timers in a dialog, then Asterisk ignores that request unless it's
205 noted as a requirement (Require: header), in which case the INVITE is
206 rejected with a 420 Bad Extension response.
210 #include "asterisk.h"
212 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
215 #include <sys/signal.h>
217 #include <inttypes.h>
219 #include "asterisk/network.h"
220 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
222 Uncomment the define below, if you are having refcount related memory leaks.
223 With this uncommented, this module will generate a file, /tmp/refs, which contains
224 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
225 be modified to ao2_t_* calls, and include a tag describing what is happening with
226 enough detail, to make pairing up a reference count increment with its corresponding decrement.
227 The refcounter program in utils/ can be invaluable in highlighting objects that are not
228 balanced, along with the complete history for that object.
229 In normal operation, the macros defined will throw away the tags, so they do not
230 affect the speed of the program at all. They can be considered to be documentation.
232 /* #define REF_DEBUG 1 */
233 #include "asterisk/lock.h"
234 #include "asterisk/config.h"
235 #include "asterisk/module.h"
236 #include "asterisk/pbx.h"
237 #include "asterisk/sched.h"
238 #include "asterisk/io.h"
239 #include "asterisk/rtp_engine.h"
240 #include "asterisk/udptl.h"
241 #include "asterisk/acl.h"
242 #include "asterisk/manager.h"
243 #include "asterisk/callerid.h"
244 #include "asterisk/cli.h"
245 #include "asterisk/musiconhold.h"
246 #include "asterisk/dsp.h"
247 #include "asterisk/features.h"
248 #include "asterisk/srv.h"
249 #include "asterisk/astdb.h"
250 #include "asterisk/causes.h"
251 #include "asterisk/utils.h"
252 #include "asterisk/file.h"
253 #include "asterisk/astobj2.h"
254 #include "asterisk/dnsmgr.h"
255 #include "asterisk/devicestate.h"
256 #include "asterisk/monitor.h"
257 #include "asterisk/netsock2.h"
258 #include "asterisk/localtime.h"
259 #include "asterisk/abstract_jb.h"
260 #include "asterisk/threadstorage.h"
261 #include "asterisk/translate.h"
262 #include "asterisk/ast_version.h"
263 #include "asterisk/event.h"
264 #include "asterisk/cel.h"
265 #include "asterisk/data.h"
266 #include "asterisk/aoc.h"
267 #include "asterisk/message.h"
268 #include "sip/include/sip.h"
269 #include "sip/include/globals.h"
270 #include "sip/include/config_parser.h"
271 #include "sip/include/reqresp_parser.h"
272 #include "sip/include/sip_utils.h"
273 #include "sip/include/srtp.h"
274 #include "sip/include/sdp_crypto.h"
275 #include "asterisk/ccss.h"
276 #include "asterisk/xml.h"
277 #include "sip/include/dialog.h"
278 #include "sip/include/dialplan_functions.h"
282 <application name="SIPDtmfMode" language="en_US">
284 Change the dtmfmode for a SIP call.
287 <parameter name="mode" required="true">
289 <enum name="inband" />
291 <enum name="rfc2833" />
296 <para>Changes the dtmfmode for a SIP call.</para>
299 <application name="SIPAddHeader" language="en_US">
301 Add a SIP header to the outbound call.
304 <parameter name="Header" required="true" />
305 <parameter name="Content" required="true" />
308 <para>Adds a header to a SIP call placed with DIAL.</para>
309 <para>Remember to use the X-header if you are adding non-standard SIP
310 headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
311 Adding the wrong headers may jeopardize the SIP dialog.</para>
312 <para>Always returns <literal>0</literal>.</para>
315 <application name="SIPRemoveHeader" language="en_US">
317 Remove SIP headers previously added with SIPAddHeader
320 <parameter name="Header" required="false" />
323 <para>SIPRemoveHeader() allows you to remove headers which were previously
324 added with SIPAddHeader(). If no parameter is supplied, all previously added
325 headers will be removed. If a parameter is supplied, only the matching headers
326 will be removed.</para>
327 <para>For example you have added these 2 headers:</para>
328 <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
329 <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
331 <para>// remove all headers</para>
332 <para>SIPRemoveHeader();</para>
333 <para>// remove all P- headers</para>
334 <para>SIPRemoveHeader(P-);</para>
335 <para>// remove only the PAI header (note the : at the end)</para>
336 <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
338 <para>Always returns <literal>0</literal>.</para>
341 <function name="SIP_HEADER" language="en_US">
343 Gets the specified SIP header.
346 <parameter name="name" required="true" />
347 <parameter name="number">
348 <para>If not specified, defaults to <literal>1</literal>.</para>
352 <para>Since there are several headers (such as Via) which can occur multiple
353 times, SIP_HEADER takes an optional second argument to specify which header with
354 that name to retrieve. Headers start at offset <literal>1</literal>.</para>
357 <function name="SIPPEER" language="en_US">
359 Gets SIP peer information.
362 <parameter name="peername" required="true" />
363 <parameter name="item">
366 <para>(default) The ip address.</para>
369 <para>The port number.</para>
371 <enum name="mailbox">
372 <para>The configured mailbox.</para>
374 <enum name="context">
375 <para>The configured context.</para>
378 <para>The epoch time of the next expire.</para>
380 <enum name="dynamic">
381 <para>Is it dynamic? (yes/no).</para>
383 <enum name="callerid_name">
384 <para>The configured Caller ID name.</para>
386 <enum name="callerid_num">
387 <para>The configured Caller ID number.</para>
389 <enum name="callgroup">
390 <para>The configured Callgroup.</para>
392 <enum name="pickupgroup">
393 <para>The configured Pickupgroup.</para>
396 <para>The configured codecs.</para>
399 <para>Status (if qualify=yes).</para>
401 <enum name="regexten">
402 <para>Registration extension.</para>
405 <para>Call limit (call-limit).</para>
407 <enum name="busylevel">
408 <para>Configured call level for signalling busy.</para>
410 <enum name="curcalls">
411 <para>Current amount of calls. Only available if call-limit is set.</para>
413 <enum name="language">
414 <para>Default language for peer.</para>
416 <enum name="accountcode">
417 <para>Account code for this peer.</para>
419 <enum name="useragent">
420 <para>Current user agent id for peer.</para>
422 <enum name="maxforwards">
423 <para>The value used for SIP loop prevention in outbound requests</para>
425 <enum name="chanvar[name]">
426 <para>A channel variable configured with setvar for this peer.</para>
428 <enum name="codec[x]">
429 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
434 <description></description>
436 <function name="SIPCHANINFO" language="en_US">
438 Gets the specified SIP parameter from the current channel.
441 <parameter name="item" required="true">
444 <para>The IP address of the peer.</para>
447 <para>The source IP address of the peer.</para>
450 <para>The URI from the <literal>From:</literal> header.</para>
453 <para>The URI from the <literal>Contact:</literal> header.</para>
455 <enum name="useragent">
456 <para>The useragent.</para>
458 <enum name="peername">
459 <para>The name of the peer.</para>
461 <enum name="t38passthrough">
462 <para><literal>1</literal> if T38 is offered or enabled in this channel,
463 otherwise <literal>0</literal>.</para>
468 <description></description>
470 <function name="CHECKSIPDOMAIN" language="en_US">
472 Checks if domain is a local domain.
475 <parameter name="domain" required="true" />
478 <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
479 as a local SIP domain that this Asterisk server is configured to handle.
480 Returns the domain name if it is locally handled, otherwise an empty string.
481 Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
484 <manager name="SIPpeers" language="en_US">
486 List SIP peers (text format).
489 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
492 <para>Lists SIP peers in text format with details on current status.
493 Peerlist will follow as separate events, followed by a final event called
494 PeerlistComplete.</para>
497 <manager name="SIPshowpeer" language="en_US">
499 show SIP peer (text format).
502 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
503 <parameter name="Peer" required="true">
504 <para>The peer name you want to check.</para>
508 <para>Show one SIP peer with details on current status.</para>
511 <manager name="SIPqualifypeer" language="en_US">
516 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
517 <parameter name="Peer" required="true">
518 <para>The peer name you want to qualify.</para>
522 <para>Qualify a SIP peer.</para>
525 <manager name="SIPshowregistry" language="en_US">
527 Show SIP registrations (text format).
530 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
533 <para>Lists all registration requests and status. Registrations will follow as separate
534 events. followed by a final event called RegistrationsComplete.</para>
537 <manager name="SIPnotify" language="en_US">
542 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
543 <parameter name="Channel" required="true">
544 <para>Peer to receive the notify.</para>
546 <parameter name="Variable" required="true">
547 <para>At least one variable pair must be specified.
548 <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
552 <para>Sends a SIP Notify event.</para>
553 <para>All parameters for this event must be specified in the body of this request
554 via multiple Variable: name=value sequences.</para>
559 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
560 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
561 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
562 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
564 static int unauth_sessions = 0;
565 static int authlimit = DEFAULT_AUTHLIMIT;
566 static int authtimeout = DEFAULT_AUTHTIMEOUT;
568 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
569 * \note Values shown here match the defaults shown in sip.conf.sample */
570 static struct ast_jb_conf default_jbconf =
574 .resync_threshold = 1000,
578 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
580 static const char config[] = "sip.conf"; /*!< Main configuration file */
581 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
583 /*! \brief Readable descriptions of device states.
584 * \note Should be aligned to above table as index */
585 static const struct invstate2stringtable {
586 const enum invitestates state;
588 } invitestate2string[] = {
590 {INV_CALLING, "Calling (Trying)"},
591 {INV_PROCEEDING, "Proceeding "},
592 {INV_EARLY_MEDIA, "Early media"},
593 {INV_COMPLETED, "Completed (done)"},
594 {INV_CONFIRMED, "Confirmed (up)"},
595 {INV_TERMINATED, "Done"},
596 {INV_CANCELLED, "Cancelled"}
599 /*! \brief Subscription types that we support. We support
600 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
601 * - SIMPLE presence used for device status
602 * - Voicemail notification subscriptions
604 static const struct cfsubscription_types {
605 enum subscriptiontype type;
606 const char * const event;
607 const char * const mediatype;
608 const char * const text;
609 } subscription_types[] = {
610 { NONE, "-", "unknown", "unknown" },
611 /* RFC 4235: SIP Dialog event package */
612 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
613 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
614 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
615 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
616 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
619 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
620 * structure and then route the messages according to the type.
622 * \note Note that sip_methods[i].id == i must hold or the code breaks
624 static const struct cfsip_methods {
626 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
628 enum can_create_dialog can_create;
630 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
631 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
632 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
633 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
634 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
635 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
636 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
637 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
638 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
639 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
640 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
641 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
642 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
643 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
644 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
645 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
646 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
649 /*! \brief Diversion header reasons
651 * The core defines a bunch of constants used to define
652 * redirecting reasons. This provides a translation table
653 * between those and the strings which may be present in
654 * a SIP Diversion header
656 static const struct sip_reasons {
657 enum AST_REDIRECTING_REASON code;
659 } sip_reason_table[] = {
660 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
661 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
662 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
663 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
664 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
665 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
666 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
667 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
668 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
669 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
670 { AST_REDIRECTING_REASON_AWAY, "away" },
671 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
675 /*! \name DefaultSettings
676 Default setttings are used as a channel setting and as a default when
680 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
681 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
682 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
683 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
684 static int default_fromdomainport; /*!< Default domain port on outbound messages */
685 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
686 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
687 static int default_qualify; /*!< Default Qualify= setting */
688 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
689 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
690 * a bridged channel on hold */
691 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
692 static char default_engine[256]; /*!< Default RTP engine */
693 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
694 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
695 static unsigned int default_transports; /*!< Default Transports (enum sip_transport) that are acceptable */
696 static unsigned int default_primary_transport; /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
699 static struct sip_settings sip_cfg; /*!< SIP configuration data.
700 \note in the future we could have multiple of these (per domain, per device group etc) */
702 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
703 #define SIP_PEDANTIC_DECODE(str) \
704 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
705 ast_uri_decode(str, ast_uri_sip_user); \
708 static unsigned int chan_idx; /*!< used in naming sip channel */
709 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
711 static int global_relaxdtmf; /*!< Relax DTMF */
712 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
713 static int global_rtptimeout; /*!< Time out call if no RTP */
714 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
715 static int global_rtpkeepalive; /*!< Send RTP keepalives */
716 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
717 static int global_regattempts_max; /*!< Registration attempts before giving up */
718 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
719 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
720 * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
721 * with just a boolean flag in the device structure */
722 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
723 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
724 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
725 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
726 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
727 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
728 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
729 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
730 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
731 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
732 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
733 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
734 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
735 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
736 static int global_t1; /*!< T1 time */
737 static int global_t1min; /*!< T1 roundtrip time minimum */
738 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
739 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
740 static int global_qualifyfreq; /*!< Qualify frequency */
741 static int global_qualify_gap; /*!< Time between our group of peer pokes */
742 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
744 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
745 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
746 static int global_min_se; /*!< Lowest threshold for session refresh interval */
747 static int global_max_se; /*!< Highest threshold for session refresh interval */
749 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
753 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
754 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
755 * event package. This variable is set at module load time and may be checked at runtime to determine
756 * if XML parsing support was found.
758 static int can_parse_xml;
760 /*! \name Object counters @{
761 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
762 * should be used to modify these values. */
763 static int speerobjs = 0; /*!< Static peers */
764 static int rpeerobjs = 0; /*!< Realtime peers */
765 static int apeerobjs = 0; /*!< Autocreated peer objects */
766 static int regobjs = 0; /*!< Registry objects */
769 static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
770 static int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
772 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
773 static int network_change_event_sched_id = -1;
775 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
777 AST_MUTEX_DEFINE_STATIC(netlock);
779 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
780 when it's doing something critical. */
781 AST_MUTEX_DEFINE_STATIC(monlock);
783 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
785 /*! \brief This is the thread for the monitor which checks for input on the channels
786 which are not currently in use. */
787 static pthread_t monitor_thread = AST_PTHREADT_NULL;
789 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
790 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
792 struct ast_sched_context *sched; /*!< The scheduling context */
793 static struct io_context *io; /*!< The IO context */
794 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
796 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
798 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
800 static enum sip_debug_e sipdebug;
802 /*! \brief extra debugging for 'text' related events.
803 * At the moment this is set together with sip_debug_console.
804 * \note It should either go away or be implemented properly.
806 static int sipdebug_text;
808 static const struct _map_x_s referstatusstrings[] = {
809 { REFER_IDLE, "<none>" },
810 { REFER_SENT, "Request sent" },
811 { REFER_RECEIVED, "Request received" },
812 { REFER_CONFIRMED, "Confirmed" },
813 { REFER_ACCEPTED, "Accepted" },
814 { REFER_RINGING, "Target ringing" },
815 { REFER_200OK, "Done" },
816 { REFER_FAILED, "Failed" },
817 { REFER_NOAUTH, "Failed - auth failure" },
818 { -1, NULL} /* terminator */
821 /* --- Hash tables of various objects --------*/
823 static const int HASH_PEER_SIZE = 17;
824 static const int HASH_DIALOG_SIZE = 17;
826 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
827 static const int HASH_DIALOG_SIZE = 563;
830 static const struct {
831 enum ast_cc_service_type service;
832 const char *service_string;
833 } sip_cc_service_map [] = {
834 [AST_CC_NONE] = { AST_CC_NONE, "" },
835 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
836 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
837 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
840 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
842 enum ast_cc_service_type service;
843 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
844 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
851 static const struct {
852 enum sip_cc_notify_state state;
853 const char *state_string;
854 } sip_cc_notify_state_map [] = {
855 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
856 [CC_READY] = {CC_READY, "cc-state: ready"},
859 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
861 static int sip_epa_register(const struct epa_static_data *static_data)
863 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
869 backend->static_data = static_data;
871 AST_LIST_LOCK(&epa_static_data_list);
872 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
873 AST_LIST_UNLOCK(&epa_static_data_list);
877 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
879 static void cc_epa_destructor(void *data)
881 struct sip_epa_entry *epa_entry = data;
882 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
886 static const struct epa_static_data cc_epa_static_data = {
887 .event = CALL_COMPLETION,
888 .name = "call-completion",
889 .handle_error = cc_handle_publish_error,
890 .destructor = cc_epa_destructor,
893 static const struct epa_static_data *find_static_data(const char * const event_package)
895 const struct epa_backend *backend = NULL;
897 AST_LIST_LOCK(&epa_static_data_list);
898 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
899 if (!strcmp(backend->static_data->name, event_package)) {
903 AST_LIST_UNLOCK(&epa_static_data_list);
904 return backend ? backend->static_data : NULL;
907 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
909 struct sip_epa_entry *epa_entry;
910 const struct epa_static_data *static_data;
912 if (!(static_data = find_static_data(event_package))) {
916 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
920 epa_entry->static_data = static_data;
921 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
926 * Used to create new entity IDs by ESCs.
928 static int esc_etag_counter;
929 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
932 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);
934 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
935 .initial_handler = cc_esc_publish_handler,
936 .modify_handler = cc_esc_publish_handler,
941 * \brief The Event State Compositors
943 * An Event State Compositor is an entity which
944 * accepts PUBLISH requests and acts appropriately
945 * based on these requests.
947 * The actual event_state_compositor structure is simply
948 * an ao2_container of sip_esc_entrys. When an incoming
949 * PUBLISH is received, we can match the appropriate sip_esc_entry
950 * using the entity ID of the incoming PUBLISH.
952 static struct event_state_compositor {
953 enum subscriptiontype event;
955 const struct sip_esc_publish_callbacks *callbacks;
956 struct ao2_container *compositor;
957 } event_state_compositors [] = {
959 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
963 static const int ESC_MAX_BUCKETS = 37;
965 static void esc_entry_destructor(void *obj)
967 struct sip_esc_entry *esc_entry = obj;
968 if (esc_entry->sched_id > -1) {
969 AST_SCHED_DEL(sched, esc_entry->sched_id);
973 static int esc_hash_fn(const void *obj, const int flags)
975 const struct sip_esc_entry *entry = obj;
976 return ast_str_hash(entry->entity_tag);
979 static int esc_cmp_fn(void *obj, void *arg, int flags)
981 struct sip_esc_entry *entry1 = obj;
982 struct sip_esc_entry *entry2 = arg;
984 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
987 static struct event_state_compositor *get_esc(const char * const event_package) {
989 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
990 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
991 return &event_state_compositors[i];
997 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
998 struct sip_esc_entry *entry;
999 struct sip_esc_entry finder;
1001 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1003 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1008 static int publish_expire(const void *data)
1010 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1011 struct event_state_compositor *esc = get_esc(esc_entry->event);
1013 ast_assert(esc != NULL);
1015 ao2_unlink(esc->compositor, esc_entry);
1016 ao2_ref(esc_entry, -1);
1020 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1022 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1023 struct event_state_compositor *esc = get_esc(esc_entry->event);
1025 ast_assert(esc != NULL);
1027 ao2_unlink(esc->compositor, esc_entry);
1029 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1030 ao2_link(esc->compositor, esc_entry);
1033 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1035 struct sip_esc_entry *esc_entry;
1038 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1042 esc_entry->event = esc->name;
1044 expires_ms = expires * 1000;
1045 /* Bump refcount for scheduler */
1046 ao2_ref(esc_entry, +1);
1047 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1049 /* Note: This links the esc_entry into the ESC properly */
1050 create_new_sip_etag(esc_entry, 0);
1055 static int initialize_escs(void)
1058 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1059 if (!((event_state_compositors[i].compositor) =
1060 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1067 static void destroy_escs(void)
1070 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1071 ao2_ref(event_state_compositors[i].compositor, -1);
1076 * Here we implement the container for dialogs which are in the
1077 * dialog_needdestroy state to iterate only through the dialogs
1078 * unlink them instead of iterate through all dialogs
1080 struct ao2_container *dialogs_needdestroy;
1083 * Here we implement the container for dialogs which have rtp
1084 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1085 * set. We use this container instead the whole dialog list.
1087 struct ao2_container *dialogs_rtpcheck;
1090 * Here we implement the container for dialogs (sip_pvt), defining
1091 * generic wrapper functions to ease the transition from the current
1092 * implementation (a single linked list) to a different container.
1093 * In addition to a reference to the container, we need functions to lock/unlock
1094 * the container and individual items, and functions to add/remove
1095 * references to the individual items.
1097 static struct ao2_container *dialogs;
1098 #define sip_pvt_lock(x) ao2_lock(x)
1099 #define sip_pvt_trylock(x) ao2_trylock(x)
1100 #define sip_pvt_unlock(x) ao2_unlock(x)
1102 /*! \brief The table of TCP threads */
1103 static struct ao2_container *threadt;
1105 /*! \brief The peer list: Users, Peers and Friends */
1106 static struct ao2_container *peers;
1107 static struct ao2_container *peers_by_ip;
1109 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
1110 static struct ast_register_list {
1111 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1115 /*! \brief The MWI subscription list */
1116 static struct ast_subscription_mwi_list {
1117 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1119 static int temp_pvt_init(void *);
1120 static void temp_pvt_cleanup(void *);
1122 /*! \brief A per-thread temporary pvt structure */
1123 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1125 /*! \brief Authentication container for realm authentication */
1126 static struct sip_auth_container *authl = NULL;
1127 /*! \brief Global authentication container protection while adjusting the references. */
1128 AST_MUTEX_DEFINE_STATIC(authl_lock);
1130 /* --- Sockets and networking --------------*/
1132 /*! \brief Main socket for UDP SIP communication.
1134 * sipsock is shared between the SIP manager thread (which handles reload
1135 * requests), the udp io handler (sipsock_read()) and the user routines that
1136 * issue udp writes (using __sip_xmit()).
1137 * The socket is -1 only when opening fails (this is a permanent condition),
1138 * or when we are handling a reload() that changes its address (this is
1139 * a transient situation during which we might have a harmless race, see
1140 * below). Because the conditions for the race to be possible are extremely
1141 * rare, we don't want to pay the cost of locking on every I/O.
1142 * Rather, we remember that when the race may occur, communication is
1143 * bound to fail anyways, so we just live with this event and let
1144 * the protocol handle this above us.
1146 static int sipsock = -1;
1148 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
1150 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1151 * internip is initialized picking a suitable address from one of the
1152 * interfaces, and the same port number we bind to. It is used as the
1153 * default address/port in SIP messages, and as the default address
1154 * (but not port) in SDP messages.
1156 static struct ast_sockaddr internip;
1158 /*! \brief our external IP address/port for SIP sessions.
1159 * externaddr.sin_addr is only set when we know we might be behind
1160 * a NAT, and this is done using a variety of (mutually exclusive)
1161 * ways from the config file:
1163 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1164 * The address is looked up only once when (re)loading the config file;
1166 * + with "externhost = host[:port]" we do a similar thing, but the
1167 * hostname is stored in externhost, and the hostname->IP mapping
1168 * is refreshed every 'externrefresh' seconds;
1170 * Other variables (externhost, externexpire, externrefresh) are used
1171 * to support the above functions.
1173 static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
1174 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1176 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1177 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1178 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
1179 static uint16_t externtcpport; /*!< external tcp port */
1180 static uint16_t externtlsport; /*!< external tls port */
1182 /*! \brief List of local networks
1183 * We store "localnet" addresses from the config file into an access list,
1184 * marked as 'DENY', so the call to ast_apply_ha() will return
1185 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1186 * (i.e. presumably public) addresses.
1188 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1190 static int ourport_tcp; /*!< The port used for TCP connections */
1191 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1192 static struct ast_sockaddr debugaddr;
1194 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
1196 /*! some list management macros. */
1198 #define UNLINK(element, head, prev) do { \
1200 (prev)->next = (element)->next; \
1202 (head) = (element)->next; \
1205 /*---------------------------- Forward declarations of functions in chan_sip.c */
1206 /* Note: This is added to help splitting up chan_sip.c into several files
1207 in coming releases. */
1209 /*--- PBX interface functions */
1210 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause);
1211 static int sip_devicestate(void *data);
1212 static int sip_sendtext(struct ast_channel *ast, const char *text);
1213 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1214 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1215 static int sip_hangup(struct ast_channel *ast);
1216 static int sip_answer(struct ast_channel *ast);
1217 static struct ast_frame *sip_read(struct ast_channel *ast);
1218 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1219 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1220 static int sip_transfer(struct ast_channel *ast, const char *dest);
1221 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1222 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1223 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1224 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1225 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1226 static const char *sip_get_callid(struct ast_channel *chan);
1228 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1229 static int sip_standard_port(enum sip_transport type, int port);
1230 static int sip_prepare_socket(struct sip_pvt *p);
1231 static int get_address_family_filter(const struct ast_sockaddr *addr);
1233 /*--- Transmitting responses and requests */
1234 static int sipsock_read(int *id, int fd, short events, void *ignore);
1235 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1236 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1237 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1238 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1239 static int retrans_pkt(const void *data);
1240 static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1241 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1242 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1243 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1244 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);
1245 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1246 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);
1247 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1248 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1249 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1250 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1251 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1252 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1253 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1254 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1255 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1256 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1257 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1258 static int transmit_message_with_text(struct sip_pvt *p, const char *text, int init, int auth);
1259 static int transmit_message_with_msg(struct sip_pvt *p, const struct ast_msg *msg);
1260 static int transmit_refer(struct sip_pvt *p, const char *dest);
1261 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1262 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1263 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1264 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1265 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1266 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1267 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1268 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1269 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1270 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1272 /* Misc dialog routines */
1273 static int __sip_autodestruct(const void *data);
1274 static void *registry_unref(struct sip_registry *reg, char *tag);
1275 static int update_call_counter(struct sip_pvt *fup, int event);
1276 static int auto_congest(const void *arg);
1277 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1278 static void free_old_route(struct sip_route *route);
1279 static void list_route(struct sip_route *route);
1280 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1281 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1282 struct sip_request *req, const char *uri);
1283 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1284 static void check_pendings(struct sip_pvt *p);
1285 static void *sip_park_thread(void *stuff);
1286 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno, char *parkexten);
1288 static void *sip_pickup_thread(void *stuff);
1289 static int sip_pickup(struct ast_channel *chan);
1291 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1292 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1294 /*--- Codec handling / SDP */
1295 static void try_suggested_sip_codec(struct sip_pvt *p);
1296 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1297 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1298 static int find_sdp(struct sip_request *req);
1299 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1300 static int process_sdp_o(const char *o, struct sip_pvt *p);
1301 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1302 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1303 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1304 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1305 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);
1306 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1307 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1308 struct ast_str **m_buf, struct ast_str **a_buf,
1309 int debug, int *min_packet_size);
1310 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1311 struct ast_str **m_buf, struct ast_str **a_buf,
1313 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1314 static void do_setnat(struct sip_pvt *p);
1315 static void stop_media_flows(struct sip_pvt *p);
1317 /*--- Authentication stuff */
1318 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1319 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1320 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1321 const char *secret, const char *md5secret, int sipmethod,
1322 const char *uri, enum xmittype reliable, int ignore);
1323 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1324 int sipmethod, const char *uri, enum xmittype reliable,
1325 struct ast_sockaddr *addr, struct sip_peer **authpeer);
1326 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1328 /*--- Domain handling */
1329 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1330 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1331 static void clear_sip_domains(void);
1333 /*--- SIP realm authentication */
1334 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1335 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1337 /*--- Misc functions */
1338 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1339 static int reload_config(enum channelreloadreason reason);
1340 static int expire_register(const void *data);
1341 static void *do_monitor(void *data);
1342 static int restart_monitor(void);
1343 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1344 static struct ast_variable *copy_vars(struct ast_variable *src);
1345 static int dialog_find_multiple(void *obj, void *arg, int flags);
1346 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1347 static int sip_refer_allocate(struct sip_pvt *p);
1348 static int sip_notify_allocate(struct sip_pvt *p);
1349 static void ast_quiet_chan(struct ast_channel *chan);
1350 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1351 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1353 /*--- Device monitoring and Device/extension state/event handling */
1354 static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data);
1355 static int sip_devicestate(void *data);
1356 static int sip_poke_noanswer(const void *data);
1357 static int sip_poke_peer(struct sip_peer *peer, int force);
1358 static void sip_poke_all_peers(void);
1359 static void sip_peer_hold(struct sip_pvt *p, int hold);
1360 static void mwi_event_cb(const struct ast_event *, void *);
1361 static void network_change_event_cb(const struct ast_event *, void *);
1363 /*--- Applications, functions, CLI and manager command helpers */
1364 static const char *sip_nat_mode(const struct sip_pvt *p);
1365 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1366 static char *transfermode2str(enum transfermodes mode) attribute_const;
1367 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1368 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1369 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1370 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1371 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1372 static void print_group(int fd, ast_group_t group, int crlf);
1373 static const char *dtmfmode2str(int mode) attribute_const;
1374 static int str2dtmfmode(const char *str) attribute_unused;
1375 static const char *insecure2str(int mode) attribute_const;
1376 static void cleanup_stale_contexts(char *new, char *old);
1377 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1378 static const char *domain_mode_to_text(const enum domain_mode mode);
1379 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1380 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1381 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1382 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1383 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1384 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1385 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1387 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1388 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1389 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1390 static char *complete_sip_peer(const char *word, int state, int flags2);
1391 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1392 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1393 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1394 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1395 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1396 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1397 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1398 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1399 static char *sip_do_debug_ip(int fd, const char *arg);
1400 static char *sip_do_debug_peer(int fd, const char *arg);
1401 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1402 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1403 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1404 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1405 static int sip_addheader(struct ast_channel *chan, const char *data);
1406 static int sip_do_reload(enum channelreloadreason reason);
1407 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1408 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1409 const char *name, int flag, int family);
1410 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1411 const char *name, int flag);
1414 Functions for enabling debug per IP or fully, or enabling history logging for
1417 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1418 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1419 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1420 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1421 static void sip_dump_history(struct sip_pvt *dialog);
1423 /*--- Device object handling */
1424 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1425 static int update_call_counter(struct sip_pvt *fup, int event);
1426 static void sip_destroy_peer(struct sip_peer *peer);
1427 static void sip_destroy_peer_fn(void *peer);
1428 static void set_peer_defaults(struct sip_peer *peer);
1429 static struct sip_peer *temp_peer(const char *name);
1430 static void register_peer_exten(struct sip_peer *peer, int onoff);
1431 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1432 static int sip_poke_peer_s(const void *data);
1433 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1434 static void reg_source_db(struct sip_peer *peer);
1435 static void destroy_association(struct sip_peer *peer);
1436 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1437 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1438 static void set_socket_transport(struct sip_socket *socket, int transport);
1440 /* Realtime device support */
1441 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1442 static void update_peer(struct sip_peer *p, int expire);
1443 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1444 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1445 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
1446 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1448 /*--- Internal UA client handling (outbound registrations) */
1449 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1450 static void sip_registry_destroy(struct sip_registry *reg);
1451 static int sip_register(const char *value, int lineno);
1452 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1453 static int sip_reregister(const void *data);
1454 static int __sip_do_register(struct sip_registry *r);
1455 static int sip_reg_timeout(const void *data);
1456 static void sip_send_all_registers(void);
1457 static int sip_reinvite_retry(const void *data);
1459 /*--- Parsing SIP requests and responses */
1460 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1461 static int determine_firstline_parts(struct sip_request *req);
1462 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1463 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1464 static int find_sip_method(const char *msg);
1465 static unsigned int parse_allowed_methods(struct sip_request *req);
1466 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1467 static int parse_request(struct sip_request *req);
1468 static const char *get_header(const struct sip_request *req, const char *name);
1469 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1470 static int method_match(enum sipmethod id, const char *name);
1471 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1472 static const char *find_alias(const char *name, const char *_default);
1473 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1474 static void lws2sws(struct ast_str *msgbuf);
1475 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1476 static char *remove_uri_parameters(char *uri);
1477 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1478 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1479 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1480 static int set_address_from_contact(struct sip_pvt *pvt);
1481 static void check_via(struct sip_pvt *p, struct sip_request *req);
1482 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1483 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1484 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1485 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1486 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1487 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1488 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1489 static int get_domain(const char *str, char *domain, int len);
1490 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1492 /*-- TCP connection handling ---*/
1493 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1494 static void *sip_tcp_worker_fn(void *);
1496 /*--- Constructing requests and responses */
1497 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1498 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1499 static void deinit_req(struct sip_request *req);
1500 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1501 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1502 static int init_resp(struct sip_request *resp, const char *msg);
1503 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1504 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1505 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1506 static void build_via(struct sip_pvt *p);
1507 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1508 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1509 static char *generate_random_string(char *buf, size_t size);
1510 static void build_callid_pvt(struct sip_pvt *pvt);
1511 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1512 static void make_our_tag(char *tagbuf, size_t len);
1513 static int add_header(struct sip_request *req, const char *var, const char *value);
1514 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1515 static int add_content(struct sip_request *req, const char *line);
1516 static int finalize_content(struct sip_request *req);
1517 static int add_text(struct sip_request *req, const char *text);
1518 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1519 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1520 static int add_vidupdate(struct sip_request *req);
1521 static void add_route(struct sip_request *req, struct sip_route *route);
1522 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1523 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1524 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1525 static void set_destination(struct sip_pvt *p, char *uri);
1526 static void append_date(struct sip_request *req);
1527 static void build_contact(struct sip_pvt *p);
1529 /*------Request handling functions */
1530 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1531 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1532 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1533 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1534 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1535 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1536 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1537 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1538 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1539 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1540 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1541 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
1542 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1543 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1545 /*------Response handling functions */
1546 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1547 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1548 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1549 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1550 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1551 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1552 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1554 /*------ SRTP Support -------- */
1555 static int setup_srtp(struct sip_srtp **srtp);
1556 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
1558 /*------ T38 Support --------- */
1559 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1560 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1561 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1562 static void change_t38_state(struct sip_pvt *p, int state);
1564 /*------ Session-Timers functions --------- */
1565 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1566 static int proc_session_timer(const void *vp);
1567 static void stop_session_timer(struct sip_pvt *p);
1568 static void start_session_timer(struct sip_pvt *p);
1569 static void restart_session_timer(struct sip_pvt *p);
1570 static const char *strefresher2str(enum st_refresher r);
1571 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1572 static int parse_minse(const char *p_hdrval, int *const p_interval);
1573 static int st_get_se(struct sip_pvt *, int max);
1574 static enum st_refresher st_get_refresher(struct sip_pvt *);
1575 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1576 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1578 /*------- RTP Glue functions -------- */
1579 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, const struct ast_format_cap *cap, int nat_active);
1581 /*!--- SIP MWI Subscription support */
1582 static int sip_subscribe_mwi(const char *value, int lineno);
1583 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1584 static void sip_send_all_mwi_subscriptions(void);
1585 static int sip_subscribe_mwi_do(const void *data);
1586 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1588 /*! \brief Definition of this channel for PBX channel registration */
1589 struct ast_channel_tech sip_tech = {
1591 .description = "Session Initiation Protocol (SIP)",
1592 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1593 .requester = sip_request_call, /* called with chan unlocked */
1594 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1595 .call = sip_call, /* called with chan locked */
1596 .send_html = sip_sendhtml,
1597 .hangup = sip_hangup, /* called with chan locked */
1598 .answer = sip_answer, /* called with chan locked */
1599 .read = sip_read, /* called with chan locked */
1600 .write = sip_write, /* called with chan locked */
1601 .write_video = sip_write, /* called with chan locked */
1602 .write_text = sip_write,
1603 .indicate = sip_indicate, /* called with chan locked */
1604 .transfer = sip_transfer, /* called with chan locked */
1605 .fixup = sip_fixup, /* called with chan locked */
1606 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1607 .send_digit_end = sip_senddigit_end,
1608 .bridge = ast_rtp_instance_bridge, /* XXX chan unlocked ? */
1609 .early_bridge = ast_rtp_instance_early_bridge,
1610 .send_text = sip_sendtext, /* called with chan locked */
1611 .func_channel_read = sip_acf_channel_read,
1612 .setoption = sip_setoption,
1613 .queryoption = sip_queryoption,
1614 .get_pvt_uniqueid = sip_get_callid,
1617 /*! \brief This version of the sip channel tech has no send_digit_begin
1618 * callback so that the core knows that the channel does not want
1619 * DTMF BEGIN frames.
1620 * The struct is initialized just before registering the channel driver,
1621 * and is for use with channels using SIP INFO DTMF.
1623 struct ast_channel_tech sip_tech_info;
1625 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1626 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1627 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1628 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1629 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1630 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1631 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1632 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1634 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1636 .init = sip_cc_agent_init,
1637 .start_offer_timer = sip_cc_agent_start_offer_timer,
1638 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1639 .respond = sip_cc_agent_respond,
1640 .status_request = sip_cc_agent_status_request,
1641 .start_monitoring = sip_cc_agent_start_monitoring,
1642 .callee_available = sip_cc_agent_recall,
1643 .destructor = sip_cc_agent_destructor,
1646 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1648 struct ast_cc_agent *agent = obj;
1649 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1650 const char *uri = arg;
1652 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1655 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1657 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1661 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1663 struct ast_cc_agent *agent = obj;
1664 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1665 const char *uri = arg;
1667 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1670 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1672 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1676 static int find_by_callid_helper(void *obj, void *arg, int flags)
1678 struct ast_cc_agent *agent = obj;
1679 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1680 struct sip_pvt *call_pvt = arg;
1682 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1685 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1687 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1691 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1693 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1694 struct sip_pvt *call_pvt = chan->tech_pvt;
1700 ast_assert(!strcmp(chan->tech->type, "SIP"));
1702 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1703 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1704 agent_pvt->offer_timer_id = -1;
1705 agent->private_data = agent_pvt;
1706 sip_pvt_lock(call_pvt);
1707 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1708 sip_pvt_unlock(call_pvt);
1712 static int sip_offer_timer_expire(const void *data)
1714 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1715 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1717 agent_pvt->offer_timer_id = -1;
1719 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1722 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1724 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1727 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1728 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1732 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1734 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1736 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1740 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1742 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1744 sip_pvt_lock(agent_pvt->subscribe_pvt);
1745 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1746 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1747 /* The second half of this if statement may be a bit hard to grasp,
1748 * so here's an explanation. When a subscription comes into
1749 * chan_sip, as long as it is not malformed, it will be passed
1750 * to the CC core. If the core senses an out-of-order state transition,
1751 * then the core will call this callback with the "reason" set to a
1752 * failure condition.
1753 * However, an out-of-order state transition will occur during a resubscription
1754 * for CC. In such a case, we can see that we have already generated a notify_uri
1755 * and so we can detect that this isn't a *real* failure. Rather, it is just
1756 * something the core doesn't recognize as a legitimate SIP state transition.
1757 * Thus we respond with happiness and flowers.
1759 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1760 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1762 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1764 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1765 agent_pvt->is_available = TRUE;
1768 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1770 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1771 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1772 return ast_cc_agent_status_response(agent->core_id, state);
1775 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1777 /* To start monitoring just means to wait for an incoming PUBLISH
1778 * to tell us that the caller has become available again. No special
1784 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1786 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1787 /* If we have received a PUBLISH beforehand stating that the caller in question
1788 * is not available, we can save ourself a bit of effort here and just report
1789 * the caller as busy
1791 if (!agent_pvt->is_available) {
1792 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1793 agent->device_name);
1795 /* Otherwise, we transmit a NOTIFY to the caller and await either
1796 * a PUBLISH or an INVITE
1798 sip_pvt_lock(agent_pvt->subscribe_pvt);
1799 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1800 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1804 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1806 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1809 /* The agent constructor probably failed. */
1813 sip_cc_agent_stop_offer_timer(agent);
1814 if (agent_pvt->subscribe_pvt) {
1815 sip_pvt_lock(agent_pvt->subscribe_pvt);
1816 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1817 /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1818 * the subscriber know something went wrong
1820 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1822 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1823 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1825 ast_free(agent_pvt);
1828 struct ao2_container *sip_monitor_instances;
1830 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1832 const struct sip_monitor_instance *monitor_instance = obj;
1833 return monitor_instance->core_id;
1836 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1838 struct sip_monitor_instance *monitor_instance1 = obj;
1839 struct sip_monitor_instance *monitor_instance2 = arg;
1841 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1844 static void sip_monitor_instance_destructor(void *data)
1846 struct sip_monitor_instance *monitor_instance = data;
1847 if (monitor_instance->subscription_pvt) {
1848 sip_pvt_lock(monitor_instance->subscription_pvt);
1849 monitor_instance->subscription_pvt->expiry = 0;
1850 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1851 sip_pvt_unlock(monitor_instance->subscription_pvt);
1852 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1854 if (monitor_instance->suspension_entry) {
1855 monitor_instance->suspension_entry->body[0] = '\0';
1856 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1857 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1859 ast_string_field_free_memory(monitor_instance);
1862 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)
1864 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1866 if (!monitor_instance) {
1870 if (ast_string_field_init(monitor_instance, 256)) {
1871 ao2_ref(monitor_instance, -1);
1875 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1876 ast_string_field_set(monitor_instance, peername, peername);
1877 ast_string_field_set(monitor_instance, device_name, device_name);
1878 monitor_instance->core_id = core_id;
1879 ao2_link(sip_monitor_instances, monitor_instance);
1880 return monitor_instance;
1883 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1885 struct sip_monitor_instance *monitor_instance = obj;
1886 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1889 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1891 struct sip_monitor_instance *monitor_instance = obj;
1892 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1895 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1896 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1897 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1898 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1899 static void sip_cc_monitor_destructor(void *private_data);
1901 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1903 .request_cc = sip_cc_monitor_request_cc,
1904 .suspend = sip_cc_monitor_suspend,
1905 .unsuspend = sip_cc_monitor_unsuspend,
1906 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1907 .destructor = sip_cc_monitor_destructor,
1910 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1912 struct sip_monitor_instance *monitor_instance = monitor->private_data;
1913 enum ast_cc_service_type service = monitor->service_offered;
1916 if (!monitor_instance) {
1920 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1924 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1925 ast_get_ccnr_available_timer(monitor->interface->config_params);
1927 sip_pvt_lock(monitor_instance->subscription_pvt);
1928 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1929 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1930 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1931 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1932 monitor_instance->subscription_pvt->expiry = when;
1934 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1935 sip_pvt_unlock(monitor_instance->subscription_pvt);
1937 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1938 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1942 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1944 struct ast_str *body = ast_str_alloca(size);
1947 generate_random_string(tuple_id, sizeof(tuple_id));
1949 /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
1950 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
1952 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1953 /* XXX The entity attribute is currently set to the peer name associated with the
1954 * dialog. This is because we currently only call this function for call-completion
1955 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
1956 * event packages, it may be crucial to have a proper URI as the presentity so this
1957 * should be revisited as support is expanded.
1959 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
1960 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
1961 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
1962 ast_str_append(&body, 0, "</tuple>\n");
1963 ast_str_append(&body, 0, "</presence>\n");
1964 ast_copy_string(pidf_body, ast_str_buffer(body), size);
1968 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1970 struct sip_monitor_instance *monitor_instance = monitor->private_data;
1971 enum sip_publish_type publish_type;
1972 struct cc_epa_entry *cc_entry;
1974 if (!monitor_instance) {
1978 if (!monitor_instance->suspension_entry) {
1979 /* We haven't yet allocated the suspension entry, so let's give it a shot */
1980 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
1981 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
1982 ao2_ref(monitor_instance, -1);
1985 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
1986 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
1987 ao2_ref(monitor_instance, -1);
1990 cc_entry->core_id = monitor->core_id;
1991 monitor_instance->suspension_entry->instance_data = cc_entry;
1992 publish_type = SIP_PUBLISH_INITIAL;
1994 publish_type = SIP_PUBLISH_MODIFY;
1995 cc_entry = monitor_instance->suspension_entry->instance_data;
1998 cc_entry->current_state = CC_CLOSED;
2000 if (ast_strlen_zero(monitor_instance->notify_uri)) {
2001 /* If we have no set notify_uri, then what this means is that we have
2002 * not received a NOTIFY from this destination stating that he is
2003 * currently available.
2005 * This situation can arise when the core calls the suspend callbacks
2006 * of multiple destinations. If one of the other destinations aside
2007 * from this one notified Asterisk that he is available, then there
2008 * is no reason to take any suspension action on this device. Rather,
2009 * we should return now and if we receive a NOTIFY while monitoring
2010 * is still "suspended" then we can immediately respond with the
2011 * proper PUBLISH to let this endpoint know what is going on.
2015 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2016 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2019 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2021 struct sip_monitor_instance *monitor_instance = monitor->private_data;
2022 struct cc_epa_entry *cc_entry;
2024 if (!monitor_instance) {
2028 ast_assert(monitor_instance->suspension_entry != NULL);
2030 cc_entry = monitor_instance->suspension_entry->instance_data;
2031 cc_entry->current_state = CC_OPEN;
2032 if (ast_strlen_zero(monitor_instance->notify_uri)) {
2033 /* This means we are being asked to unsuspend a call leg we never
2034 * sent a PUBLISH on. As such, there is no reason to send another
2035 * PUBLISH at this point either. We can just return instead.
2039 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2040 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2043 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2045 if (*sched_id != -1) {
2046 AST_SCHED_DEL(sched, *sched_id);
2047 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2052 static void sip_cc_monitor_destructor(void *private_data)
2054 struct sip_monitor_instance *monitor_instance = private_data;
2055 ao2_unlink(sip_monitor_instances, monitor_instance);
2056 ast_module_unref(ast_module_info->self);
2059 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2061 char *call_info = ast_strdupa(get_header(req, "Call-Info"));
2065 static const char cc_purpose[] = "purpose=call-completion";
2066 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2068 if (ast_strlen_zero(call_info)) {
2069 /* No Call-Info present. Definitely no CC offer */
2073 uri = strsep(&call_info, ";");
2075 while ((purpose = strsep(&call_info, ";"))) {
2076 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2081 /* We didn't find the appropriate purpose= parameter. Oh well */
2085 /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2086 while ((service_str = strsep(&call_info, ";"))) {
2087 if (!strncmp(service_str, "m=", 2)) {
2092 /* So they didn't offer a particular service, We'll just go with CCBS since it really
2093 * doesn't matter anyway
2097 /* We already determined that there is an "m=" so no need to check
2098 * the result of this strsep
2100 strsep(&service_str, "=");
2103 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2104 /* Invalid service offered */
2108 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2114 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2116 * After taking care of some formalities to be sure that this call is eligible for CC,
2117 * we first try to see if we can make use of native CC. We grab the information from
2118 * the passed-in sip_request (which is always a response to an INVITE). If we can
2119 * use native CC monitoring for the call, then so be it.
2121 * If native cc monitoring is not possible or not supported, then we will instead attempt
2122 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2123 * monitoring will only work if the monitor policy of the endpoint is "always"
2125 * \param pvt The current dialog. Contains CC parameters for the endpoint
2126 * \param req The response to the INVITE we want to inspect
2127 * \param service The service to use if generic monitoring is to be used. For native
2128 * monitoring, we get the service from the SIP response itself
2130 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2132 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2134 char interface_name[AST_CHANNEL_NAME];
2136 if (monitor_policy == AST_CC_MONITOR_NEVER) {
2137 /* Don't bother, just return */
2141 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2142 /* For some reason, CC is invalid, so don't try it! */
2146 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2148 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2149 char subscribe_uri[SIPBUFSIZE];
2150 char device_name[AST_CHANNEL_NAME];
2151 enum ast_cc_service_type offered_service;
2152 struct sip_monitor_instance *monitor_instance;
2153 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2154 /* If CC isn't being offered to us, or for some reason the CC offer is
2155 * not formatted correctly, then it may still be possible to use generic
2156 * call completion since the monitor policy may be "always"
2160 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2161 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2162 /* Same deal. We can try using generic still */
2165 /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2166 * will have a reference to callbacks in this module. We decrement the module
2167 * refcount once the monitor destructor is called
2169 ast_module_ref(ast_module_info->self);
2170 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2171 ao2_ref(monitor_instance, -1);
2176 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2177 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2181 /*! \brief Working TLS connection configuration */
2182 static struct ast_tls_config sip_tls_cfg;
2184 /*! \brief Default TLS connection configuration */
2185 static struct ast_tls_config default_tls_cfg;
2187 /*! \brief The TCP server definition */
2188 static struct ast_tcptls_session_args sip_tcp_desc = {
2190 .master = AST_PTHREADT_NULL,
2193 .name = "SIP TCP server",
2194 .accept_fn = ast_tcptls_server_root,
2195 .worker_fn = sip_tcp_worker_fn,
2198 /*! \brief The TCP/TLS server definition */
2199 static struct ast_tcptls_session_args sip_tls_desc = {
2201 .master = AST_PTHREADT_NULL,
2202 .tls_cfg = &sip_tls_cfg,
2204 .name = "SIP TLS server",
2205 .accept_fn = ast_tcptls_server_root,
2206 .worker_fn = sip_tcp_worker_fn,
2209 /*! \brief Append to SIP dialog history
2210 \return Always returns 0 */
2211 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2213 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2217 __ao2_ref_debug(p, 1, tag, file, line, func);
2222 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2226 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
2230 __ao2_ref_debug(p, -1, tag, file, line, func);
2237 /*! \brief map from an integer value to a string.
2238 * If no match is found, return errorstring
2240 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2242 const struct _map_x_s *cur;
2244 for (cur = table; cur->s; cur++) {
2252 /*! \brief map from a string to an integer value, case insensitive.
2253 * If no match is found, return errorvalue.
2255 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2257 const struct _map_x_s *cur;
2259 for (cur = table; cur->s; cur++) {
2260 if (!strcasecmp(cur->s, s)) {
2267 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2269 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2272 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2273 if (!strcasecmp(text, sip_reason_table[i].text)) {
2274 ast = sip_reason_table[i].code;
2282 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2284 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2285 return sip_reason_table[code].text;
2292 * \brief generic function for determining if a correct transport is being
2293 * used to contact a peer
2295 * this is done as a macro so that the "tmpl" var can be passed either a
2296 * sip_request or a sip_peer
2298 #define check_request_transport(peer, tmpl) ({ \
2300 if (peer->socket.type == tmpl->socket.type) \
2302 else if (!(peer->transports & tmpl->socket.type)) {\
2303 ast_log(LOG_ERROR, \
2304 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2305 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2308 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
2309 ast_log(LOG_WARNING, \
2310 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2311 peer->name, get_transport(tmpl->socket.type) \
2315 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2316 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
2323 * duplicate a list of channel variables, \return the copy.
2325 static struct ast_variable *copy_vars(struct ast_variable *src)
2327 struct ast_variable *res = NULL, *tmp, *v = NULL;
2329 for (v = src ; v ; v = v->next) {
2330 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2338 static void tcptls_packet_destructor(void *obj)
2340 struct tcptls_packet *packet = obj;
2342 ast_free(packet->data);
2345 static void sip_tcptls_client_args_destructor(void *obj)
2347 struct ast_tcptls_session_args *args = obj;
2348 if (args->tls_cfg) {
2349 ast_free(args->tls_cfg->certfile);
2350 ast_free(args->tls_cfg->pvtfile);
2351 ast_free(args->tls_cfg->cipher);
2352 ast_free(args->tls_cfg->cafile);
2353 ast_free(args->tls_cfg->capath);
2355 ast_free(args->tls_cfg);
2356 ast_free((char *) args->name);
2359 static void sip_threadinfo_destructor(void *obj)
2361 struct sip_threadinfo *th = obj;
2362 struct tcptls_packet *packet;
2364 if (th->alert_pipe[1] > -1) {
2365 close(th->alert_pipe[0]);
2367 if (th->alert_pipe[1] > -1) {
2368 close(th->alert_pipe[1]);
2370 th->alert_pipe[0] = th->alert_pipe[1] = -1;
2372 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2373 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2376 if (th->tcptls_session) {
2377 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2381 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2382 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2384 struct sip_threadinfo *th;
2386 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2390 th->alert_pipe[0] = th->alert_pipe[1] = -1;
2392 if (pipe(th->alert_pipe) == -1) {
2393 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2394 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2397 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2398 th->tcptls_session = tcptls_session;
2399 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
2400 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2401 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2405 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2406 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2409 struct sip_threadinfo *th = NULL;
2410 struct tcptls_packet *packet = NULL;
2411 struct sip_threadinfo tmp = {
2412 .tcptls_session = tcptls_session,
2414 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2416 if (!tcptls_session) {
2420 ast_mutex_lock(&tcptls_session->lock);
2422 if ((tcptls_session->fd == -1) ||
2423 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2424 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2425 !(packet->data = ast_str_create(len))) {
2426 goto tcptls_write_setup_error;
2429 /* goto tcptls_write_error should _NOT_ be used beyond this point */
2430 ast_str_set(&packet->data, 0, "%s", (char *) buf);
2433 /* alert tcptls thread handler that there is a packet to be sent.
2434 * must lock the thread info object to guarantee control of the
2437 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2438 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2439 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2442 } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2443 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2447 ast_mutex_unlock(&tcptls_session->lock);
2448 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2451 tcptls_write_setup_error:
2453 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2456 ao2_t_ref(packet, -1, "could not allocate packet's data");
2458 ast_mutex_unlock(&tcptls_session->lock);
2463 /*! \brief SIP TCP connection handler */
2464 static void *sip_tcp_worker_fn(void *data)
2466 struct ast_tcptls_session_instance *tcptls_session = data;
2468 return _sip_tcp_helper_thread(NULL, tcptls_session);
2471 /*! \brief Check if the authtimeout has expired.
2472 * \param start the time when the session started
2474 * \retval 0 the timeout has expired
2476 * \return the number of milliseconds until the timeout will expire
2478 static int sip_check_authtimeout(time_t start)
2482 if(time(&now) == -1) {
2483 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2487 timeout = (authtimeout - (now - start)) * 1000;
2489 /* we have timed out */
2496 /*! \brief SIP TCP thread management function
2497 This function reads from the socket, parses the packet into a request
2499 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2501 int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
2503 struct sip_request req = { 0, } , reqcpy = { 0, };
2504 struct sip_threadinfo *me = NULL;
2505 char buf[1024] = "";
2506 struct pollfd fds[2] = { { 0 }, { 0 }, };
2507 struct ast_tcptls_session_args *ca = NULL;
2509 /* If this is a server session, then the connection has already been
2510 * setup. Check if the authlimit has been reached and if not create the
2511 * threadinfo object so we can access this thread for writing.
2513 * if this is a client connection more work must be done.
2514 * 1. We own the parent session args for a client connection. This pointer needs
2515 * to be held on to so we can decrement it's ref count on thread destruction.
2516 * 2. The threadinfo object was created before this thread was launched, however
2517 * it must be found within the threadt table.
2518 * 3. Last, the tcptls_session must be started.
2520 if (!tcptls_session->client) {
2521 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
2522 /* unauth_sessions is decremented in the cleanup code */
2526 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
2527 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2531 flags |= O_NONBLOCK;
2532 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
2533 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2537 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
2540 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2542 struct sip_threadinfo tmp = {
2543 .tcptls_session = tcptls_session,
2546 if ((!(ca = tcptls_session->parent)) ||
2547 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2548 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2554 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
2555 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
2559 me->threadid = pthread_self();
2560 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2562 /* set up pollfd to watch for reads on both the socket and the alert_pipe */
2563 fds[0].fd = tcptls_session->fd;
2564 fds[1].fd = me->alert_pipe[0];
2565 fds[0].events = fds[1].events = POLLIN | POLLPRI;
2567 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2570 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
2574 if(time(&start) == -1) {
2575 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2580 struct ast_str *str_save;
2582 if (!tcptls_session->client && req.authenticated && !authenticated) {
2584 ast_atomic_fetchadd_int(&unauth_sessions, -1);
2587 /* calculate the timeout for unauthenticated server sessions */
2588 if (!tcptls_session->client && !authenticated ) {
2589 if ((timeout = sip_check_authtimeout(start)) < 0) {
2594 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2601 res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
2603 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2605 } else if (res == 0) {
2607 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2611 /* handle the socket event, check for both reads from the socket fd,
2612 * and writes from alert_pipe fd */
2613 if (fds[0].revents) { /* there is data on the socket to be read */
2618 /* clear request structure */
2619 str_save = req.data;
2620 memset(&req, 0, sizeof(req));
2621 req.data = str_save;
2622 ast_str_reset(req.data);
2624 str_save = reqcpy.data;
2625 memset(&reqcpy, 0, sizeof(reqcpy));
2626 reqcpy.data = str_save;
2627 ast_str_reset(reqcpy.data);
2629 memset(buf, 0, sizeof(buf));
2631 if (tcptls_session->ssl) {
2632 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2633 req.socket.port = htons(ourport_tls);
2635 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
2636 req.socket.port = htons(ourport_tcp);
2638 req.socket.fd = tcptls_session->fd;
2640 /* Read in headers one line at a time */
2641 while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
2642 if (!tcptls_session->client && !authenticated ) {
2643 if ((timeout = sip_check_authtimeout(start)) < 0) {
2648 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2655 /* special polling behavior is required for TLS
2656 * sockets because of the buffering done in the
2658 if (!tcptls_session->ssl || need_poll) {
2661 res = ast_wait_for_input(tcptls_session->fd, timeout);
2663 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2665 } else if (res == 0) {
2667 ast_debug(2, "SIP TCP server timed out\n");
2672 ast_mutex_lock(&tcptls_session->lock);
2673 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2674 ast_mutex_unlock(&tcptls_session->lock);
2682 ast_mutex_unlock(&tcptls_session->lock);
2687 ast_str_append(&req.data, 0, "%s", buf);
2689 copy_request(&reqcpy, &req);
2690 parse_request(&reqcpy);
2691 /* In order to know how much to read, we need the content-length header */
2692 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2695 if (!tcptls_session->client && !authenticated ) {
2696 if ((timeout = sip_check_authtimeout(start)) < 0) {
2701 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2708 if (!tcptls_session->ssl || need_poll) {
2711 res = ast_wait_for_input(tcptls_session->fd, timeout);
2713 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2715 } else if (res == 0) {
2717 ast_debug(2, "SIP TCP server timed out\n");
2722 ast_mutex_lock(&tcptls_session->lock);
2723 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2724 ast_mutex_unlock(&tcptls_session->lock);
2732 buf[bytes_read] = '\0';
2733 ast_mutex_unlock(&tcptls_session->lock);
2739 ast_str_append(&req.data, 0, "%s", buf);
2742 /*! \todo XXX If there's no Content-Length or if the content-length and what
2743 we receive is not the same - we should generate an error */
2745 req.socket.tcptls_session = tcptls_session;
2746 handle_request_do(&req, &tcptls_session->remote_address);
2749 if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2750 enum sip_tcptls_alert alert;
2751 struct tcptls_packet *packet;
2755 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2756 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2761 case TCPTLS_ALERT_STOP:
2763 case TCPTLS_ALERT_DATA:
2765 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2766 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
2771 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
2772 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
2774 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
2778 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
2783 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
2786 if (tcptls_session && !tcptls_session->client && !authenticated) {
2787 ast_atomic_fetchadd_int(&unauth_sessions, -1);
2791 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2792 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2794 deinit_req(&reqcpy);
2797 /* if client, we own the parent session arguments and must decrement ref */
2799 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2802 if (tcptls_session) {
2803 ast_mutex_lock(&tcptls_session->lock);
2804 if (tcptls_session->f) {
2805 fclose(tcptls_session->f);
2806 tcptls_session->f = NULL;
2808 if (tcptls_session->fd != -1) {
2809 close(tcptls_session->fd);
2810 tcptls_session->fd = -1;
2812 tcptls_session->parent = NULL;
2813 ast_mutex_unlock(&tcptls_session->lock);
2815 ao2_ref(tcptls_session, -1);
2816 tcptls_session = NULL;
2822 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2823 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
2824 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2827 __ao2_ref_debug(peer, 1, tag, file, line, func);
2829 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
2833 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
2836 __ao2_ref_debug(peer, -1, tag, file, line, func);
2841 * helper functions to unreference various types of objects.
2842 * By handling them this way, we don't have to declare the
2843 * destructor on each call, which removes the chance of errors.
2845 static void *unref_peer(struct sip_peer *peer, char *tag)
2847 ao2_t_ref(peer, -1, tag);
2851 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2853 ao2_t_ref(peer, 1, tag);
2856 #endif /* REF_DEBUG */
2858 static void peer_sched_cleanup(struct sip_peer *peer)
2860 if (peer->pokeexpire != -1) {
2861 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
2862 unref_peer(peer, "removing poke peer ref"));
2864 if (peer->expire != -1) {
2865 AST_SCHED_DEL_UNREF(sched, peer->expire,
2866 unref_peer(peer, "remove register expire ref"));
2873 } peer_unlink_flag_t;
2875 /* this func is used with ao2_callback to unlink/delete all marked or linked
2876 peers, depending on arg */
2877 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
2879 struct sip_peer *peer = peerobj;
2880 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
2882 if (which == SIP_PEERS_ALL || peer->the_mark) {
2883 peer_sched_cleanup(peer);
2889 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
2891 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
2892 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
2893 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
2894 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
2897 /* \brief Unlink all marked peers from ao2 containers */
2898 static void unlink_marked_peers_from_tables(void)
2900 unlink_peers_from_tables(SIP_PEERS_MARKED);
2903 static void unlink_all_peers_from_tables(void)
2905 unlink_peers_from_tables(SIP_PEERS_ALL);
2908 /* \brief Unlink single peer from all ao2 containers */
2909 static void unlink_peer_from_tables(struct sip_peer *peer)
2911 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
2912 if (!ast_sockaddr_isnull(&peer->addr)) {
2913 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
2917 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2919 * This function sets pvt's outboundproxy pointer to the one referenced
2920 * by the proxy parameter. Because proxy may be a refcounted object, and
2921 * because pvt's old outboundproxy may also be a refcounted object, we need
2922 * to maintain the proper refcounts.
2924 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2925 * \param proxy The sip_proxy which we will point pvt towards.
2926 * \return Returns void
2928 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2930 struct sip_proxy *old_obproxy = pvt->outboundproxy;
2931 /* The sip_cfg.outboundproxy is statically allocated, and so
2932 * we don't ever need to adjust refcounts for it
2934 if (proxy && proxy != &sip_cfg.outboundproxy) {
2937 pvt->outboundproxy = proxy;
2938 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2939 ao2_ref(old_obproxy, -1);
2944 * \brief Unlink a dialog from the dialogs_checkrtp container
2946 static void *dialog_unlink_rtpcheck(struct sip_pvt *dialog)
2948 ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2953 * \brief Unlink a dialog from the dialogs container, as well as any other places
2954 * that it may be currently stored.
2956 * \note A reference to the dialog must be held before calling this function, and this
2957 * function does not release that reference.
2959 void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2963 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2965 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2966 ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
2967 ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
2969 /* Unlink us from the owner (channel) if we have one */
2970 if (dialog->owner) {
2972 ast_channel_lock(dialog->owner);
2974 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2975 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2977 ast_channel_unlock(dialog->owner);
2980 if (dialog->registry) {
2981 if (dialog->registry->call == dialog) {
2982 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2984 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2986 if (dialog->stateid > -1) {
2987 ast_extension_state_del(dialog->stateid, NULL);
2988 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2989 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2991 /* Remove link from peer to subscription of MWI */
2992 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2993 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2995 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2996 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2999 /* remove all current packets in this dialog */
3000 while((cp = dialog->packets)) {
3001 dialog->packets = dialog->packets->next;
3002 AST_SCHED_DEL(sched, cp->retransid);
3003 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
3010 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"));
3012 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"));
3014 if (dialog->autokillid > -1) {
3015 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"));
3018 if (dialog->request_queue_sched_id > -1) {
3019 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"));
3022 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"));
3024 if (dialog->t38id > -1) {
3025 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"));
3028 if (dialog->stimer) {
3029 stop_session_timer(dialog);
3032 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3036 void *registry_unref(struct sip_registry *reg, char *tag)
3038 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
3039 ASTOBJ_UNREF(reg, sip_registry_destroy);
3043 /*! \brief Add object reference to SIP registry */
3044 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
3046 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
3047 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
3050 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3051 static struct ast_udptl_protocol sip_udptl = {
3053 get_udptl_info: sip_get_udptl_peer,
3054 set_udptl_peer: sip_set_udptl_peer,
3057 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3058 __attribute__((format(printf, 2, 3)));
3061 /*! \brief Convert transfer status to string */
3062 static const char *referstatus2str(enum referstatus rstatus)
3064 return map_x_s(referstatusstrings, rstatus, "");
3067 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3069 if (pvt->final_destruction_scheduled) {
3070 return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3072 if(pvt->needdestroy != 1) {
3073 ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3075 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3076 pvt->needdestroy = 1;
3079 /*! \brief Initialize the initital request packet in the pvt structure.