2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
31 * ********** IMPORTANT *
32 * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33 * settings, dialplan commands and dialplans apps/functions
34 * See \ref sip_tcp_tls
37 * ******** General TODO:s
38 * \todo Better support of forking
39 * \todo VIA branch tag transaction checking
40 * \todo Transaction support
42 * ******** Wishlist: Improvements
43 * - Support of SIP domains for devices, so that we match on username@domain in the From: header
44 * - Connect registrations with a specific device on the incoming call. It's not done
45 * automatically in Asterisk
47 * \ingroup channel_drivers
49 * \par Overview of the handling of SIP sessions
50 * The SIP channel handles several types of SIP sessions, or dialogs,
51 * not all of them being "telephone calls".
52 * - Incoming calls that will be sent to the PBX core
53 * - Outgoing calls, generated by the PBX
54 * - SIP subscriptions and notifications of states and voicemail messages
55 * - SIP registrations, both inbound and outbound
56 * - SIP peer management (peerpoke, OPTIONS)
59 * In the SIP channel, there's a list of active SIP dialogs, which includes
60 * all of these when they are active. "sip show channels" in the CLI will
61 * show most of these, excluding subscriptions which are shown by
62 * "sip show subscriptions"
64 * \par incoming packets
65 * Incoming packets are received in the monitoring thread, then handled by
66 * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
67 * sipsock_read() function parses the packet and matches an existing
68 * dialog or starts a new SIP dialog.
70 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
71 * If it is a response to an outbound request, the packet is sent to handle_response().
72 * If it is a request, handle_incoming() sends it to one of a list of functions
73 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
74 * sipsock_read locks the ast_channel if it exists (an active call) and
75 * unlocks it after we have processed the SIP message.
77 * A new INVITE is sent to handle_request_invite(), that will end up
78 * starting a new channel in the PBX, the new channel after that executing
79 * in a separate channel thread. This is an incoming "call".
80 * When the call is answered, either by a bridged channel or the PBX itself
81 * the sip_answer() function is called.
83 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
87 * Outbound calls are set up by the PBX through the sip_request_call()
88 * function. After that, they are activated by sip_call().
91 * The PBX issues a hangup on both incoming and outgoing calls through
92 * the sip_hangup() function
96 * \page sip_tcp_tls SIP TCP and TLS support
98 * \par tcpfixes TCP implementation changes needed
99 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
100 * \todo Save TCP/TLS sessions in registry
101 * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
102 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
103 * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
104 * The tcpbindaddr config option should only be used to open ADDITIONAL ports
105 * So we should propably go back to
106 * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
107 * if tlsenable=yes, open TLS port (provided we also have cert)
108 * tcpbindaddr = extra address for additional TCP connections
109 * tlsbindaddr = extra address for additional TCP/TLS connections
110 * udpbindaddr = extra address for additional UDP connections
111 * These three options should take multiple IP/port pairs
112 * Note: Since opening additional listen sockets is a *new* feature we do not have today
113 * the XXXbindaddr options needs to be disabled until we have support for it
115 * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
116 * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
117 * even if udp is the configured first transport.
119 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
120 * specially to communication with other peers (proxies).
121 * \todo We need to test TCP sessions with SIP proxies and in regards
122 * to the SIP outbound specs.
123 * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
125 * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
126 * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
127 * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
128 * multiple domains in our TLS implementation, meaning one socket and one cert per domain
129 * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
130 * also considering outbound proxy options.
131 * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
132 * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
133 * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
134 * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
135 * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
136 * devices directly from the dialplan. UDP is only a fallback if no other method works,
137 * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
138 * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
140 * When dialling unconfigured peers (with no port number) or devices in external domains
141 * NAPTR records MUST be consulted to find configured transport. If they are not found,
142 * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
143 * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
144 * \note this only applies if there's no outbound proxy configured for the session. If an outbound
145 * proxy is configured, these procedures might apply for locating the proxy and determining
146 * the transport to use for communication with the proxy.
147 * \par Other bugs to fix ----
148 * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
149 * - sets TLS port as default for all TCP connections, unless other port is given in contact.
150 * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
151 * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
153 * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
154 * get_destination(struct sip_pvt *p, struct sip_request *oreq)
155 * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
156 * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
157 * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
158 * channel variable in the dialplan.
159 * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
160 * - As above, if we have a SIPS: uri in the refer-to header
161 * - Does not check transport in refer_to uri.
165 <depend>chan_local</depend>
168 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
170 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
171 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
172 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
173 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
174 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
175 that do not support Session-Timers).
177 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
178 per-peer settings override the global settings. The following new parameters have been
179 added to the sip.conf file.
180 session-timers=["accept", "originate", "refuse"]
181 session-expires=[integer]
182 session-minse=[integer]
183 session-refresher=["uas", "uac"]
185 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
186 Asterisk. The Asterisk can be configured in one of the following three modes:
188 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
189 made by remote end-points. A remote end-point can request Asterisk to engage
190 session-timers by either sending it an INVITE request with a "Supported: timer"
191 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
192 Session-Expires: header in it. In this mode, the Asterisk server does not
193 request session-timers from remote end-points. This is the default mode.
194 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
195 end-points to activate session-timers in addition to honoring such requests
196 made by the remote end-pints. In order to get as much protection as possible
197 against hanging SIP channels due to network or end-point failures, Asterisk
198 resends periodic re-INVITEs even if a remote end-point does not support
199 the session-timers feature.
200 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
201 timers for inbound or outbound requests. If a remote end-point requests
202 session-timers in a dialog, then Asterisk ignores that request unless it's
203 noted as a requirement (Require: header), in which case the INVITE is
204 rejected with a 420 Bad Extension response.
208 #include "asterisk.h"
210 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
213 #include <sys/signal.h>
215 #include <inttypes.h>
217 #include "asterisk/network.h"
218 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
220 Uncomment the define below, if you are having refcount related memory leaks.
221 With this uncommented, this module will generate a file, /tmp/refs, which contains
222 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
223 be modified to ao2_t_* calls, and include a tag describing what is happening with
224 enough detail, to make pairing up a reference count increment with its corresponding decrement.
225 The refcounter program in utils/ can be invaluable in highlighting objects that are not
226 balanced, along with the complete history for that object.
227 In normal operation, the macros defined will throw away the tags, so they do not
228 affect the speed of the program at all. They can be considered to be documentation.
230 /* #define REF_DEBUG 1 */
231 #include "asterisk/lock.h"
232 #include "asterisk/config.h"
233 #include "asterisk/module.h"
234 #include "asterisk/pbx.h"
235 #include "asterisk/sched.h"
236 #include "asterisk/io.h"
237 #include "asterisk/rtp_engine.h"
238 #include "asterisk/udptl.h"
239 #include "asterisk/acl.h"
240 #include "asterisk/manager.h"
241 #include "asterisk/callerid.h"
242 #include "asterisk/cli.h"
243 #include "asterisk/musiconhold.h"
244 #include "asterisk/dsp.h"
245 #include "asterisk/features.h"
246 #include "asterisk/srv.h"
247 #include "asterisk/astdb.h"
248 #include "asterisk/causes.h"
249 #include "asterisk/utils.h"
250 #include "asterisk/file.h"
251 #include "asterisk/astobj2.h"
252 #include "asterisk/dnsmgr.h"
253 #include "asterisk/devicestate.h"
254 #include "asterisk/monitor.h"
255 #include "asterisk/netsock.h"
256 #include "asterisk/localtime.h"
257 #include "asterisk/abstract_jb.h"
258 #include "asterisk/threadstorage.h"
259 #include "asterisk/translate.h"
260 #include "asterisk/ast_version.h"
261 #include "asterisk/event.h"
262 #include "asterisk/stun.h"
263 #include "asterisk/cel.h"
264 #include "sip/include/sip.h"
265 #include "sip/include/globals.h"
266 #include "sip/include/config_parser.h"
267 #include "sip/include/reqresp_parser.h"
268 #include "sip/include/sip_utils.h"
269 #include "sip/include/dialog.h"
270 #include "sip/include/dialplan_functions.h"
273 <application name="SIPDtmfMode" language="en_US">
275 Change the dtmfmode for a SIP call.
278 <parameter name="mode" required="true">
280 <enum name="inband" />
282 <enum name="rfc2833" />
287 <para>Changes the dtmfmode for a SIP call.</para>
290 <application name="SIPAddHeader" language="en_US">
292 Add a SIP header to the outbound call.
295 <parameter name="Header" required="true" />
296 <parameter name="Content" required="true" />
299 <para>Adds a header to a SIP call placed with DIAL.</para>
300 <para>Remember to use the X-header if you are adding non-standard SIP
301 headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
302 Adding the wrong headers may jeopardize the SIP dialog.</para>
303 <para>Always returns <literal>0</literal>.</para>
306 <application name="SIPRemoveHeader" language="en_US">
308 Remove SIP headers previously added with SIPAddHeader
311 <parameter name="Header" required="false" />
314 <para>SIPRemoveHeader() allows you to remove headers which were previously
315 added with SIPAddHeader(). If no parameter is supplied, all previously added
316 headers will be removed. If a parameter is supplied, only the matching headers
317 will be removed.</para>
318 <para>For example you have added these 2 headers:</para>
319 <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
320 <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
322 <para>// remove all headers</para>
323 <para>SIPRemoveHeader();</para>
324 <para>// remove all P- headers</para>
325 <para>SIPRemoveHeader(P-);</para>
326 <para>// remove only the PAI header (note the : at the end)</para>
327 <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
329 <para>Always returns <literal>0</literal>.</para>
332 <function name="SIP_HEADER" language="en_US">
334 Gets the specified SIP header.
337 <parameter name="name" required="true" />
338 <parameter name="number">
339 <para>If not specified, defaults to <literal>1</literal>.</para>
343 <para>Since there are several headers (such as Via) which can occur multiple
344 times, SIP_HEADER takes an optional second argument to specify which header with
345 that name to retrieve. Headers start at offset <literal>1</literal>.</para>
348 <function name="SIPPEER" language="en_US">
350 Gets SIP peer information.
353 <parameter name="peername" required="true" />
354 <parameter name="item">
357 <para>(default) The ip address.</para>
360 <para>The port number.</para>
362 <enum name="mailbox">
363 <para>The configured mailbox.</para>
365 <enum name="context">
366 <para>The configured context.</para>
369 <para>The epoch time of the next expire.</para>
371 <enum name="dynamic">
372 <para>Is it dynamic? (yes/no).</para>
374 <enum name="callerid_name">
375 <para>The configured Caller ID name.</para>
377 <enum name="callerid_num">
378 <para>The configured Caller ID number.</para>
380 <enum name="callgroup">
381 <para>The configured Callgroup.</para>
383 <enum name="pickupgroup">
384 <para>The configured Pickupgroup.</para>
387 <para>The configured codecs.</para>
390 <para>Status (if qualify=yes).</para>
392 <enum name="regexten">
393 <para>Registration extension.</para>
396 <para>Call limit (call-limit).</para>
398 <enum name="busylevel">
399 <para>Configured call level for signalling busy.</para>
401 <enum name="curcalls">
402 <para>Current amount of calls. Only available if call-limit is set.</para>
404 <enum name="language">
405 <para>Default language for peer.</para>
407 <enum name="accountcode">
408 <para>Account code for this peer.</para>
410 <enum name="useragent">
411 <para>Current user agent id for peer.</para>
413 <enum name="chanvar[name]">
414 <para>A channel variable configured with setvar for this peer.</para>
416 <enum name="codec[x]">
417 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
424 <function name="SIPCHANINFO" language="en_US">
426 Gets the specified SIP parameter from the current channel.
429 <parameter name="item" required="true">
432 <para>The IP address of the peer.</para>
435 <para>The source IP address of the peer.</para>
438 <para>The URI from the <literal>From:</literal> header.</para>
441 <para>The URI from the <literal>Contact:</literal> header.</para>
443 <enum name="useragent">
444 <para>The useragent.</para>
446 <enum name="peername">
447 <para>The name of the peer.</para>
449 <enum name="t38passthrough">
450 <para><literal>1</literal> if T38 is offered or enabled in this channel,
451 otherwise <literal>0</literal>.</para>
458 <function name="CHECKSIPDOMAIN" language="en_US">
460 Checks if domain is a local domain.
463 <parameter name="domain" required="true" />
466 <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
467 as a local SIP domain that this Asterisk server is configured to handle.
468 Returns the domain name if it is locally handled, otherwise an empty string.
469 Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
472 <manager name="SIPpeers" language="en_US">
474 List SIP peers (text format).
477 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
480 <para>Lists SIP peers in text format with details on current status.
481 Peerlist will follow as separate events, followed by a final event called
482 PeerlistComplete.</para>
485 <manager name="SIPshowpeer" language="en_US">
487 show SIP peer (text format).
490 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
491 <parameter name="Peer" required="true">
492 <para>The peer name you want to check.</para>
496 <para>Show one SIP peer with details on current status.</para>
499 <manager name="SIPqualifypeer" language="en_US">
504 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
505 <parameter name="Peer" required="true">
506 <para>The peer name you want to qualify.</para>
510 <para>Qualify a SIP peer.</para>
513 <manager name="SIPshowregistry" language="en_US">
515 Show SIP registrations (text format).
518 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
521 <para>Lists all registration requests and status. Registrations will follow as separate
522 events. followed by a final event called RegistrationsComplete.</para>
525 <manager name="SIPnotify" language="en_US">
530 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
531 <parameter name="Channel" required="true">
532 <para>Peer to receive the notify.</para>
534 <parameter name="Variable" required="true">
535 <para>At least one variable pair must be specified.
536 <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
540 <para>Sends a SIP Notify event.</para>
541 <para>All parameters for this event must be specified in the body of this request
542 via multiple Variable: name=value sequences.</para>
547 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
548 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
549 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
550 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
552 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
553 static struct ast_jb_conf default_jbconf =
557 .resync_threshold = -1,
561 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
563 static const char config[] = "sip.conf"; /*!< Main configuration file */
564 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
566 /*! \brief Readable descriptions of device states.
567 * \note Should be aligned to above table as index */
568 static const struct invstate2stringtable {
569 const enum invitestates state;
571 } invitestate2string[] = {
573 {INV_CALLING, "Calling (Trying)"},
574 {INV_PROCEEDING, "Proceeding "},
575 {INV_EARLY_MEDIA, "Early media"},
576 {INV_COMPLETED, "Completed (done)"},
577 {INV_CONFIRMED, "Confirmed (up)"},
578 {INV_TERMINATED, "Done"},
579 {INV_CANCELLED, "Cancelled"}
582 /*! \brief Subscription types that we support. We support
583 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
584 * - SIMPLE presence used for device status
585 * - Voicemail notification subscriptions
587 static const struct cfsubscription_types {
588 enum subscriptiontype type;
589 const char * const event;
590 const char * const mediatype;
591 const char * const text;
592 } subscription_types[] = {
593 { NONE, "-", "unknown", "unknown" },
594 /* RFC 4235: SIP Dialog event package */
595 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
596 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
597 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
598 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
599 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
602 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
603 * structure and then route the messages according to the type.
605 * \note Note that sip_methods[i].id == i must hold or the code breaks
607 static const struct cfsip_methods {
609 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
611 enum can_create_dialog can_create;
613 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
614 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
615 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
616 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
617 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
618 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
619 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
620 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
621 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
622 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
623 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
624 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
625 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
626 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
627 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
628 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
629 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
632 /*! \brief List of well-known SIP options. If we get this in a require,
633 we should check the list and answer accordingly. */
634 static const struct cfsip_options {
635 int id; /*!< Bitmap ID */
636 int supported; /*!< Supported by Asterisk ? */
637 char * const text; /*!< Text id, as in standard */
638 } sip_options[] = { /* XXX used in 3 places */
639 /* RFC3262: PRACK 100% reliability */
640 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
641 /* RFC3959: SIP Early session support */
642 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
643 /* SIMPLE events: RFC4662 */
644 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
645 /* RFC 4916- Connected line ID updates */
646 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
647 /* GRUU: Globally Routable User Agent URI's */
648 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
649 /* RFC4244 History info */
650 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
651 /* RFC3911: SIP Join header support */
652 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
653 /* Disable the REFER subscription, RFC 4488 */
654 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
655 /* SIP outbound - the final NAT battle - draft-sip-outbound */
656 { SIP_OPT_OUTBOUND, NOT_SUPPORTED, "outbound" },
657 /* RFC3327: Path support */
658 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
659 /* RFC3840: Callee preferences */
660 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
661 /* RFC3312: Precondition support */
662 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
663 /* RFC3323: Privacy with proxies*/
664 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
665 /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
666 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
667 /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
668 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
669 /* RFC3891: Replaces: header for transfer */
670 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
671 /* One version of Polycom firmware has the wrong label */
672 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
673 /* RFC4412 Resource priorities */
674 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
675 /* RFC3329: Security agreement mechanism */
676 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
677 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
678 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
679 /* RFC4028: SIP Session-Timers */
680 { SIP_OPT_TIMER, SUPPORTED, "timer" },
681 /* RFC4538: Target-dialog */
682 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
685 /*! \brief Diversion header reasons
687 * The core defines a bunch of constants used to define
688 * redirecting reasons. This provides a translation table
689 * between those and the strings which may be present in
690 * a SIP Diversion header
692 static const struct sip_reasons {
693 enum AST_REDIRECTING_REASON code;
695 } sip_reason_table[] = {
696 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
697 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
698 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
699 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
700 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
701 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
702 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
703 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
704 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
705 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
706 { AST_REDIRECTING_REASON_AWAY, "away" },
707 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
711 /*! \name DefaultSettings
712 Default setttings are used as a channel setting and as a default when
716 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
717 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
718 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
719 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
720 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
721 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
722 static int default_qualify; /*!< Default Qualify= setting */
723 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
724 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
725 * a bridged channel on hold */
726 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
727 static char default_engine[256]; /*!< Default RTP engine */
728 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
729 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
730 static unsigned int default_transports; /*!< Default Transports (enum sip_transport) that are acceptable */
731 static unsigned int default_primary_transport; /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
734 static struct sip_settings sip_cfg; /*!< SIP configuration data.
735 \note in the future we could have multiple of these (per domain, per device group etc) */
737 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
738 #define SIP_PEDANTIC_DECODE(str) \
739 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
740 ast_uri_decode(str); \
743 static unsigned int chan_idx; /*!< used in naming sip channel */
744 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
746 static int global_relaxdtmf; /*!< Relax DTMF */
747 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
748 static int global_rtptimeout; /*!< Time out call if no RTP */
749 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
750 static int global_rtpkeepalive; /*!< Send RTP keepalives */
751 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
752 static int global_regattempts_max; /*!< Registration attempts before giving up */
753 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
754 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
755 * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
756 * with just a boolean flag in the device structure */
757 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
758 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
759 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
760 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
761 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
762 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
763 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
764 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
765 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
766 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
767 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
768 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
769 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
770 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
771 static int global_t1; /*!< T1 time */
772 static int global_t1min; /*!< T1 roundtrip time minimum */
773 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
774 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
775 static int global_qualifyfreq; /*!< Qualify frequency */
776 static int global_qualify_gap; /*!< Time between our group of peer pokes */
777 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
779 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
780 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
781 static int global_min_se; /*!< Lowest threshold for session refresh interval */
782 static int global_max_se; /*!< Highest threshold for session refresh interval */
784 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
787 /*! \name Object counters @{
788 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
789 * should be used to modify these values. */
790 static int speerobjs = 0; /*!< Static peers */
791 static int rpeerobjs = 0; /*!< Realtime peers */
792 static int apeerobjs = 0; /*!< Autocreated peer objects */
793 static int regobjs = 0; /*!< Registry objects */
796 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
797 static int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
799 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
801 AST_MUTEX_DEFINE_STATIC(netlock);
803 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
804 when it's doing something critical. */
805 AST_MUTEX_DEFINE_STATIC(monlock);
807 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
809 /*! \brief This is the thread for the monitor which checks for input on the channels
810 which are not currently in use. */
811 static pthread_t monitor_thread = AST_PTHREADT_NULL;
813 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
814 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
816 struct sched_context *sched; /*!< The scheduling context */
817 static struct io_context *io; /*!< The IO context */
818 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
820 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
822 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
824 static enum sip_debug_e sipdebug;
826 /*! \brief extra debugging for 'text' related events.
827 * At the moment this is set together with sip_debug_console.
828 * \note It should either go away or be implemented properly.
830 static int sipdebug_text;
832 static const struct _map_x_s referstatusstrings[] = {
833 { REFER_IDLE, "<none>" },
834 { REFER_SENT, "Request sent" },
835 { REFER_RECEIVED, "Request received" },
836 { REFER_CONFIRMED, "Confirmed" },
837 { REFER_ACCEPTED, "Accepted" },
838 { REFER_RINGING, "Target ringing" },
839 { REFER_200OK, "Done" },
840 { REFER_FAILED, "Failed" },
841 { REFER_NOAUTH, "Failed - auth failure" },
842 { -1, NULL} /* terminator */
845 /* --- Hash tables of various objects --------*/
847 static const int HASH_PEER_SIZE = 17;
848 static const int HASH_DIALOG_SIZE = 17;
850 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
851 static const int HASH_DIALOG_SIZE = 563;
855 * Here we implement the container for dialogs (sip_pvt), defining
856 * generic wrapper functions to ease the transition from the current
857 * implementation (a single linked list) to a different container.
858 * In addition to a reference to the container, we need functions to lock/unlock
859 * the container and individual items, and functions to add/remove
860 * references to the individual items.
862 static struct ao2_container *dialogs;
863 #define sip_pvt_lock(x) ao2_lock(x)
864 #define sip_pvt_trylock(x) ao2_trylock(x)
865 #define sip_pvt_unlock(x) ao2_unlock(x)
867 /*! \brief The table of TCP threads */
868 static struct ao2_container *threadt;
870 /*! \brief The peer list: Users, Peers and Friends */
871 static struct ao2_container *peers;
872 static struct ao2_container *peers_by_ip;
874 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
875 static struct ast_register_list {
876 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
880 /*! \brief The MWI subscription list */
881 static struct ast_subscription_mwi_list {
882 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
884 static int temp_pvt_init(void *);
885 static void temp_pvt_cleanup(void *);
887 /*! \brief A per-thread temporary pvt structure */
888 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
890 /*! \brief Authentication list for realm authentication
891 * \todo Move the sip_auth list to AST_LIST */
892 static struct sip_auth *authl = NULL;
894 /* --- Sockets and networking --------------*/
896 /*! \brief Main socket for UDP SIP communication.
898 * sipsock is shared between the SIP manager thread (which handles reload
899 * requests), the udp io handler (sipsock_read()) and the user routines that
900 * issue udp writes (using __sip_xmit()).
901 * The socket is -1 only when opening fails (this is a permanent condition),
902 * or when we are handling a reload() that changes its address (this is
903 * a transient situation during which we might have a harmless race, see
904 * below). Because the conditions for the race to be possible are extremely
905 * rare, we don't want to pay the cost of locking on every I/O.
906 * Rather, we remember that when the race may occur, communication is
907 * bound to fail anyways, so we just live with this event and let
908 * the protocol handle this above us.
910 static int sipsock = -1;
912 struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
914 /*! \brief our (internal) default address/port to put in SIP/SDP messages
915 * internip is initialized picking a suitable address from one of the
916 * interfaces, and the same port number we bind to. It is used as the
917 * default address/port in SIP messages, and as the default address
918 * (but not port) in SDP messages.
920 static struct sockaddr_in internip;
922 /*! \brief our external IP address/port for SIP sessions.
923 * externip.sin_addr is only set when we know we might be behind
924 * a NAT, and this is done using a variety of (mutually exclusive)
925 * ways from the config file:
927 * + with "externip = host[:port]" we specify the address/port explicitly.
928 * The address is looked up only once when (re)loading the config file;
930 * + with "externhost = host[:port]" we do a similar thing, but the
931 * hostname is stored in externhost, and the hostname->IP mapping
932 * is refreshed every 'externrefresh' seconds;
934 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
935 * to the specified server, and store the result in externip.
937 * Other variables (externhost, externexpire, externrefresh) are used
938 * to support the above functions.
940 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
941 static struct sockaddr_in media_address; /*!< External RTP IP address if we are behind NAT */
943 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
944 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
945 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
946 static struct sockaddr_in stunaddr; /*!< stun server address */
947 static uint16_t externtcpport; /*!< external tcp port */
948 static uint16_t externtlsport; /*!< external tls port */
950 /*! \brief List of local networks
951 * We store "localnet" addresses from the config file into an access list,
952 * marked as 'DENY', so the call to ast_apply_ha() will return
953 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
954 * (i.e. presumably public) addresses.
956 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
958 static int ourport_tcp; /*!< The port used for TCP connections */
959 static int ourport_tls; /*!< The port used for TCP/TLS connections */
960 static struct sockaddr_in debugaddr;
962 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
964 /*! some list management macros. */
966 #define UNLINK(element, head, prev) do { \
968 (prev)->next = (element)->next; \
970 (head) = (element)->next; \
973 /*---------------------------- Forward declarations of functions in chan_sip.c */
974 /* Note: This is added to help splitting up chan_sip.c into several files
975 in coming releases. */
977 /*--- PBX interface functions */
978 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
979 static int sip_devicestate(void *data);
980 static int sip_sendtext(struct ast_channel *ast, const char *text);
981 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
982 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
983 static int sip_hangup(struct ast_channel *ast);
984 static int sip_answer(struct ast_channel *ast);
985 static struct ast_frame *sip_read(struct ast_channel *ast);
986 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
987 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
988 static int sip_transfer(struct ast_channel *ast, const char *dest);
989 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
990 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
991 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
992 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
993 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
994 static const char *sip_get_callid(struct ast_channel *chan);
996 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
997 static int sip_standard_port(enum sip_transport type, int port);
998 static int sip_prepare_socket(struct sip_pvt *p);
1000 /*--- Transmitting responses and requests */
1001 static int sipsock_read(int *id, int fd, short events, void *ignore);
1002 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1003 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1004 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1005 static int retrans_pkt(const void *data);
1006 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1007 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1008 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1009 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1010 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);
1011 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1012 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);
1013 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1014 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1015 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1016 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1017 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1018 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1019 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1020 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1021 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1022 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1023 static int transmit_refer(struct sip_pvt *p, const char *dest);
1024 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1025 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1026 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1027 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1028 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1029 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1030 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1031 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1032 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1034 /* Misc dialog routines */
1035 static int __sip_autodestruct(const void *data);
1036 static void *registry_unref(struct sip_registry *reg, char *tag);
1037 static int update_call_counter(struct sip_pvt *fup, int event);
1038 static int auto_congest(const void *arg);
1039 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1040 static void free_old_route(struct sip_route *route);
1041 static void list_route(struct sip_route *route);
1042 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1043 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1044 struct sip_request *req, const char *uri);
1045 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1046 static void check_pendings(struct sip_pvt *p);
1047 static void *sip_park_thread(void *stuff);
1048 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1049 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1050 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1052 /*--- Codec handling / SDP */
1053 static void try_suggested_sip_codec(struct sip_pvt *p);
1054 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1055 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1056 static int find_sdp(struct sip_request *req);
1057 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1058 static int process_sdp_o(const char *o, struct sip_pvt *p);
1059 static int process_sdp_c(const char *c, struct ast_hostent *hp);
1060 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1061 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1062 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1063 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);
1064 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1065 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1066 struct ast_str **m_buf, struct ast_str **a_buf,
1067 int debug, int *min_packet_size);
1068 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1069 struct ast_str **m_buf, struct ast_str **a_buf,
1071 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1072 static void do_setnat(struct sip_pvt *p);
1073 static void stop_media_flows(struct sip_pvt *p);
1075 /*--- Authentication stuff */
1076 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1077 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1078 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1079 const char *secret, const char *md5secret, int sipmethod,
1080 const char *uri, enum xmittype reliable, int ignore);
1081 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1082 int sipmethod, const char *uri, enum xmittype reliable,
1083 struct sockaddr_in *sin, struct sip_peer **authpeer);
1084 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1086 /*--- Domain handling */
1087 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1088 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1089 static void clear_sip_domains(void);
1091 /*--- SIP realm authentication */
1092 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1093 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1094 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1096 /*--- Misc functions */
1097 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1098 static int sip_do_reload(enum channelreloadreason reason);
1099 static int reload_config(enum channelreloadreason reason);
1100 static int expire_register(const void *data);
1101 static void *do_monitor(void *data);
1102 static int restart_monitor(void);
1103 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1104 static struct ast_variable *copy_vars(struct ast_variable *src);
1105 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1106 static int sip_refer_allocate(struct sip_pvt *p);
1107 static int sip_notify_allocate(struct sip_pvt *p);
1108 static void ast_quiet_chan(struct ast_channel *chan);
1109 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1110 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1112 /*--- Device monitoring and Device/extension state/event handling */
1113 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1114 static int sip_devicestate(void *data);
1115 static int sip_poke_noanswer(const void *data);
1116 static int sip_poke_peer(struct sip_peer *peer, int force);
1117 static void sip_poke_all_peers(void);
1118 static void sip_peer_hold(struct sip_pvt *p, int hold);
1119 static void mwi_event_cb(const struct ast_event *, void *);
1121 /*--- Applications, functions, CLI and manager command helpers */
1122 static const char *sip_nat_mode(const struct sip_pvt *p);
1123 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1124 static char *transfermode2str(enum transfermodes mode) attribute_const;
1125 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1126 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1127 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1128 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1129 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1130 static void print_group(int fd, ast_group_t group, int crlf);
1131 static const char *dtmfmode2str(int mode) attribute_const;
1132 static int str2dtmfmode(const char *str) attribute_unused;
1133 static const char *insecure2str(int mode) attribute_const;
1134 static void cleanup_stale_contexts(char *new, char *old);
1135 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1136 static const char *domain_mode_to_text(const enum domain_mode mode);
1137 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1138 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1139 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1140 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1141 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1142 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1143 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1144 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1145 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1146 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1147 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1148 static char *complete_sip_peer(const char *word, int state, int flags2);
1149 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1150 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1151 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1152 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1153 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1154 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1155 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1156 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1157 static char *sip_do_debug_ip(int fd, const char *arg);
1158 static char *sip_do_debug_peer(int fd, const char *arg);
1159 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1160 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1161 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1162 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1163 static int sip_addheader(struct ast_channel *chan, const char *data);
1164 static int sip_do_reload(enum channelreloadreason reason);
1165 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1168 Functions for enabling debug per IP or fully, or enabling history logging for
1171 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1172 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1173 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1174 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1175 static void sip_dump_history(struct sip_pvt *dialog);
1177 /*--- Device object handling */
1178 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1179 static int update_call_counter(struct sip_pvt *fup, int event);
1180 static void sip_destroy_peer(struct sip_peer *peer);
1181 static void sip_destroy_peer_fn(void *peer);
1182 static void set_peer_defaults(struct sip_peer *peer);
1183 static struct sip_peer *temp_peer(const char *name);
1184 static void register_peer_exten(struct sip_peer *peer, int onoff);
1185 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
1186 static int sip_poke_peer_s(const void *data);
1187 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1188 static void reg_source_db(struct sip_peer *peer);
1189 static void destroy_association(struct sip_peer *peer);
1190 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1191 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1192 static void set_socket_transport(struct sip_socket *socket, int transport);
1194 /* Realtime device support */
1195 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1196 static void update_peer(struct sip_peer *p, int expire);
1197 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1198 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1199 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1200 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1202 /*--- Internal UA client handling (outbound registrations) */
1203 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
1204 static void sip_registry_destroy(struct sip_registry *reg);
1205 static int sip_register(const char *value, int lineno);
1206 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1207 static int sip_reregister(const void *data);
1208 static int __sip_do_register(struct sip_registry *r);
1209 static int sip_reg_timeout(const void *data);
1210 static void sip_send_all_registers(void);
1211 static int sip_reinvite_retry(const void *data);
1213 /*--- Parsing SIP requests and responses */
1214 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1215 static int determine_firstline_parts(struct sip_request *req);
1216 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1217 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1218 static int find_sip_method(const char *msg);
1219 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1220 static unsigned int parse_allowed_methods(struct sip_request *req);
1221 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1222 static int parse_request(struct sip_request *req);
1223 static const char *get_header(const struct sip_request *req, const char *name);
1224 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1225 static int method_match(enum sipmethod id, const char *name);
1226 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1227 static const char *find_alias(const char *name, const char *_default);
1228 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1229 static int lws2sws(char *msgbuf, int len);
1230 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1231 static char *remove_uri_parameters(char *uri);
1232 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1233 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1234 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1235 static int set_address_from_contact(struct sip_pvt *pvt);
1236 static void check_via(struct sip_pvt *p, struct sip_request *req);
1237 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1238 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1239 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1240 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1241 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1242 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1243 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1244 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);
1245 static int get_domain(const char *str, char *domain, int len);
1246 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1248 /*-- TCP connection handling ---*/
1249 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1250 static void *sip_tcp_worker_fn(void *);
1252 /*--- Constructing requests and responses */
1253 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1254 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1255 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1256 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1257 static int init_resp(struct sip_request *resp, const char *msg);
1258 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1259 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1260 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1261 static void build_via(struct sip_pvt *p);
1262 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1263 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
1264 static char *generate_random_string(char *buf, size_t size);
1265 static void build_callid_pvt(struct sip_pvt *pvt);
1266 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1267 static void make_our_tag(char *tagbuf, size_t len);
1268 static int add_header(struct sip_request *req, const char *var, const char *value);
1269 static int add_header_contentLength(struct sip_request *req, int len);
1270 static int add_line(struct sip_request *req, const char *line);
1271 static int add_text(struct sip_request *req, const char *text);
1272 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1273 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1274 static int add_vidupdate(struct sip_request *req);
1275 static void add_route(struct sip_request *req, struct sip_route *route);
1276 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1277 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1278 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1279 static void set_destination(struct sip_pvt *p, char *uri);
1280 static void append_date(struct sip_request *req);
1281 static void build_contact(struct sip_pvt *p);
1283 /*------Request handling functions */
1284 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1285 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1286 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, const char *e, int *nounlock);
1287 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1288 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1289 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, const char *e);
1290 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1291 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1292 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1293 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1294 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1295 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
1296 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1297 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1299 /*------Response handling functions */
1300 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1301 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1302 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1303 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1304 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1305 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1307 /*------ T38 Support --------- */
1308 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1309 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1310 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1311 static void change_t38_state(struct sip_pvt *p, int state);
1313 /*------ Session-Timers functions --------- */
1314 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1315 static int proc_session_timer(const void *vp);
1316 static void stop_session_timer(struct sip_pvt *p);
1317 static void start_session_timer(struct sip_pvt *p);
1318 static void restart_session_timer(struct sip_pvt *p);
1319 static const char *strefresher2str(enum st_refresher r);
1320 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1321 static int parse_minse(const char *p_hdrval, int *const p_interval);
1322 static int st_get_se(struct sip_pvt *, int max);
1323 static enum st_refresher st_get_refresher(struct sip_pvt *);
1324 static enum st_mode st_get_mode(struct sip_pvt *);
1325 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1327 /*------- RTP Glue functions -------- */
1328 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, format_t codecs, int nat_active);
1330 /*!--- SIP MWI Subscription support */
1331 static int sip_subscribe_mwi(const char *value, int lineno);
1332 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1333 static void sip_send_all_mwi_subscriptions(void);
1334 static int sip_subscribe_mwi_do(const void *data);
1335 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1337 /*! \brief Definition of this channel for PBX channel registration */
1338 const struct ast_channel_tech sip_tech = {
1340 .description = "Session Initiation Protocol (SIP)",
1341 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
1342 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1343 .requester = sip_request_call, /* called with chan unlocked */
1344 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1345 .call = sip_call, /* called with chan locked */
1346 .send_html = sip_sendhtml,
1347 .hangup = sip_hangup, /* called with chan locked */
1348 .answer = sip_answer, /* called with chan locked */
1349 .read = sip_read, /* called with chan locked */
1350 .write = sip_write, /* called with chan locked */
1351 .write_video = sip_write, /* called with chan locked */
1352 .write_text = sip_write,
1353 .indicate = sip_indicate, /* called with chan locked */
1354 .transfer = sip_transfer, /* called with chan locked */
1355 .fixup = sip_fixup, /* called with chan locked */
1356 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1357 .send_digit_end = sip_senddigit_end,
1358 .bridge = ast_rtp_instance_bridge, /* XXX chan unlocked ? */
1359 .early_bridge = ast_rtp_instance_early_bridge,
1360 .send_text = sip_sendtext, /* called with chan locked */
1361 .func_channel_read = sip_acf_channel_read,
1362 .setoption = sip_setoption,
1363 .queryoption = sip_queryoption,
1364 .get_pvt_uniqueid = sip_get_callid,
1367 /*! \brief This version of the sip channel tech has no send_digit_begin
1368 * callback so that the core knows that the channel does not want
1369 * DTMF BEGIN frames.
1370 * The struct is initialized just before registering the channel driver,
1371 * and is for use with channels using SIP INFO DTMF.
1373 struct ast_channel_tech sip_tech_info;
1375 /*! \brief Working TLS connection configuration */
1376 static struct ast_tls_config sip_tls_cfg;
1378 /*! \brief Default TLS connection configuration */
1379 static struct ast_tls_config default_tls_cfg;
1381 /*! \brief The TCP server definition */
1382 static struct ast_tcptls_session_args sip_tcp_desc = {
1384 .master = AST_PTHREADT_NULL,
1387 .name = "SIP TCP server",
1388 .accept_fn = ast_tcptls_server_root,
1389 .worker_fn = sip_tcp_worker_fn,
1392 /*! \brief The TCP/TLS server definition */
1393 static struct ast_tcptls_session_args sip_tls_desc = {
1395 .master = AST_PTHREADT_NULL,
1396 .tls_cfg = &sip_tls_cfg,
1398 .name = "SIP TLS server",
1399 .accept_fn = ast_tcptls_server_root,
1400 .worker_fn = sip_tcp_worker_fn,
1403 /*! \brief Append to SIP dialog history
1404 \return Always returns 0 */
1405 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1407 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1411 __ao2_ref_debug(p, 1, tag, file, line, func);
1416 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1420 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1424 __ao2_ref_debug(p, -1, tag, file, line, func);
1431 /*! \brief map from an integer value to a string.
1432 * If no match is found, return errorstring
1434 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
1436 const struct _map_x_s *cur;
1438 for (cur = table; cur->s; cur++)
1444 /*! \brief map from a string to an integer value, case insensitive.
1445 * If no match is found, return errorvalue.
1447 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
1449 const struct _map_x_s *cur;
1451 for (cur = table; cur->s; cur++)
1452 if (!strcasecmp(cur->s, s))
1457 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
1459 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
1462 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
1463 if (!strcasecmp(text, sip_reason_table[i].text)) {
1464 ast = sip_reason_table[i].code;
1472 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
1474 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
1475 return sip_reason_table[code].text;
1482 * \brief generic function for determining if a correct transport is being
1483 * used to contact a peer
1485 * this is done as a macro so that the "tmpl" var can be passed either a
1486 * sip_request or a sip_peer
1488 #define check_request_transport(peer, tmpl) ({ \
1490 if (peer->socket.type == tmpl->socket.type) \
1492 else if (!(peer->transports & tmpl->socket.type)) {\
1493 ast_log(LOG_ERROR, \
1494 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
1495 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
1498 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
1499 ast_log(LOG_WARNING, \
1500 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
1501 peer->name, get_transport(tmpl->socket.type) \
1505 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
1506 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
1513 * duplicate a list of channel variables, \return the copy.
1515 static struct ast_variable *copy_vars(struct ast_variable *src)
1517 struct ast_variable *res = NULL, *tmp, *v = NULL;
1519 for (v = src ; v ; v = v->next) {
1520 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
1528 static void tcptls_packet_destructor(void *obj)
1530 struct tcptls_packet *packet = obj;
1532 ast_free(packet->data);
1535 static void sip_tcptls_client_args_destructor(void *obj)
1537 struct ast_tcptls_session_args *args = obj;
1538 if (args->tls_cfg) {
1539 ast_free(args->tls_cfg->certfile);
1540 ast_free(args->tls_cfg->pvtfile);
1541 ast_free(args->tls_cfg->cipher);
1542 ast_free(args->tls_cfg->cafile);
1543 ast_free(args->tls_cfg->capath);
1545 ast_free(args->tls_cfg);
1546 ast_free((char *) args->name);
1549 static void sip_threadinfo_destructor(void *obj)
1551 struct sip_threadinfo *th = obj;
1552 struct tcptls_packet *packet;
1553 if (th->alert_pipe[1] > -1) {
1554 close(th->alert_pipe[0]);
1556 if (th->alert_pipe[1] > -1) {
1557 close(th->alert_pipe[1]);
1559 th->alert_pipe[0] = th->alert_pipe[1] = -1;
1561 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
1562 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
1565 if (th->tcptls_session) {
1566 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
1570 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
1571 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
1573 struct sip_threadinfo *th;
1575 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
1579 th->alert_pipe[0] = th->alert_pipe[1] = -1;
1581 if (pipe(th->alert_pipe) == -1) {
1582 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
1583 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
1586 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
1587 th->tcptls_session = tcptls_session;
1588 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
1589 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
1590 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
1594 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
1595 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
1598 struct sip_threadinfo *th = NULL;
1599 struct tcptls_packet *packet = NULL;
1600 struct sip_threadinfo tmp = {
1601 .tcptls_session = tcptls_session,
1603 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
1605 if (!tcptls_session) {
1609 ast_mutex_lock(&tcptls_session->lock);
1611 if ((tcptls_session->fd == -1) ||
1612 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
1613 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
1614 !(packet->data = ast_str_create(len))) {
1615 goto tcptls_write_setup_error;
1618 /* goto tcptls_write_error should _NOT_ be used beyond this point */
1619 ast_str_set(&packet->data, 0, "%s", (char *) buf);
1622 /* alert tcptls thread handler that there is a packet to be sent.
1623 * must lock the thread info object to guarantee control of the
1626 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
1627 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
1628 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
1631 } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
1632 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
1636 ast_mutex_unlock(&tcptls_session->lock);
1637 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
1640 tcptls_write_setup_error:
1642 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
1645 ao2_t_ref(packet, -1, "could not allocate packet's data");
1647 ast_mutex_unlock(&tcptls_session->lock);
1652 /*! \brief SIP TCP connection handler */
1653 static void *sip_tcp_worker_fn(void *data)
1655 struct ast_tcptls_session_instance *tcptls_session = data;
1657 return _sip_tcp_helper_thread(NULL, tcptls_session);
1660 /*! \brief SIP TCP thread management function
1661 This function reads from the socket, parses the packet into a request
1663 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
1666 struct sip_request req = { 0, } , reqcpy = { 0, };
1667 struct sip_threadinfo *me = NULL;
1668 char buf[1024] = "";
1669 struct pollfd fds[2] = { { 0 }, { 0 }, };
1670 struct ast_tcptls_session_args *ca = NULL;
1672 /* If this is a server session, then the connection has already been setup,
1673 * simply create the threadinfo object so we can access this thread for writing.
1675 * if this is a client connection more work must be done.
1676 * 1. We own the parent session args for a client connection. This pointer needs
1677 * to be held on to so we can decrement it's ref count on thread destruction.
1678 * 2. The threadinfo object was created before this thread was launched, however
1679 * it must be found within the threadt table.
1680 * 3. Last, the tcptls_session must be started.
1682 if (!tcptls_session->client) {
1683 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
1686 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
1688 struct sip_threadinfo tmp = {
1689 .tcptls_session = tcptls_session,
1692 if ((!(ca = tcptls_session->parent)) ||
1693 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
1694 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
1699 me->threadid = pthread_self();
1700 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
1702 /* set up pollfd to watch for reads on both the socket and the alert_pipe */
1703 fds[0].fd = tcptls_session->fd;
1704 fds[1].fd = me->alert_pipe[0];
1705 fds[0].events = fds[1].events = POLLIN | POLLPRI;
1707 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
1709 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
1713 struct ast_str *str_save;
1715 res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
1717 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
1721 /* handle the socket event, check for both reads from the socket fd,
1722 * and writes from alert_pipe fd */
1723 if (fds[0].revents) { /* there is data on the socket to be read */
1727 /* clear request structure */
1728 str_save = req.data;
1729 memset(&req, 0, sizeof(req));
1730 req.data = str_save;
1731 ast_str_reset(req.data);
1733 str_save = reqcpy.data;
1734 memset(&reqcpy, 0, sizeof(reqcpy));
1735 reqcpy.data = str_save;
1736 ast_str_reset(reqcpy.data);
1738 memset(buf, 0, sizeof(buf));
1740 if (tcptls_session->ssl) {
1741 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
1742 req.socket.port = htons(ourport_tls);
1744 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
1745 req.socket.port = htons(ourport_tcp);
1747 req.socket.fd = tcptls_session->fd;
1749 /* Read in headers one line at a time */
1750 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
1751 ast_mutex_lock(&tcptls_session->lock);
1752 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
1753 ast_mutex_unlock(&tcptls_session->lock);
1756 ast_mutex_unlock(&tcptls_session->lock);
1759 ast_str_append(&req.data, 0, "%s", buf);
1760 req.len = req.data->used;
1762 copy_request(&reqcpy, &req);
1763 parse_request(&reqcpy);
1764 /* In order to know how much to read, we need the content-length header */
1765 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
1768 ast_mutex_lock(&tcptls_session->lock);
1769 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
1770 ast_mutex_unlock(&tcptls_session->lock);
1773 buf[bytes_read] = '\0';
1774 ast_mutex_unlock(&tcptls_session->lock);
1778 ast_str_append(&req.data, 0, "%s", buf);
1779 req.len = req.data->used;
1782 /*! \todo XXX If there's no Content-Length or if the content-length and what
1783 we receive is not the same - we should generate an error */
1785 req.socket.tcptls_session = tcptls_session;
1786 handle_request_do(&req, &tcptls_session->remote_address);
1789 if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
1790 enum sip_tcptls_alert alert;
1791 struct tcptls_packet *packet;
1795 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
1796 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
1801 case TCPTLS_ALERT_STOP:
1803 case TCPTLS_ALERT_DATA:
1805 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
1806 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
1807 } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
1808 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
1812 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
1817 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
1822 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
1826 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
1827 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
1830 ast_free(reqcpy.data);
1838 /* if client, we own the parent session arguments and must decrement ref */
1840 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
1843 if (tcptls_session) {
1844 ast_mutex_lock(&tcptls_session->lock);
1845 if (tcptls_session->f) {
1846 fclose(tcptls_session->f);
1847 tcptls_session->f = NULL;
1849 if (tcptls_session->fd != -1) {
1850 close(tcptls_session->fd);
1851 tcptls_session->fd = -1;
1853 tcptls_session->parent = NULL;
1854 ast_mutex_unlock(&tcptls_session->lock);
1856 ao2_ref(tcptls_session, -1);
1857 tcptls_session = NULL;
1864 * helper functions to unreference various types of objects.
1865 * By handling them this way, we don't have to declare the
1866 * destructor on each call, which removes the chance of errors.
1868 static void *unref_peer(struct sip_peer *peer, char *tag)
1870 ao2_t_ref(peer, -1, tag);
1874 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
1876 ao2_t_ref(peer, 1, tag);
1880 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
1882 * This function sets pvt's outboundproxy pointer to the one referenced
1883 * by the proxy parameter. Because proxy may be a refcounted object, and
1884 * because pvt's old outboundproxy may also be a refcounted object, we need
1885 * to maintain the proper refcounts.
1887 * \param pvt The sip_pvt for which we wish to set the outboundproxy
1888 * \param proxy The sip_proxy which we will point pvt towards.
1889 * \return Returns void
1891 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
1893 struct sip_proxy *old_obproxy = pvt->outboundproxy;
1894 /* The sip_cfg.outboundproxy is statically allocated, and so
1895 * we don't ever need to adjust refcounts for it
1897 if (proxy && proxy != &sip_cfg.outboundproxy) {
1900 pvt->outboundproxy = proxy;
1901 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
1902 ao2_ref(old_obproxy, -1);
1907 * \brief Unlink a dialog from the dialogs container, as well as any other places
1908 * that it may be currently stored.
1910 * \note A reference to the dialog must be held before calling this function, and this
1911 * function does not release that reference.
1913 void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
1917 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
1919 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
1921 /* Unlink us from the owner (channel) if we have one */
1922 if (dialog->owner) {
1924 ast_channel_lock(dialog->owner);
1925 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
1926 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
1928 ast_channel_unlock(dialog->owner);
1930 if (dialog->registry) {
1931 if (dialog->registry->call == dialog)
1932 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
1933 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
1935 if (dialog->stateid > -1) {
1936 ast_extension_state_del(dialog->stateid, NULL);
1937 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
1938 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
1940 /* Remove link from peer to subscription of MWI */
1941 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
1942 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
1943 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
1944 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
1946 /* remove all current packets in this dialog */
1947 while((cp = dialog->packets)) {
1948 dialog->packets = dialog->packets->next;
1949 AST_SCHED_DEL(sched, cp->retransid);
1950 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
1957 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"));
1959 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"));
1961 if (dialog->autokillid > -1)
1962 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"));
1964 if (dialog->request_queue_sched_id > -1) {
1965 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"));
1968 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"));
1970 if (dialog->t38id > -1) {
1971 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"));
1974 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
1978 void *registry_unref(struct sip_registry *reg, char *tag)
1980 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
1981 ASTOBJ_UNREF(reg, sip_registry_destroy);
1985 /*! \brief Add object reference to SIP registry */
1986 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
1988 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
1989 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
1992 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1993 static struct ast_udptl_protocol sip_udptl = {
1995 get_udptl_info: sip_get_udptl_peer,
1996 set_udptl_peer: sip_set_udptl_peer,
1999 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2000 __attribute__((format(printf, 2, 3)));
2003 /*! \brief Convert transfer status to string */
2004 static const char *referstatus2str(enum referstatus rstatus)
2006 return map_x_s(referstatusstrings, rstatus, "");
2009 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2011 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2012 pvt->needdestroy = 1;
2015 /*! \brief Initialize the initital request packet in the pvt structure.
2016 This packet is used for creating replies and future requests in
2018 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2020 if (p->initreq.headers)
2021 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2023 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2024 /* Use this as the basis */
2025 copy_request(&p->initreq, req);
2026 parse_request(&p->initreq);
2028 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2031 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2032 static void sip_alreadygone(struct sip_pvt *dialog)
2034 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2035 dialog->alreadygone = 1;
2038 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2039 static int proxy_update(struct sip_proxy *proxy)
2041 /* if it's actually an IP address and not a name,
2042 there's no need for a managed lookup */
2043 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2044 /* Ok, not an IP address, then let's check if it's a domain or host */
2045 /* XXX Todo - if we have proxy port, don't do SRV */
2046 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2047 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2051 proxy->last_dnsupdate = time(NULL);
2055 /*! \brief converts ascii port to int representation. If no
2056 * pt buffer is provided or the pt has errors when being converted
2057 * to an int value, the port provided as the standard is used.
2059 unsigned int port_str2int(const char *pt, unsigned int standard)
2061 int port = standard;
2062 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2069 /*! \brief Allocate and initialize sip proxy */
2070 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2072 struct sip_proxy *proxy;
2074 if (ast_strlen_zero(name)) {
2078 proxy = ao2_alloc(sizeof(*proxy), NULL);
2081 proxy->force = force;
2082 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2083 proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
2084 proxy_update(proxy);
2088 /*! \brief Get default outbound proxy or global proxy */
2089 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2091 if (peer && peer->outboundproxy) {
2093 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2094 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2095 return peer->outboundproxy;
2097 if (sip_cfg.outboundproxy.name[0]) {
2099 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2100 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2101 return &sip_cfg.outboundproxy;
2104 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2108 /*! \brief returns true if 'name' (with optional trailing whitespace)
2109 * matches the sip method 'id'.
2110 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2111 * a case-insensitive comparison to be more tolerant.
2112 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2114 static int method_match(enum sipmethod id, const char *name)
2116 int len = strlen(sip_methods[id].text);
2117 int l_name = name ? strlen(name) : 0;
2118 /* true if the string is long enough, and ends with whitespace, and matches */
2119 return (l_name >= len && name[len] < 33 &&
2120 !strncasecmp(sip_methods[id].text, name, len));
2123 /*! \brief find_sip_method: Find SIP method from header */
2124 static int find_sip_method(const char *msg)
2128 if (ast_strlen_zero(msg))
2130 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2131 if (method_match(i, msg))
2132 res = sip_methods[i].id;
2137 /*! \brief Parse supported header in incoming packet */
2138 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2142 unsigned int profile = 0;
2145 if (ast_strlen_zero(supported) )
2147 temp = ast_strdupa(supported);
2150 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2152 for (next = temp; next; next = sep) {
2154 if ( (sep = strchr(next, ',')) != NULL)
2156 next = ast_skip_blanks(next);
2158 ast_debug(3, "Found SIP option: -%s-\n", next);
2159 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2160 if (!strcasecmp(next, sip_options[i].text)) {
2161 profile |= sip_options[i].id;
2164 ast_debug(3, "Matched SIP option: %s\n", next);
2169 /* This function is used to parse both Suported: and Require: headers.
2170 Let the caller of this function know that an unknown option tag was
2171 encountered, so that if the UAC requires it then the request can be
2172 rejected with a 420 response. */
2174 profile |= SIP_OPT_UNKNOWN;
2176 if (!found && sipdebug) {
2177 if (!strncasecmp(next, "x-", 2))
2178 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2180 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2185 pvt->sipoptions = profile;
2189 /*! \brief See if we pass debug IP filter */
2190 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2194 if (debugaddr.sin_addr.s_addr) {
2195 if (((ntohs(debugaddr.sin_port) != 0)
2196 && (debugaddr.sin_port != addr->sin_port))
2197 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2203 /*! \brief The real destination address for a write */
2204 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2206 if (p->outboundproxy)
2207 return &p->outboundproxy->ip;
2209 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
2212 /*! \brief Display SIP nat mode */
2213 static const char *sip_nat_mode(const struct sip_pvt *p)
2215 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
2218 /*! \brief Test PVT for debugging output */
2219 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2223 return sip_debug_test_addr(sip_real_dst(p));
2226 /*! \brief Return int representing a bit field of transport types found in const char *transport */
2227 static int get_transport_str2enum(const char *transport)
2231 if (ast_strlen_zero(transport)) {
2235 if (!strcasecmp(transport, "udp")) {
2236 res |= SIP_TRANSPORT_UDP;
2238 if (!strcasecmp(transport, "tcp")) {
2239 res |= SIP_TRANSPORT_TCP;
2241 if (!strcasecmp(transport, "tls")) {
2242 res |= SIP_TRANSPORT_TLS;
2248 /*! \brief Return configuration of transports for a device */
2249 static inline const char *get_transport_list(unsigned int transports) {
2250 switch (transports) {
2251 case SIP_TRANSPORT_UDP:
2253 case SIP_TRANSPORT_TCP:
2255 case SIP_TRANSPORT_TLS:
2257 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
2259 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
2261 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
2265 "TLS,TCP,UDP" : "UNKNOWN";
2269 /*! \brief Return transport as string */
2270 static inline const char *get_transport(enum sip_transport t)
2273 case SIP_TRANSPORT_UDP:
2275 case SIP_TRANSPORT_TCP:
2277 case SIP_TRANSPORT_TLS:
2284 /*! \brief Return transport of dialog.
2285 \note this is based on a false assumption. We don't always use the
2286 outbound proxy for all requests in a dialog. It depends on the
2287 "force" parameter. The FIRST request is always sent to the ob proxy.
2288 \todo Fix this function to work correctly
2290 static inline const char *get_transport_pvt(struct sip_pvt *p)
2292 if (p->outboundproxy && p->outboundproxy->transport) {
2293 set_socket_transport(&p->socket, p->outboundproxy->transport);
2296 return get_transport(p->socket.type);
2299 /*! \brief Transmit SIP message
2300 Sends a SIP request or response on a given socket (in the pvt)
2301 Called by retrans_pkt, send_request, send_response and
2303 \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
2305 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2308 const struct sockaddr_in *dst = sip_real_dst(p);
2310 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
2312 if (sip_prepare_socket(p) < 0)
2315 if (p->socket.type == SIP_TRANSPORT_UDP) {
2316 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2317 } else if (p->socket.tcptls_session) {
2318 res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
2320 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
2326 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2327 case EHOSTUNREACH: /* Host can't be reached */
2328 case ENETDOWN: /* Interface down */
2329 case ENETUNREACH: /* Network failure */
2330 case ECONNREFUSED: /* ICMP port unreachable */
2331 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2335 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
2340 /*! \brief Build a Via header for a request */
2341 static void build_via(struct sip_pvt *p)
2343 /* Work around buggy UNIDEN UIP200 firmware */
2344 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
2346 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2347 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
2348 get_transport_pvt(p),
2349 ast_inet_ntoa(p->ourip.sin_addr),
2350 ntohs(p->ourip.sin_port), (int) p->branch, rport);
2353 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2355 * Using the localaddr structure built up with localnet statements in sip.conf
2356 * apply it to their address to see if we need to substitute our
2357 * externip or can get away with our internal bindaddr
2358 * 'us' is always overwritten.
2360 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
2362 struct sockaddr_in theirs;
2363 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2364 * reachable IP address and port. This is done if:
2365 * 1. we have a localaddr list (containing 'internal' addresses marked
2366 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2367 * and AST_SENSE_ALLOW on 'external' ones);
2368 * 2. either stunaddr or externip is set, so we know what to use as the
2369 * externally visible address;
2370 * 3. the remote address, 'them', is external;
2371 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2372 * when passed to ast_apply_ha() so it does need to be remapped.
2373 * This fourth condition is checked later.
2377 *us = internip; /* starting guess for the internal address */
2378 /* now ask the system what would it use to talk to 'them' */
2379 ast_ouraddrfor(them, &us->sin_addr);
2380 theirs.sin_addr = *them;
2382 want_remap = localaddr &&
2383 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2384 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2387 (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2388 /* if we used externhost or stun, see if it is time to refresh the info */
2389 if (externexpire && time(NULL) >= externexpire) {
2390 if (stunaddr.sin_addr.s_addr) {
2391 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2393 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2394 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2396 externexpire = time(NULL) + externrefresh;
2398 if (externip.sin_addr.s_addr) {
2400 switch (p->socket.type) {
2401 case SIP_TRANSPORT_TCP:
2402 us->sin_port = htons(externtcpport);
2404 case SIP_TRANSPORT_TLS:
2405 us->sin_port = htons(externtlsport);
2407 case SIP_TRANSPORT_UDP:
2408 break; /* fall through */
2410 us->sin_port = htons(STANDARD_SIP_PORT); /* we should never get here */
2414 ast_log(LOG_WARNING, "stun failed\n");
2415 ast_debug(1, "Target address %s is not local, substituting externip\n",
2416 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2418 /* no remapping, but we bind to a specific address, so use it. */
2419 switch (p->socket.type) {
2420 case SIP_TRANSPORT_TCP:
2421 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
2422 *us = sip_tcp_desc.local_address;
2424 us->sin_port = sip_tcp_desc.local_address.sin_port;
2427 case SIP_TRANSPORT_TLS:
2428 if (sip_tls_desc.local_address.sin_addr.s_addr) {
2429 *us = sip_tls_desc.local_address;
2431 us->sin_port = sip_tls_desc.local_address.sin_port;
2434 case SIP_TRANSPORT_UDP:
2435 /* fall through on purpose */
2437 if (bindaddr.sin_addr.s_addr) {
2441 } else if (bindaddr.sin_addr.s_addr) {
2444 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
2447 /*! \brief Append to SIP dialog history with arg list */
2448 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2450 char buf[80], *c = buf; /* max history length */
2451 struct sip_history *hist;
2454 vsnprintf(buf, sizeof(buf), fmt, ap);
2455 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2456 l = strlen(buf) + 1;
2457 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2459 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2463 memcpy(hist->event, buf, l);
2464 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2465 struct sip_history *oldest;
2466 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2467 p->history_entries--;
2470 AST_LIST_INSERT_TAIL(p->history, hist, list);
2471 p->history_entries++;
2474 /*! \brief Append to SIP dialog history with arg list */
2475 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2482 if (!p->do_history && !recordhistory && !dumphistory)
2486 append_history_va(p, fmt, ap);
2492 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2493 static int retrans_pkt(const void *data)
2495 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2496 int reschedule = DEFAULT_RETRANS;
2499 /* Lock channel PVT */
2500 sip_pvt_lock(pkt->owner);
2502 if (pkt->retrans < MAX_RETRANS) {
2504 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2506 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
2511 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2515 pkt->timer_a = 2 * pkt->timer_a;
2517 /* For non-invites, a maximum of 4 secs */
2518 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2519 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2522 /* Reschedule re-transmit */
2523 reschedule = siptimer_a;
2524 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
2527 if (sip_debug_test_pvt(pkt->owner)) {
2528 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2529 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2530 pkt->retrans, sip_nat_mode(pkt->owner),
2531 ast_inet_ntoa(dst->sin_addr),
2532 ntohs(dst->sin_port), pkt->data->str);
2535 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
2536 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2537 sip_pvt_unlock(pkt->owner);
2538 if (xmitres == XMIT_ERROR)
2539 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2543 /* Too many retries */
2544 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2545 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2546 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
2547 pkt->owner->callid, pkt->seqno,
2548 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2549 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2550 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
2553 if (xmitres == XMIT_ERROR) {
2554 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2555 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2557 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2559 pkt->retransid = -1;
2561 if (pkt->is_fatal) {
2562 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2563 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2565 sip_pvt_lock(pkt->owner);
2568 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
2569 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2571 if (pkt->owner->owner) {
2572 sip_alreadygone(pkt->owner);
2573 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
2574 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
2575 ast_channel_unlock(pkt->owner->owner);
2577 /* If no channel owner, destroy now */
2579 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2580 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2581 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
2582 sip_alreadygone(pkt->owner);
2583 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2588 if (pkt->method == SIP_BYE) {
2589 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
2590 if (pkt->owner->owner)
2591 ast_channel_unlock(pkt->owner->owner);
2592 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2593 pvt_set_needdestroy(pkt->owner, "no response to BYE");
2596 /* Remove the packet */
2597 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2599 UNLINK(cur, pkt->owner->packets, prev);
2600 sip_pvt_unlock(pkt->owner);
2602 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
2604 ast_free(pkt->data);
2611 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2612 sip_pvt_unlock(pkt->owner);
2616 /*! \brief Transmit packet with retransmits
2617 \return 0 on success, -1 on failure to allocate packet
2619 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
2621 struct sip_pkt *pkt = NULL;
2622 int siptimer_a = DEFAULT_RETRANS;
2626 if (sipmethod == SIP_INVITE) {
2627 /* Note this is a pending invite */
2628 p->pendinginvite = seqno;
2631 /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
2632 /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
2633 /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
2634 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
2635 xmitres = __sip_xmit(p, data, len); /* Send packet */
2636 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2637 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
2644 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2646 /* copy data, add a terminator and save length */
2647 if (!(pkt->data = ast_str_create(len))) {
2651 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
2652 pkt->packetlen = len;
2653 /* copy other parameters from the caller */
2654 pkt->method = sipmethod;
2656 pkt->is_resp = resp;
2657 pkt->is_fatal = fatal;
2658 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
2659 pkt->next = p->packets;
2660 p->packets = pkt; /* Add it to the queue */
2662 /* Parse out the response code */
2663 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
2664 pkt->response_code = respid;
2667 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2668 pkt->retransid = -1;
2670 siptimer_a = pkt->timer_t1 * 2;
2672 /* Schedule retransmission */
2673 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
2675 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2677 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2679 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2680 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2681 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
2682 AST_SCHED_DEL(sched, pkt->retransid);
2683 p->packets = pkt->next;
2684 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
2685 ast_free(pkt->data);
2693 /*! \brief Kill a SIP dialog (called only by the scheduler)
2694 * The scheduler has a reference to this dialog when p->autokillid != -1,
2695 * and we are called using that reference. So if the event is not
2696 * rescheduled, we need to call dialog_unref().
2698 static int __sip_autodestruct(const void *data)
2700 struct sip_pvt *p = (struct sip_pvt *)data;
2702 /* If this is a subscription, tell the phone that we got a timeout */
2703 if (p->subscribed) {
2704 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2705 p->subscribed = NONE;
2706 append_history(p, "Subscribestatus", "timeout");
2707 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
2708 return 10000; /* Reschedule this destruction so that we know that it's gone */
2711 /* If there are packets still waiting for delivery, delay the destruction */
2713 if (!p->needdestroy) {
2714 char method_str[31];
2715 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2716 append_history(p, "ReliableXmit", "timeout");
2717 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
2718 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
2719 pvt_set_needdestroy(p, "autodestruct");
2724 /* They've had their chance to respond. Time to bail */
2725 __sip_pretend_ack(p);
2729 if (p->subscribed == MWI_NOTIFICATION) {
2730 if (p->relatedpeer) {
2731 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer"); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2735 /* Reset schedule ID */
2739 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2740 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
2741 } else if (p->refer && !p->alreadygone) {
2742 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
2743 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2744 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2745 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2747 append_history(p, "AutoDestroy", "%s", p->callid);
2748 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
2749 dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
2750 /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
2751 /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
2752 /* sip_destroy also absorbs the reference */
2754 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
2758 /*! \brief Schedule destruction of SIP dialog */
2759 void sip_scheddestroy(struct sip_pvt *p, int ms)
2762 if (p->timer_t1 == 0) {
2763 p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
2765 if (p->timer_b == 0) {
2766 p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
2768 ms = p->timer_t1 * 64;
2770 if (sip_debug_test_pvt(p))
2771 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2772 if (sip_cancel_destroy(p))
2773 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
2776 append_history(p, "SchedDestroy", "%d ms", ms);
2777 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
2779 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
2780 stop_session_timer(p);
2783 /*! \brief Cancel destruction of SIP dialog.
2784 * Be careful as this also absorbs the reference - if you call it
2785 * from within the scheduler, this might be the last reference.
2787 int sip_cancel_destroy(struct sip_pvt *p)
2790 if (p->autokillid > -1) {
2793 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
2794 append_history(p, "CancelDestroy", "");
2796 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
2802 /*! \brief Acknowledges receipt of a packet and stops retransmission
2803 * called with p locked*/
2804 int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2806 struct sip_pkt *cur, *prev = NULL;
2807 const char *msg = "Not Found"; /* used only for debugging */
2810 /* If we have an outbound proxy for this dialog, then delete it now since
2811 the rest of the requests in this dialog needs to follow the routing.
2812 If obforcing is set, we will keep the outbound proxy during the whole
2813 dialog, regardless of what the SIP rfc says
2815 if (p->outboundproxy && !p->outboundproxy->force){
2819 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2820 if (cur->seqno != seqno || cur->is_resp != resp)
2822 if (cur->is_resp || cur->method == sipmethod) {
2825 if (!resp && (seqno == p->pendinginvite)) {
2826 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
2827 p->pendinginvite = 0;
2829 if (cur->retransid > -1) {
2831 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2833 /* This odd section is designed to thwart a
2834 * race condition in the packet scheduler. There are
2835 * two conditions under which deleting the packet from the
2836 * scheduler can fail.
2838 * 1. The packet has been removed from the scheduler because retransmission
2839 * is being attempted. The problem is that if the packet is currently attempting
2840 * retransmission and we are at this point in the code, then that MUST mean
2841 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
2842 * lock temporarily to allow retransmission.
2844 * 2. The packet has reached its maximum number of retransmissions and has
2845 * been permanently removed from the packet scheduler. If this is the case, then
2846 * the packet's retransid will be set to -1. The atomicity of the setting and checking
2847 * of the retransid to -1 is ensured since in both cases p's lock is held.
2849 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
2854 UNLINK(cur, p->packets, prev);
2855 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
2857 ast_free(cur->data);
2862 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2863 p->callid, resp ? "Response" : "Request", seqno, msg);
2867 /*! \brief Pretend to ack all packets
2868 * called with p locked */
2869 void __sip_pretend_ack(struct sip_pvt *p)
2871 struct sip_pkt *cur = NULL;
2873 while (p->packets) {
2875 if (cur == p->packets) {
2876 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2880 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
2881 __sip_ack(p, cur->seqno, cur->is_resp, method);
2885 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2886 int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2888 struct sip_pkt *cur;
2891 for (cur = p->packets; cur; cur = cur->next) {
2892 if (cur->seqno == seqno && cur->is_resp == resp &&
2893 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
2894 /* this is our baby */
2895 if (cur->retransid > -1) {
2897 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2899 AST_SCHED_DEL(sched, cur->retransid);
2904 ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
2909 /*! \brief Copy SIP request, parse it */
2910 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2912 copy_request(dst, src);
2916 /*! \brief add a blank line if no body */
2917 static void add_blank(struct sip_request *req)
2920 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2921 ast_str_append(&req->data, 0, "\r\n");
2922 req->len = ast_str_strlen(req->data);
2926 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
2928 const char *msg = NULL;
2930 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
2931 msg = "183 Session Progress";
2934 if (pvt->invitestate < INV_COMPLETED) {
2936 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
2938 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
2940 return PROVIS_KEEPALIVE_TIMEOUT;
2946 static int send_provisional_keepalive(const void *data) {
2947 struct sip_pvt *pvt = (struct sip_pvt *) data;
2949 return send_provisional_keepalive_full(pvt, 0);
2952 static int send_provisional_keepalive_with_sdp(const void *data) {
2953 struct sip_pvt *pvt = (void *)data;
2955 return send_provisional_keepalive_full(pvt, 1);
2958 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
2960 AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
2962 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
2963 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
2966 /*! \brief Transmit response on SIP request*/
2967 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2972 if (sip_debug_test_pvt(p)) {
2973 const struct sockaddr_in *dst = sip_real_dst(p);
2975 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2976 reliable ? "Reliably " : "", sip_nat_mode(p),
2977 ast_inet_ntoa(dst->sin_addr),
2978 ntohs(dst->sin_port), req->data->str);
2980 if (p->do_history) {
2981 struct sip_request tmp = { .rlPart1 = 0, };
2982 parse_copy(&tmp, req);
2983 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
2984 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
2988 /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
2989 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
2990 AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
2994 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2995 __sip_xmit(p, req->data, req->len);
2996 ast_free(req->data);
3003 /*! \brief Send SIP Request to the other part of the dialogue
3004 \return see \ref __sip_xmit
3006 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3010 /* If we have an outbound proxy, reset peer address
3013 if (p->outboundproxy) {
3014 p->sa = p->outboundproxy->ip;
3018 if (sip_debug_test_pvt(p)) {
3019 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))
3020 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
3022 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
3024 if (p->do_history) {
3025 struct sip_request tmp = { .rlPart1 = 0, };
3026 parse_copy(&tmp, req);
3027 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3031 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3032 __sip_xmit(p, req->data, req->len);
3034 ast_free(req->data);
3040 static void enable_dsp_detect(struct sip_pvt *p)
3048 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
3049 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
3050 if (!p->rtp || ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND)) {
3051 features |= DSP_FEATURE_DIGIT_DETECT;
3055 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
3056 features |= DSP_FEATURE_FAX_DETECT;
3063 if (!(p->dsp = ast_dsp_new())) {
3067 ast_dsp_set_features(p->dsp, features);
3068 if (global_relaxdtmf) {
3069 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
3073 static void disable_dsp_detect(struct sip_pvt *p)
3076 ast_dsp_free(p->dsp);
3081 /*! \brief Set an option on a SIP dialog */
3082 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
3085 struct sip_pvt *p = chan->tech_pvt;
3088 case AST_OPTION_FORMAT_READ:
3089 res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
3091 case AST_OPTION_FORMAT_WRITE:
3092 res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
3094 case AST_OPTION_MAKE_COMPATIBLE:
3095 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
3097 case AST_OPTION_DIGIT_DETECT:
3098 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
3099 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
3100 char *cp = (char *) data;
3102 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
3104 enable_dsp_detect(p);
3106 disable_dsp_detect(p);
3118 /*! \brief Query an option on a SIP dialog */
3119 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3122 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
3123 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
3127 case AST_OPTION_T38_STATE:
3128 /* Make sure we got an ast_t38_state enum passed in */
3129 if (*datalen != sizeof(enum ast_t38_state)) {
3130 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
3136 /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
3137 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
3138 switch (p->t38.state) {
3139 case T38_LOCAL_REINVITE:
3140 case T38_PEER_REINVITE:
3141 state = T38_STATE_NEGOTIATING;
3144 state = T38_STATE_NEGOTIATED;
3147 state = T38_STATE_UNKNOWN;
3153 *((enum ast_t38_state *) data) = state;
3157 case AST_OPTION_DIGIT_DETECT:
3159 *cp = p->dsp ? 1 : 0;
3160 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
3169 /*! \brief Locate closing quote in a string, skipping escaped quotes.
3170 * optionally with a limit on the search.
3171 * start must be past the first quote.
3173 const char *find_closing_quote(const char *start, const char *lim)
3175 char last_char = '\0';
3177 for (s = start; *s && s != lim; last_char = *s++) {
3178 if (*s == '"' && last_char != '\\')
3184 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
3185 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3187 struct sip_pvt *p = chan->tech_pvt;
3189 if (subclass != AST_HTML_URL)
3192 ast_string_field_build(p, url, "<%s>;mode=active", data);
3194 if (sip_debug_test_pvt(p))
3195 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
3197 switch (chan->_state) {
3198 case AST_STATE_RING:
3199 transmit_response(p, "100 Trying", &p->initreq);
3201 case AST_STATE_RINGING:
3202 transmit_response(p, "180 Ringing", &p->initreq);
3205 if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
3206 transmit_reinvite_with_sdp(p, FALSE, FALSE);
3207 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
3208 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
3212 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
3218 /*! \brief Deliver SIP call ID for the call */
3219 static const char *sip_get_callid(struct ast_channel *chan)
3221 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
3224 /*! \brief Send SIP MESSAGE text within a call
3225 Called from PBX core sendtext() application */
3226 static int sip_sendtext(struct ast_channel *ast, const char *text)
3228 struct sip_pvt *dialog = ast->tech_pvt;
3229 int debug = sip_debug_test_pvt(dialog);
3233 /* NOT ast_strlen_zero, because a zero-length message is specifically
3234 * allowed by RFC 3428 (See section 10, Examples) */
3237 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
3238 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
3242 ast_verbose("Sending text %s on %s\n", text, ast->name);
3243 transmit_message_with_text(dialog, text);
3247 /*! \brief Update peer object in realtime storage
3248 If the Asterisk system name is set in asterisk.conf, we will use
3249 that name and store that in the "regserver" field in the sippeers
3250 table to facilitate multi-server setups.
3252 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms)
3255 char ipaddr[INET_ADDRSTRLEN];
3256 char regseconds[20];
3257 char *tablename = NULL;
3258 char str_lastms[20];
3260 const char *sysname = ast_config_AST_SYSTEM_NAME;
3261 char *syslabel = NULL;
3263 time_t nowtime = time(NULL) + expirey;
3264 const char *fc = fullcontact ? "fullcontact" : NULL;
3266 int realtimeregs = ast_check_realtime("sipregs");
3268 tablename = realtimeregs ? "sipregs" : "sippeers";
3271 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
3272 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
3273 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3274 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3276 if (ast_strlen_zero(sysname)) /* No system name, disable this */
3278 else if (sip_cfg.rtsave_sysname)
3279 syslabel = "regserver";
3282 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3283 "port", port, "regseconds", regseconds,
3284 deprecated_username ? "username" : "defaultuser", defaultuser,
3285 "useragent", useragent, "lastms", str_lastms,
3286 fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
3288 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3289 "port", port, "regseconds", regseconds,
3290 "useragent", useragent, "lastms", str_lastms,
3291 deprecated_username ? "username" : "defaultuser", defaultuser,
3292 syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
3296 /*! \brief Automatically add peer extension to dial plan */
3297 static void register_peer_exten(struct sip_peer *peer, int onoff)
3300 char *stringp, *ext, *context;
3301 struct pbx_find_info q = { .stacklen = 0 };
3303 /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
3304 * the name of the global regexten context, if not specified
3307 if (ast_strlen_zero(sip_cfg.regcontext))
3310 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
3312 while ((ext = strsep(&stringp, "&"))) {
3313 if ((context = strchr(ext, '@'))) {
3314 *context++ = '\0'; /* split ext@context */
3315 if (!ast_context_find(context)) {
3316 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
3320 context = sip_cfg.regcontext;
3323 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
3324 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
3325 ast_strdup(peer->name), ast_free_ptr, "SIP");
3327 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
3328 ast_context_remove_extension(context, ext, 1, NULL);
3333 /*! Destroy mailbox subscriptions */
3334 static void destroy_mailbox(struct sip_mailbox *mailbox)
3336 if (mailbox->mailbox)
3337 ast_free(mailbox->mailbox);
3338 if (mailbox->context)
3339 ast_free(mailbox->context);
3340 if (mailbox->event_sub)
3341 ast_event_unsubscribe(mailbox->event_sub);
3345 /*! Destroy all peer-related mailbox subscriptions */
3346 static void clear_peer_mailboxes(struct sip_peer *peer)
3348 struct sip_mailbox *mailbox;
3350 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
3351 destroy_mailbox(mailbox);
3354 static void sip_destroy_peer_fn(void *peer)
3356 sip_destroy_peer(peer);
3359 /*! \brief Destroy peer object from memory */
3360 static void sip_destroy_peer(struct sip_peer *peer)
3362 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
3363 if (peer->outboundproxy)
3364 ao2_ref(peer->outboundproxy, -1);
3365 peer->outboundproxy = NULL;
3367 /* Delete it, it needs to disappear */
3369 dialog_unlink_all(peer->call, TRUE, TRUE);
3370 peer->call = dialog_unref(peer->call, "peer->call is being unset");
3374 if (peer->mwipvt) { /* We have an active subscription, delete it */
3375 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
3376 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
3379 if (peer->chanvars) {
3380 ast_variables_destroy(peer->chanvars);
3381 peer->chanvars = NULL;
3384 register_peer_exten(peer, FALSE);
3385 ast_free_ha(peer->ha);
3386 if (peer->selfdestruct)
3387 ast_atomic_fetchadd_int(&apeerobjs, -1);
3388 else if (peer->is_realtime) {
3389 ast_atomic_fetchadd_int(&rpeerobjs, -1);
3390 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
3392 ast_atomic_fetchadd_int(&speerobjs, -1);
3393 clear_realm_authentication(peer->auth);
3396 ast_dnsmgr_release(peer->dnsmgr);
3397 clear_peer_mailboxes(peer);
3399 if (peer->socket.tcptls_session) {
3400 ao2_ref(peer->socket.tcptls_session, -1);
3401 peer->socket.tcptls_session = NULL;
3404 ast_string_field_free_memory(peer);
3407 /*! \brief Update peer data in database (if used) */
3408 static void update_peer(struct sip_peer *p, int expire)
3410 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
3411 if (sip_cfg.peer_rtupdate &&
3412 (p->is_realtime || rtcachefriends)) {
3413 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
3417 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
3419 struct ast_variable *var = NULL;
3420 struct ast_flags flags = {0};
3422 const char *insecure;
3423 while ((cat = ast_category_browse(cfg, cat))) {
3424 insecure = ast_variable_retrieve(cfg, cat, "insecure");
3425 set_insecure_flags(&flags, insecure, -1);
3426 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
3427 var = ast_category_root(cfg, cat);
3434 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
3436 struct ast_variable *tmp;
3437 for (tmp = var; tmp; tmp = tmp->next) {
3438 if (!newpeername && !strcasecmp(tmp->name, "name"))
3439 newpeername = tmp->value;
3444 /*! \brief realtime_peer: Get peer from realtime storage
3445 * Checks the "sippeers" realtime family from extconfig.conf
3446 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
3447 * This returns a pointer to a peer and because we use build_peer, we can rest
3448 * assured that the refcount is bumped.
3450 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
3452 struct sip_peer *peer;
3453 struct ast_variable *var = NULL;
3454 struct ast_variable *varregs = NULL;
3455 struct ast_variable *tmp;
3456 struct ast_config *peerlist = NULL;
3457 char ipaddr[INET_ADDRSTRLEN];
3458 char portstring[6]; /*up to 5 digits plus null terminator*/
3460 unsigned short portnum;
3461 int realtimeregs = ast_check_realtime("sipregs");
3463 /* First check on peer name */
3466 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3468 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
3470 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
3472 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
3474 * If this one loaded something, then we need to ensure that the host
3475 * field matched. The only reason why we can't have this as a criteria
3476 * is because we only have the IP address and the host field might be
3477 * set as a name (and the reverse PTR might not match).
3480 for (tmp = var; tmp; tmp = tmp->next) {
3481 if (!strcasecmp(tmp->name, "host")) {
3483 struct ast_hostent ahp;
3484 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {