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
37 * \todo Better support of forking
38 * \todo VIA branch tag transaction checking
39 * \todo Transaction support
40 * \todo We need to test TCP sessions with SIP proxies and in regards
41 * to the SIP outbound specs.
42 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
43 * \todo Save TCP/TLS sessions in registry
44 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
46 * \ingroup channel_drivers
48 * \par Overview of the handling of SIP sessions
49 * The SIP channel handles several types of SIP sessions, or dialogs,
50 * not all of them being "telephone calls".
51 * - Incoming calls that will be sent to the PBX core
52 * - Outgoing calls, generated by the PBX
53 * - SIP subscriptions and notifications of states and voicemail messages
54 * - SIP registrations, both inbound and outbound
55 * - SIP peer management (peerpoke, OPTIONS)
58 * In the SIP channel, there's a list of active SIP dialogs, which includes
59 * all of these when they are active. "sip show channels" in the CLI will
60 * show most of these, excluding subscriptions which are shown by
61 * "sip show subscriptions"
63 * \par incoming packets
64 * Incoming packets are received in the monitoring thread, then handled by
65 * sipsock_read(). This function parses the packet and matches an existing
66 * dialog or starts a new SIP dialog.
68 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
69 * If it is a response to an outbound request, the packet is sent to handle_response().
70 * If it is a request, handle_incoming() sends it to one of a list of functions
71 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
72 * sipsock_read locks the ast_channel if it exists (an active call) and
73 * unlocks it after we have processed the SIP message.
75 * A new INVITE is sent to handle_request_invite(), that will end up
76 * starting a new channel in the PBX, the new channel after that executing
77 * in a separate channel thread. This is an incoming "call".
78 * When the call is answered, either by a bridged channel or the PBX itself
79 * the sip_answer() function is called.
81 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
85 * Outbound calls are set up by the PBX through the sip_request_call()
86 * function. After that, they are activated by sip_call().
89 * The PBX issues a hangup on both incoming and outgoing calls through
90 * the sip_hangup() function
94 <depend>chan_local</depend>
97 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
99 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
100 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
101 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
102 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
103 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
104 that do not support Session-Timers).
106 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
107 per-peer settings override the global settings. The following new parameters have been
108 added to the sip.conf file.
109 session-timers=["accept", "originate", "refuse"]
110 session-expires=[integer]
111 session-minse=[integer]
112 session-refresher=["uas", "uac"]
114 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
115 Asterisk. The Asterisk can be configured in one of the following three modes:
117 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
118 made by remote end-points. A remote end-point can request Asterisk to engage
119 session-timers by either sending it an INVITE request with a "Supported: timer"
120 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
121 Session-Expires: header in it. In this mode, the Asterisk server does not
122 request session-timers from remote end-points. This is the default mode.
123 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
124 end-points to activate session-timers in addition to honoring such requests
125 made by the remote end-pints. In order to get as much protection as possible
126 against hanging SIP channels due to network or end-point failures, Asterisk
127 resends periodic re-INVITEs even if a remote end-point does not support
128 the session-timers feature.
129 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
130 timers for inbound or outbound requests. If a remote end-point requests
131 session-timers in a dialog, then Asterisk ignores that request unless it's
132 noted as a requirement (Require: header), in which case the INVITE is
133 rejected with a 420 Bad Extension response.
137 #include "asterisk.h"
139 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
142 #include <sys/ioctl.h>
145 #include <sys/signal.h>
149 #include "asterisk/network.h"
150 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
152 #include "asterisk/lock.h"
153 #include "asterisk/channel.h"
154 #include "asterisk/config.h"
155 #include "asterisk/module.h"
156 #include "asterisk/pbx.h"
157 #include "asterisk/sched.h"
158 #include "asterisk/io.h"
159 #include "asterisk/rtp.h"
160 #include "asterisk/udptl.h"
161 #include "asterisk/acl.h"
162 #include "asterisk/manager.h"
163 #include "asterisk/callerid.h"
164 #include "asterisk/cli.h"
165 #include "asterisk/app.h"
166 #include "asterisk/musiconhold.h"
167 #include "asterisk/dsp.h"
168 #include "asterisk/features.h"
169 #include "asterisk/srv.h"
170 #include "asterisk/astdb.h"
171 #include "asterisk/causes.h"
172 #include "asterisk/utils.h"
173 #include "asterisk/file.h"
174 #include "asterisk/astobj.h"
176 Uncomment the define below, if you are having refcount related memory leaks.
177 With this uncommented, this module will generate a file, /tmp/refs, which contains
178 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
179 be modified to ao2_t_* calls, and include a tag describing what is happening with
180 enough detail, to make pairing up a reference count increment with its corresponding decrement.
181 The refcounter program in utils/ can be invaluable in highlighting objects that are not
182 balanced, along with the complete history for that object.
183 In normal operation, the macros defined will throw away the tags, so they do not
184 affect the speed of the program at all. They can be considered to be documentation.
186 /* #define REF_DEBUG 1 */
187 #include "asterisk/astobj2.h"
188 #include "asterisk/dnsmgr.h"
189 #include "asterisk/devicestate.h"
190 #include "asterisk/linkedlists.h"
191 #include "asterisk/stringfields.h"
192 #include "asterisk/monitor.h"
193 #include "asterisk/netsock.h"
194 #include "asterisk/localtime.h"
195 #include "asterisk/abstract_jb.h"
196 #include "asterisk/threadstorage.h"
197 #include "asterisk/translate.h"
198 #include "asterisk/ast_version.h"
199 #include "asterisk/event.h"
200 #include "asterisk/tcptls.h"
210 #define SIPBUFSIZE 512
212 #define XMIT_ERROR -2
214 /* #define VOCAL_DATA_HACK */
216 #define DEFAULT_DEFAULT_EXPIRY 120
217 #define DEFAULT_MIN_EXPIRY 60
218 #define DEFAULT_MAX_EXPIRY 3600
219 #define DEFAULT_REGISTRATION_TIMEOUT 20
220 #define DEFAULT_MAX_FORWARDS "70"
222 /* guard limit must be larger than guard secs */
223 /* guard min must be < 1000, and should be >= 250 */
224 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
225 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
227 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
228 GUARD_PCT turns out to be lower than this, it
229 will use this time instead.
230 This is in milliseconds. */
231 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
232 below EXPIRY_GUARD_LIMIT */
233 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
235 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
236 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
237 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
240 #define MAX(a,b) ((a) > (b) ? (a) : (b))
243 #define CALLERID_UNKNOWN "Unknown"
245 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
246 #define DEFAULT_QUALIFYFREQ 60 * 1000 /*!< Qualification: How often to check for the host to be up */
247 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
249 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
250 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
251 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
252 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1
253 \todo Use known T1 for timeout (peerpoke)
255 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
256 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
258 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
259 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
260 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
261 #define SIP_MIN_PACKET 1024 /*!< Initialize size of memory to allocate for packets */
263 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
265 #define DEFAULT_MAX_SE 1800 /*!< Session-Timer Default Session-Expires period (RFC 4028) */
266 #define DEFAULT_MIN_SE 90 /*!< Session-Timer Default Min-SE period (RFC 4028) */
268 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
270 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
271 static struct ast_jb_conf default_jbconf =
275 .resync_threshold = -1,
278 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
280 static const char config[] = "sip.conf"; /*!< Main configuration file */
281 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
286 /*! \brief Authorization scheme for call transfers
287 \note Not a bitfield flag, since there are plans for other modes,
288 like "only allow transfers for authenticated devices" */
290 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
291 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
295 /*! \brief The result of a lot of functions */
297 AST_SUCCESS = 0, /*! FALSE means success, funny enough */
301 /*! \brief States for the INVITE transaction, not the dialog
302 \note this is for the INVITE that sets up the dialog
305 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
306 INV_CALLING = 1, /*!< Invite sent, no answer */
307 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
308 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
309 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
310 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
311 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
312 The only way out of this is a BYE from one side */
313 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
316 /*! \brief Readable descriptions of device states.
317 \note Should be aligned to above table as index */
318 static const struct invstate2stringtable {
319 const enum invitestates state;
321 } invitestate2string[] = {
323 {INV_CALLING, "Calling (Trying)"},
324 {INV_PROCEEDING, "Proceeding "},
325 {INV_EARLY_MEDIA, "Early media"},
326 {INV_COMPLETED, "Completed (done)"},
327 {INV_CONFIRMED, "Confirmed (up)"},
328 {INV_TERMINATED, "Done"},
329 {INV_CANCELLED, "Cancelled"}
332 /*! \brief When sending a SIP message, we can send with a few options, depending on
333 type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
334 where the original response would be sent RELIABLE in an INVITE transaction */
336 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
337 If it fails, it's critical and will cause a teardown of the session */
338 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
339 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
342 enum parse_register_result {
343 PARSE_REGISTER_FAILED,
344 PARSE_REGISTER_UPDATE,
345 PARSE_REGISTER_QUERY,
348 /*! \brief Type of subscription, based on the packages we do support */
349 enum subscriptiontype {
358 /*! \brief Subscription types that we support. We support
359 - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
360 - SIMPLE presence used for device status
361 - Voicemail notification subscriptions
363 static const struct cfsubscription_types {
364 enum subscriptiontype type;
365 const char * const event;
366 const char * const mediatype;
367 const char * const text;
368 } subscription_types[] = {
369 { NONE, "-", "unknown", "unknown" },
370 /* RFC 4235: SIP Dialog event package */
371 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
372 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
373 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
374 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
375 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
379 /*! \brief Authentication types - proxy or www authentication
380 \note Endpoints, like Asterisk, should always use WWW authentication to
381 allow multiple authentications in the same call - to the proxy and
389 /*! \brief Authentication result from check_auth* functions */
390 enum check_auth_result {
391 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
392 /* XXX maybe this is the same as AUTH_NOT_FOUND */
395 AUTH_CHALLENGE_SENT = 1,
396 AUTH_SECRET_FAILED = -1,
397 AUTH_USERNAME_MISMATCH = -2,
398 AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
400 AUTH_UNKNOWN_DOMAIN = -5,
401 AUTH_PEER_NOT_DYNAMIC = -6,
402 AUTH_ACL_FAILED = -7,
403 AUTH_BAD_TRANSPORT = -8,
406 /*! \brief States for outbound registrations (with register= lines in sip.conf */
407 enum sipregistrystate {
408 REG_STATE_UNREGISTERED = 0, /*!< We are not registred
409 * \note Initial state. We should have a timeout scheduled for the initial
410 * (or next) registration transmission, calling sip_reregister
413 REG_STATE_REGSENT, /*!< Registration request sent
414 * \note sent initial request, waiting for an ack or a timeout to
415 * retransmit the initial request.
418 REG_STATE_AUTHSENT, /*!< We have tried to authenticate
419 * \note entered after transmit_register with auth info,
420 * waiting for an ack.
423 REG_STATE_REGISTERED, /*!< Registered and done */
425 REG_STATE_REJECTED, /*!< Registration rejected *
426 * \note only used when the remote party has an expire larger than
427 * our max-expire. This is a final state from which we do not
428 * recover (not sure how correctly).
431 REG_STATE_TIMEOUT, /*!< Registration timed out *
432 * \note XXX unused */
434 REG_STATE_NOAUTH, /*!< We have no accepted credentials
435 * \note fatal - no chance to proceed */
437 REG_STATE_FAILED, /*!< Registration failed after several tries
438 * \note fatal - no chance to proceed */
441 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
443 SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */
444 SESSION_TIMER_MODE_ACCEPT, /*!< Honor inbound Session-Timer requests */
445 SESSION_TIMER_MODE_ORIGINATE, /*!< Originate outbound and honor inbound requests */
446 SESSION_TIMER_MODE_REFUSE /*!< Ignore inbound Session-Timers requests */
449 /*! \brief The entity playing the refresher role for Session-Timers */
451 SESSION_TIMER_REFRESHER_AUTO, /*!< Negotiated */
452 SESSION_TIMER_REFRESHER_UAC, /*!< Session is refreshed by the UAC */
453 SESSION_TIMER_REFRESHER_UAS /*!< Session is refreshed by the UAS */
456 /*! \brief Define some implemented SIP transports
457 \note Asterisk does not support SCTP or UDP/DTLS
460 SIP_TRANSPORT_UDP = 1, /*!< Unreliable transport for SIP, needs retransmissions */
461 SIP_TRANSPORT_TCP = 1 << 1, /*!< Reliable, but unsecure */
462 SIP_TRANSPORT_TLS = 1 << 2, /*!< TCP/TLS - reliable and secure transport for signalling */
465 /*! \brief definition of a sip proxy server
467 * For outbound proxies, this is allocated in the SIP peer dynamically or
468 * statically as the global_outboundproxy. The pointer in a SIP message is just
469 * a pointer and should *not* be de-allocated.
472 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
473 struct sockaddr_in ip; /*!< Currently used IP address and port */
474 time_t last_dnsupdate; /*!< When this was resolved */
475 enum sip_transport transport;
476 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
477 /* Room for a SRV record chain based on the name */
480 /*! \brief argument for the 'show channels|subscriptions' callback. */
481 struct __show_chan_arg {
484 int numchans; /* return value */
488 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
489 enum can_create_dialog {
490 CAN_NOT_CREATE_DIALOG,
492 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
495 /*! \brief SIP Request methods known by Asterisk
497 \note Do _NOT_ make any changes to this enum, or the array following it;
498 if you think you are doing the right thing, you are probably
499 not doing the right thing. If you think there are changes
500 needed, get someone else to review them first _before_
501 submitting a patch. If these two lists do not match properly
502 bad things will happen.
506 SIP_UNKNOWN, /*!< Unknown response */
507 SIP_RESPONSE, /*!< Not request, response to outbound request */
508 SIP_REGISTER, /*!< Registration to the mothership, tell us where you are located */
509 SIP_OPTIONS, /*!< Check capabilities of a device, used for "ping" too */
510 SIP_NOTIFY, /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
511 SIP_INVITE, /*!< Set up a session */
512 SIP_ACK, /*!< End of a three-way handshake started with INVITE. */
513 SIP_PRACK, /*!< Reliable pre-call signalling. Not supported in Asterisk. */
514 SIP_BYE, /*!< End of a session */
515 SIP_REFER, /*!< Refer to another URI (transfer) */
516 SIP_SUBSCRIBE, /*!< Subscribe for updates (voicemail, session status, device status, presence) */
517 SIP_MESSAGE, /*!< Text messaging */
518 SIP_UPDATE, /*!< Update a dialog. We can send UPDATE; but not accept it */
519 SIP_INFO, /*!< Information updates during a session */
520 SIP_CANCEL, /*!< Cancel an INVITE */
521 SIP_PUBLISH, /*!< Not supported in Asterisk */
522 SIP_PING, /*!< Not supported at all, no standard but still implemented out there */
525 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
526 structure and then route the messages according to the type.
528 \note Note that sip_methods[i].id == i must hold or the code breaks */
529 static const struct cfsip_methods {
531 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
533 enum can_create_dialog can_create;
535 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
536 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
537 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
538 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
539 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
540 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
541 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
542 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
543 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
544 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
545 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
546 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
547 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
548 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
549 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
550 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
551 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
554 /*! Define SIP option tags, used in Require: and Supported: headers
555 We need to be aware of these properties in the phones to use
556 the replace: header. We should not do that without knowing
557 that the other end supports it...
558 This is nothing we can configure, we learn by the dialog
559 Supported: header on the REGISTER (peer) or the INVITE
561 We are not using many of these today, but will in the future.
562 This is documented in RFC 3261
565 #define NOT_SUPPORTED 0
568 #define SIP_OPT_REPLACES (1 << 0)
569 #define SIP_OPT_100REL (1 << 1)
570 #define SIP_OPT_TIMER (1 << 2)
571 #define SIP_OPT_EARLY_SESSION (1 << 3)
572 #define SIP_OPT_JOIN (1 << 4)
573 #define SIP_OPT_PATH (1 << 5)
574 #define SIP_OPT_PREF (1 << 6)
575 #define SIP_OPT_PRECONDITION (1 << 7)
576 #define SIP_OPT_PRIVACY (1 << 8)
577 #define SIP_OPT_SDP_ANAT (1 << 9)
578 #define SIP_OPT_SEC_AGREE (1 << 10)
579 #define SIP_OPT_EVENTLIST (1 << 11)
580 #define SIP_OPT_GRUU (1 << 12)
581 #define SIP_OPT_TARGET_DIALOG (1 << 13)
582 #define SIP_OPT_NOREFERSUB (1 << 14)
583 #define SIP_OPT_HISTINFO (1 << 15)
584 #define SIP_OPT_RESPRIORITY (1 << 16)
585 #define SIP_OPT_FROMCHANGE (1 << 17)
586 #define SIP_OPT_RECLISTINV (1 << 18)
587 #define SIP_OPT_RECLISTSUB (1 << 19)
588 #define SIP_OPT_UNKNOWN (1 << 20)
591 /*! \brief List of well-known SIP options. If we get this in a require,
592 we should check the list and answer accordingly. */
593 static const struct cfsip_options {
594 int id; /*!< Bitmap ID */
595 int supported; /*!< Supported by Asterisk ? */
596 char * const text; /*!< Text id, as in standard */
597 } sip_options[] = { /* XXX used in 3 places */
598 /* RFC3262: PRACK 100% reliability */
599 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
600 /* RFC3959: SIP Early session support */
601 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
602 /* SIMPLE events: RFC4662 */
603 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
604 /* RFC 4916- Connected line ID updates */
605 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
606 /* GRUU: Globally Routable User Agent URI's */
607 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
608 /* RFC4244 History info */
609 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
610 /* RFC3911: SIP Join header support */
611 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
612 /* Disable the REFER subscription, RFC 4488 */
613 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
614 /* RFC3327: Path support */
615 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
616 /* RFC3840: Callee preferences */
617 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
618 /* RFC3312: Precondition support */
619 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
620 /* RFC3323: Privacy with proxies*/
621 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
622 /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
623 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
624 /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
625 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
626 /* RFC3891: Replaces: header for transfer */
627 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
628 /* One version of Polycom firmware has the wrong label */
629 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
630 /* RFC4412 Resource priorities */
631 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
632 /* RFC3329: Security agreement mechanism */
633 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
634 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
635 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
636 /* RFC4028: SIP Session-Timers */
637 { SIP_OPT_TIMER, SUPPORTED, "timer" },
638 /* RFC4538: Target-dialog */
639 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
643 /*! \brief SIP Methods we support
644 \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
645 allowsubscribe and allowrefer on in sip.conf.
647 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
649 /*! \brief SIP Extensions we support
650 \note This should be generated based on the previous array
651 in combination with settings.
652 \todo We should not have "timer" if it's disabled in the configuration file.
654 #define SUPPORTED_EXTENSIONS "replaces, timer"
656 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
657 #define STANDARD_SIP_PORT 5060
658 /*! \brief Standard SIP TLS port for sips: from RFC 3261. DO NOT CHANGE THIS */
659 #define STANDARD_TLS_PORT 5061
661 /*! \note in many SIP headers, absence of a port number implies port 5060,
662 * and this is why we cannot change the above constant.
663 * There is a limited number of places in asterisk where we could,
664 * in principle, use a different "default" port number, but
665 * we do not support this feature at the moment.
666 * You can run Asterisk with SIP on a different port with a configuration
667 * option. If you change this value, the signalling will be incorrect.
670 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
672 These are default values in the source. There are other recommended values in the
673 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
674 yet encouraging new behaviour on new installations
677 #define DEFAULT_CONTEXT "default"
678 #define DEFAULT_MOHINTERPRET "default"
679 #define DEFAULT_MOHSUGGEST ""
680 #define DEFAULT_VMEXTEN "asterisk"
681 #define DEFAULT_CALLERID "asterisk"
682 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
683 #define DEFAULT_ALLOWGUEST TRUE
684 #define DEFAULT_CALLCOUNTER FALSE
685 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
686 #define DEFAULT_COMPACTHEADERS FALSE
687 #define DEFAULT_TOS_SIP 0 /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
688 #define DEFAULT_TOS_AUDIO 0 /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
689 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
690 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
691 #define DEFAULT_COS_SIP 4 /*!< Level 2 class of service for SIP signalling */
692 #define DEFAULT_COS_AUDIO 5 /*!< Level 2 class of service for audio media */
693 #define DEFAULT_COS_VIDEO 6 /*!< Level 2 class of service for video media */
694 #define DEFAULT_COS_TEXT 5 /*!< Level 2 class of service for text media (T.140) */
695 #define DEFAULT_ALLOW_EXT_DOM TRUE /*!< Allow external domains */
696 #define DEFAULT_REALM "asterisk" /*!< Realm for HTTP digest authentication */
697 #define DEFAULT_NOTIFYRINGING TRUE
698 #define DEFAULT_PEDANTIC FALSE
699 #define DEFAULT_AUTOCREATEPEER FALSE
700 #define DEFAULT_QUALIFY FALSE
701 #define DEFAULT_REGEXTENONQUALIFY FALSE
702 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
703 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
704 #ifndef DEFAULT_USERAGENT
705 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
706 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
707 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
711 /*! \name DefaultSettings
712 Default setttings are used as a channel setting and as a default when
716 static char default_context[AST_MAX_CONTEXT];
717 static char default_subscribecontext[AST_MAX_CONTEXT];
718 static char default_language[MAX_LANGUAGE];
719 static char default_callerid[AST_MAX_EXTENSION];
720 static char default_fromdomain[AST_MAX_EXTENSION];
721 static char default_notifymime[AST_MAX_EXTENSION];
722 static int default_qualify; /*!< Default Qualify= setting */
723 static char default_vmexten[AST_MAX_EXTENSION];
724 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
725 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
726 * a bridged channel on hold */
727 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
728 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
729 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
731 /*! \brief a place to store all global settings for the sip channel driver */
732 struct sip_settings {
733 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
734 int rtsave_sysname; /*!< G: Save system name at registration? */
735 int ignore_regexpire; /*!< G: Ignore expiration of peer */
738 static struct sip_settings sip_cfg;
741 /*! \name GlobalSettings
742 Global settings apply to the channel (often settings you can change in the general section
746 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
747 static int global_rtautoclear; /*!< Realtime ?? */
748 static int global_notifyringing; /*!< Send notifications on ringing */
749 static int global_notifyhold; /*!< Send notifications on hold */
750 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
751 static int global_srvlookup; /*!< SRV Lookup on or off. Default is on */
752 static int pedanticsipchecking; /*!< Extra checking ? Default off */
753 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
754 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
755 static int global_relaxdtmf; /*!< Relax DTMF */
756 static int global_rtptimeout; /*!< Time out call if no RTP */
757 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
758 static int global_rtpkeepalive; /*!< Send RTP keepalives */
759 static int global_reg_timeout;
760 static int global_regattempts_max; /*!< Registration attempts before giving up */
761 static int global_allowguest; /*!< allow unauthenticated peers to connect? */
762 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
763 call-limit to 999. When we remove the call-limit from the code, we can make it
764 with just a boolean flag in the device structure */
765 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
766 the global setting is in globals_flags[1] */
767 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
768 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
769 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
770 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
771 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
772 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
773 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
774 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
775 static int compactheaders; /*!< send compact sip headers */
776 static int recordhistory; /*!< Record SIP history. Off by default */
777 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
778 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
779 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
780 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
781 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
782 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
783 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
784 static int global_callevents; /*!< Whether we send manager events or not */
785 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
786 static int global_t1; /*!< T1 time */
787 static int global_t1min; /*!< T1 roundtrip time minimum */
788 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
789 static int global_regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
790 static int global_autoframing; /*!< Turn autoframing on or off. */
791 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
792 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
793 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
794 static int global_qualifyfreq; /*!< Qualify frequency */
797 /*! \brief Codecs that we support by default: */
798 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
800 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
801 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
802 static int global_min_se; /*!< Lowest threshold for session refresh interval */
803 static int global_max_se; /*!< Highest threshold for session refresh interval */
807 /*! \name Object counters @{
808 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
809 * should be used to modify these values. */
810 static int speerobjs = 0; /*!< Static peers */
811 static int rpeerobjs = 0; /*!< Realtime peers */
812 static int apeerobjs = 0; /*!< Autocreated peer objects */
813 static int regobjs = 0; /*!< Registry objects */
816 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
817 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
820 AST_MUTEX_DEFINE_STATIC(netlock);
822 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
823 when it's doing something critical. */
824 AST_MUTEX_DEFINE_STATIC(monlock);
826 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
828 /*! \brief This is the thread for the monitor which checks for input on the channels
829 which are not currently in use. */
830 static pthread_t monitor_thread = AST_PTHREADT_NULL;
832 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
833 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
835 static struct sched_context *sched; /*!< The scheduling context */
836 static struct io_context *io; /*!< The IO context */
837 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
839 #define DEC_CALL_LIMIT 0
840 #define INC_CALL_LIMIT 1
841 #define DEC_CALL_RINGING 2
842 #define INC_CALL_RINGING 3
844 /*! \brief The SIP socket definition */
846 enum sip_transport type; /*!< UDP, TCP or TLS */
847 int fd; /*!< Filed descriptor, the actual socket */
849 struct ast_tcptls_session_instance *ser; /* If tcp or tls, a socket manager */
852 /*! \brief sip_request: The data grabbed from the UDP socket
855 * Incoming messages: we first store the data from the socket in data[],
856 * adding a trailing \0 to make string parsing routines happy.
857 * Then call parse_request() and req.method = find_sip_method();
858 * to initialize the other fields. The \r\n at the end of each line is
859 * replaced by \0, so that data[] is not a conforming SIP message anymore.
860 * After this processing, rlPart1 is set to non-NULL to remember
861 * that we can run get_header() on this kind of packet.
863 * parse_request() splits the first line as follows:
864 * Requests have in the first line method uri SIP/2.0
865 * rlPart1 = method; rlPart2 = uri;
866 * Responses have in the first line SIP/2.0 NNN description
867 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
869 * For outgoing packets, we initialize the fields with init_req() or init_resp()
870 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
871 * and then fill the rest with add_header() and add_line().
872 * The \r\n at the end of the line are still there, so the get_header()
873 * and similar functions don't work on these packets.
877 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
878 char *rlPart2; /*!< The Request URI or Response Status */
879 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
880 int headers; /*!< # of SIP Headers */
881 int method; /*!< Method of this request */
882 int lines; /*!< Body Content */
883 unsigned int sdp_start; /*!< the line number where the SDP begins */
884 unsigned int sdp_end; /*!< the line number where the SDP ends */
885 char debug; /*!< print extra debugging if non zero */
886 char has_to_tag; /*!< non-zero if packet has To: tag */
887 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
888 char *header[SIP_MAX_HEADERS];
889 char *line[SIP_MAX_LINES];
890 struct ast_str *data;
891 /* XXX Do we need to unref socket.ser when the request goes away? */
892 struct sip_socket socket; /*!< The socket used for this request */
895 /*! \brief structure used in transfers */
897 struct ast_channel *chan1; /*!< First channel involved */
898 struct ast_channel *chan2; /*!< Second channel involved */
899 struct sip_request req; /*!< Request that caused the transfer (REFER) */
900 int seqno; /*!< Sequence number */
905 /*! \brief Parameters to the transmit_invite function */
906 struct sip_invite_param {
907 int addsipheaders; /*!< Add extra SIP headers */
908 const char *uri_options; /*!< URI options to add to the URI */
909 const char *vxml_url; /*!< VXML url for Cisco phones */
910 char *auth; /*!< Authentication */
911 char *authheader; /*!< Auth header */
912 enum sip_auth_type auth_type; /*!< Authentication type */
913 const char *replaces; /*!< Replaces header for call transfers */
914 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
917 /*! \brief Structure to save routing information for a SIP session */
919 struct sip_route *next;
923 /*! \brief Modes for SIP domain handling in the PBX */
925 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
926 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
929 /*! \brief Domain data structure.
930 \note In the future, we will connect this to a configuration tree specific
934 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
935 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
936 enum domain_mode mode; /*!< How did we find this domain? */
937 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
940 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
943 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
945 AST_LIST_ENTRY(sip_history) list;
946 char event[0]; /* actually more, depending on needs */
949 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
951 /*! \brief sip_auth: Credentials for authentication to other SIP services */
953 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
954 char username[256]; /*!< Username */
955 char secret[256]; /*!< Secret */
956 char md5secret[256]; /*!< MD5Secret */
957 struct sip_auth *next; /*!< Next auth structure in list */
961 Various flags for the flags field in the pvt structure
962 Trying to sort these up (one or more of the following):
966 When flags are used by multiple structures, it is important that
967 they have a common layout so it is easy to copy them.
970 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
971 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
972 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
973 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
974 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
975 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
976 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
977 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
978 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
979 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10) /*!< D: Do not hangup at first ast_hangup */
981 #define SIP_PROMISCREDIR (1 << 11) /*!< DP: Promiscuous redirection */
982 #define SIP_TRUSTRPID (1 << 12) /*!< DP: Trust RPID headers? */
983 #define SIP_USEREQPHONE (1 << 13) /*!< DP: Add user=phone to numeric URI. Default off */
984 #define SIP_USECLIENTCODE (1 << 14) /*!< DP: Trust X-ClientCode info message */
986 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
987 #define SIP_DTMF (7 << 15) /*!< DP: DTMF Support: five settings, uses three bits */
988 #define SIP_DTMF_RFC2833 (0 << 15) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
989 #define SIP_DTMF_INBAND (1 << 15) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
990 #define SIP_DTMF_INFO (2 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" */
991 #define SIP_DTMF_AUTO (3 << 15) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
992 #define SIP_DTMF_SHORTINFO (4 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
994 /* NAT settings - see nat2str() */
995 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
996 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
997 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
998 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
999 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
1001 /* re-INVITE related settings */
1002 #define SIP_REINVITE (7 << 20) /*!< DP: four settings, uses three bits */
1003 #define SIP_REINVITE_NONE (0 << 20) /*!< DP: no reinvite allowed */
1004 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
1005 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
1006 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
1008 /* "insecure" settings - see insecure2str() */
1009 #define SIP_INSECURE (3 << 23) /*!< DP: three settings, uses two bits */
1010 #define SIP_INSECURE_NONE (0 << 23) /*!< DP: secure mode */
1011 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
1012 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
1014 /* Sending PROGRESS in-band settings */
1015 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
1016 #define SIP_PROG_INBAND_NEVER (0 << 25)
1017 #define SIP_PROG_INBAND_NO (1 << 25)
1018 #define SIP_PROG_INBAND_YES (2 << 25)
1020 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
1021 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
1023 /*! \brief Flags to copy from peer/user to dialog */
1024 #define SIP_FLAGS_TO_COPY \
1025 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
1026 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
1027 SIP_USEREQPHONE | SIP_INSECURE)
1031 a second page of flags (for flags[1] */
1033 /* realtime flags */
1034 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
1035 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
1036 /* Space for addition of other realtime flags in the future */
1037 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
1039 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14) /*!< DP: Video supported if offered? */
1040 #define SIP_PAGE2_TEXTSUPPORT (1 << 15) /*!< GDP: Global text enable */
1041 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
1042 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
1043 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
1045 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
1046 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
1047 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1048 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1050 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
1051 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
1052 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
1053 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
1055 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
1056 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
1057 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
1058 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30) /*!< DP: Use source IP of RTP as destination if NAT is enabled */
1059 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31) /*!< DP: Always set up video, even if endpoints don't support it */
1061 #define SIP_PAGE2_FLAGS_TO_COPY \
1062 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
1063 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
1064 SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_UDPTL_DESTINATION | \
1065 SIP_PAGE2_VIDEOSUPPORT_ALWAYS)
1069 /*! \name SIPflagsT38
1070 T.38 set of flags */
1073 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
1074 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
1075 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
1076 /* Rate management */
1077 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
1078 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
1079 /* UDP Error correction */
1080 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
1081 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
1082 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
1083 /* T38 Spec version */
1084 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
1085 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
1086 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
1087 /* Maximum Fax Rate */
1088 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
1089 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
1090 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
1091 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
1092 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
1093 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
1095 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
1096 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
1099 /*! \brief debugging state
1100 * We store separately the debugging requests from the config file
1101 * and requests from the CLI. Debugging is enabled if either is set
1102 * (which means that if sipdebug is set in the config file, we can
1103 * only turn it off by reloading the config).
1107 sip_debug_config = 1,
1108 sip_debug_console = 2,
1111 static enum sip_debug_e sipdebug;
1113 /*! \brief extra debugging for 'text' related events.
1114 * At the moment this is set together with sip_debug_console.
1115 * \note It should either go away or be implemented properly.
1117 static int sipdebug_text;
1119 /*! \brief T38 States for a call */
1121 T38_DISABLED = 0, /*!< Not enabled */
1122 T38_LOCAL_DIRECT, /*!< Offered from local */
1123 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
1124 T38_PEER_DIRECT, /*!< Offered from peer */
1125 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
1126 T38_ENABLED /*!< Negotiated (enabled) */
1129 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
1130 struct t38properties {
1131 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
1132 int capability; /*!< Our T38 capability */
1133 int peercapability; /*!< Peers T38 capability */
1134 int jointcapability; /*!< Supported T38 capability at both ends */
1135 enum t38state state; /*!< T.38 state */
1138 /*! \brief Parameters to know status of transfer */
1140 REFER_IDLE, /*!< No REFER is in progress */
1141 REFER_SENT, /*!< Sent REFER to transferee */
1142 REFER_RECEIVED, /*!< Received REFER from transferrer */
1143 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
1144 REFER_ACCEPTED, /*!< Accepted by transferee */
1145 REFER_RINGING, /*!< Target Ringing */
1146 REFER_200OK, /*!< Answered by transfer target */
1147 REFER_FAILED, /*!< REFER declined - go on */
1148 REFER_NOAUTH /*!< We had no auth for REFER */
1151 /*! \brief generic struct to map between strings and integers.
1152 * Fill it with x-s pairs, terminate with an entry with s = NULL;
1153 * Then you can call map_x_s(...) to map an integer to a string,
1154 * and map_s_x() for the string -> integer mapping.
1161 static const struct _map_x_s referstatusstrings[] = {
1162 { REFER_IDLE, "<none>" },
1163 { REFER_SENT, "Request sent" },
1164 { REFER_RECEIVED, "Request received" },
1165 { REFER_CONFIRMED, "Confirmed" },
1166 { REFER_ACCEPTED, "Accepted" },
1167 { REFER_RINGING, "Target ringing" },
1168 { REFER_200OK, "Done" },
1169 { REFER_FAILED, "Failed" },
1170 { REFER_NOAUTH, "Failed - auth failure" },
1171 { -1, NULL} /* terminator */
1174 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1175 \note OEJ: Should be moved to string fields */
1177 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
1178 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
1179 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
1180 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
1181 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1182 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1183 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
1184 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
1185 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
1186 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
1187 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
1188 * dialog owned by someone else, so we should not destroy
1189 * it when the sip_refer object goes.
1191 int attendedtransfer; /*!< Attended or blind transfer? */
1192 int localtransfer; /*!< Transfer to local domain? */
1193 enum referstatus status; /*!< REFER status */
1197 /*! \brief Structure that encapsulates all attributes related to running
1198 * SIP Session-Timers feature on a per dialog basis.
1201 int st_active; /*!< Session-Timers on/off */
1202 int st_interval; /*!< Session-Timers negotiated session refresh interval */
1203 int st_schedid; /*!< Session-Timers ast_sched scheduler id */
1204 enum st_refresher st_ref; /*!< Session-Timers session refresher */
1205 int st_expirys; /*!< Session-Timers number of expirys */
1206 int st_active_peer_ua; /*!< Session-Timers on/off in peer UA */
1207 int st_cached_min_se; /*!< Session-Timers cached Min-SE */
1208 int st_cached_max_se; /*!< Session-Timers cached Session-Expires */
1209 enum st_mode st_cached_mode; /*!< Session-Timers cached M.O. */
1210 enum st_refresher st_cached_ref; /*!< Session-Timers cached refresher */
1214 /*! \brief Structure that encapsulates all attributes related to configuration
1215 * of SIP Session-Timers feature on a per user/peer basis.
1218 enum st_mode st_mode_oper; /*!< Mode of operation for Session-Timers */
1219 enum st_refresher st_ref; /*!< Session-Timer refresher */
1220 int st_min_se; /*!< Lowest threshold for session refresh interval */
1221 int st_max_se; /*!< Highest threshold for session refresh interval */
1227 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
1228 * Created and initialized by sip_alloc(), the descriptor goes into the list of
1229 * descriptors (dialoglist).
1232 struct sip_pvt *next; /*!< Next dialog in chain */
1233 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
1234 int method; /*!< SIP method that opened this dialog */
1235 AST_DECLARE_STRING_FIELDS(
1236 AST_STRING_FIELD(callid); /*!< Global CallID */
1237 AST_STRING_FIELD(randdata); /*!< Random data */
1238 AST_STRING_FIELD(accountcode); /*!< Account code */
1239 AST_STRING_FIELD(realm); /*!< Authorization realm */
1240 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1241 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1242 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1243 AST_STRING_FIELD(domain); /*!< Authorization domain */
1244 AST_STRING_FIELD(from); /*!< The From: header */
1245 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1246 AST_STRING_FIELD(exten); /*!< Extension where to start */
1247 AST_STRING_FIELD(context); /*!< Context for this call */
1248 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1249 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1250 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1251 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1252 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1253 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1254 AST_STRING_FIELD(todnid); /*!< DNID of this call (overrides host) */
1255 AST_STRING_FIELD(language); /*!< Default language for this call */
1256 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1257 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1258 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1259 AST_STRING_FIELD(redircause); /*!< Referring cause */
1260 AST_STRING_FIELD(theirtag); /*!< Their tag */
1261 AST_STRING_FIELD(username); /*!< [user] name */
1262 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1263 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1264 AST_STRING_FIELD(uri); /*!< Original requested URI */
1265 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1266 AST_STRING_FIELD(peersecret); /*!< Password */
1267 AST_STRING_FIELD(peermd5secret);
1268 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1269 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1270 AST_STRING_FIELD(via); /*!< Via: header */
1271 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1272 /* we only store the part in <brackets> in this field. */
1273 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1274 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1275 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1276 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1277 AST_STRING_FIELD(parkinglot); /*!< Parkinglot */
1279 struct sip_socket socket; /*!< The socket used for this dialog */
1280 unsigned int ocseq; /*!< Current outgoing seqno */
1281 unsigned int icseq; /*!< Current incoming seqno */
1282 ast_group_t callgroup; /*!< Call group */
1283 ast_group_t pickupgroup; /*!< Pickup group */
1284 int lastinvite; /*!< Last Cseq of invite */
1285 int lastnoninvite; /*!< Last Cseq of non-invite */
1286 struct ast_flags flags[2]; /*!< SIP_ flags */
1288 /* boolean or small integers that don't belong in flags */
1289 char do_history; /*!< Set if we want to record history */
1290 char alreadygone; /*!< already destroyed by our peer */
1291 char needdestroy; /*!< need to be destroyed by the monitor thread */
1292 char outgoing_call; /*!< this is an outgoing call */
1293 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1294 char novideo; /*!< Didn't get video in invite, don't offer */
1295 char notext; /*!< Text not supported (?) */
1297 int timer_t1; /*!< SIP timer T1, ms rtt */
1298 int timer_b; /*!< SIP timer B, ms */
1299 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1300 unsigned int reqsipoptions; /*!< Required SIP options on the other end */
1301 struct ast_codec_pref prefs; /*!< codec prefs */
1302 int capability; /*!< Special capability (codec) */
1303 int jointcapability; /*!< Supported capability at both ends (codecs) */
1304 int peercapability; /*!< Supported peer capability */
1305 int prefcodec; /*!< Preferred codec (outbound only) */
1306 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1307 int jointnoncodeccapability; /*!< Joint Non codec capability */
1308 int redircodecs; /*!< Redirect codecs */
1309 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1310 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
1311 struct t38properties t38; /*!< T38 settings */
1312 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1313 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1314 int callingpres; /*!< Calling presentation */
1315 int authtries; /*!< Times we've tried to authenticate */
1316 int expiry; /*!< How long we take to expire */
1317 long branch; /*!< The branch identifier of this session */
1318 char tag[11]; /*!< Our tag for this session */
1319 int sessionid; /*!< SDP Session ID */
1320 int sessionversion; /*!< SDP Session Version */
1321 int sessionversion_remote; /*!< Remote UA's SDP Session Version */
1322 int session_modify; /*!< Session modification request true/false */
1323 struct sockaddr_in sa; /*!< Our peer */
1324 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1325 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1326 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1327 time_t lastrtprx; /*!< Last RTP received */
1328 time_t lastrtptx; /*!< Last RTP sent */
1329 int rtptimeout; /*!< RTP timeout time */
1330 struct sockaddr_in recv; /*!< Received as */
1331 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1332 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1333 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1334 int route_persistant; /*!< Is this the "real" route? */
1335 struct ast_variable *notify_headers; /*!< Custom notify type */
1336 struct sip_auth *peerauth; /*!< Realm authentication */
1337 int noncecount; /*!< Nonce-count */
1338 char lastmsg[256]; /*!< Last Message sent/received */
1339 int amaflags; /*!< AMA Flags */
1340 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1341 struct sip_request initreq; /*!< Latest request that opened a new transaction
1343 NOT the request that opened the dialog
1346 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1347 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1348 int autokillid; /*!< Auto-kill ID (scheduler) */
1349 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1350 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1351 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1352 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1353 int laststate; /*!< SUBSCRIBE: Last known extension state */
1354 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1356 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1358 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1359 Used in peerpoke, mwi subscriptions */
1360 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1361 struct ast_rtp *rtp; /*!< RTP Session */
1362 struct ast_rtp *vrtp; /*!< Video RTP session */
1363 struct ast_rtp *trtp; /*!< Text RTP session */
1364 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1365 struct sip_history_head *history; /*!< History of this SIP dialog */
1366 size_t history_entries; /*!< Number of entires in the history */
1367 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1368 struct sip_invite_param *options; /*!< Options for INVITE */
1369 int autoframing; /*!< The number of Asters we group in a Pyroflax
1370 before strolling to the Grokyzpå
1371 (A bit unsure of this, please correct if
1373 struct sip_st_dlg *stimer; /*!< SIP Session-Timers */
1378 /*! Max entires in the history list for a sip_pvt */
1379 #define MAX_HISTORY_ENTRIES 50
1382 * Here we implement the container for dialogs (sip_pvt), defining
1383 * generic wrapper functions to ease the transition from the current
1384 * implementation (a single linked list) to a different container.
1385 * In addition to a reference to the container, we need functions to lock/unlock
1386 * the container and individual items, and functions to add/remove
1387 * references to the individual items.
1389 struct ao2_container *dialogs;
1391 #define sip_pvt_lock(x) ao2_lock(x)
1392 #define sip_pvt_trylock(x) ao2_trylock(x)
1393 #define sip_pvt_unlock(x) ao2_unlock(x)
1396 * when we create or delete references, make sure to use these
1397 * functions so we keep track of the refcounts.
1398 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1401 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1402 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1404 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1407 _ao2_ref_debug(p, 1, tag, file, line, func);
1409 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1413 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1416 _ao2_ref_debug(p, -1, tag, file, line, func);
1420 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
1425 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1429 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
1437 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1438 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1439 * Each packet holds a reference to the parent struct sip_pvt.
1440 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1441 * require retransmissions.
1444 struct sip_pkt *next; /*!< Next packet in linked list */
1445 int retrans; /*!< Retransmission number */
1446 int method; /*!< SIP method for this packet */
1447 int seqno; /*!< Sequence number */
1448 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1449 char is_fatal; /*!< non-zero if there is a fatal error */
1450 struct sip_pvt *owner; /*!< Owner AST call */
1451 int retransid; /*!< Retransmission ID */
1452 int timer_a; /*!< SIP timer A, retransmission timer */
1453 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1454 int packetlen; /*!< Length of packet */
1455 struct ast_str *data;
1459 * \brief A peer's mailbox
1461 * We could use STRINGFIELDS here, but for only two strings, it seems like
1462 * too much effort ...
1464 struct sip_mailbox {
1467 /*! Associated MWI subscription */
1468 struct ast_event_sub *event_sub;
1469 AST_LIST_ENTRY(sip_mailbox) entry;
1472 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1473 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1475 char name[80]; /*!< peer->name is the unique name of this object */
1476 struct sip_socket socket; /*!< Socket used for this peer */
1477 unsigned int transports:3; /*!< Transports (enum sip_transport) that are acceptable for this peer */
1478 char secret[80]; /*!< Password */
1479 char md5secret[80]; /*!< Password in MD5 */
1480 struct sip_auth *auth; /*!< Realm authentication list */
1481 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1482 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1483 char username[80]; /*!< Temporary username until registration */
1484 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1485 int amaflags; /*!< AMA Flags (for billing) */
1486 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1487 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1488 char fromuser[80]; /*!< From: user when calling this peer */
1489 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1490 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1491 char cid_num[80]; /*!< Caller ID num */
1492 char cid_name[80]; /*!< Caller ID name */
1493 int callingpres; /*!< Calling id presentation */
1494 int inUse; /*!< Number of calls in use */
1495 int inRinging; /*!< Number of calls ringing */
1496 int onHold; /*!< Peer has someone on hold */
1497 int call_limit; /*!< Limit of concurrent calls */
1498 int busy_level; /*!< Level of active channels where we signal busy */
1499 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1500 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1501 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1502 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1503 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1504 char parkinglot[AST_MAX_CONTEXT];/*!< Parkinglot */
1505 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1506 struct ast_codec_pref prefs; /*!< codec prefs */
1508 unsigned int sipoptions; /*!< Supported SIP options */
1509 struct ast_flags flags[2]; /*!< SIP_ flags */
1511 /*! Mailboxes that this peer cares about */
1512 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1514 /* things that don't belong in flags */
1515 char is_realtime; /*!< this is a 'realtime' peer */
1516 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1517 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1518 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1519 char onlymatchonip; /*!< P: Only match on IP for incoming calls (old type=peer) */
1520 char the_mark; /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
1522 int expire; /*!< When to expire this peer registration */
1523 int capability; /*!< Codec capability */
1524 int rtptimeout; /*!< RTP timeout */
1525 int rtpholdtimeout; /*!< RTP Hold Timeout */
1526 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1527 ast_group_t callgroup; /*!< Call group */
1528 ast_group_t pickupgroup; /*!< Pickup group */
1529 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1530 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1531 struct sockaddr_in addr; /*!< IP address of peer */
1532 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1535 struct sip_pvt *call; /*!< Call pointer */
1536 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1537 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1538 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1539 int qualifyfreq; /*!< Qualification: How often to check for the host to be up */
1540 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1541 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1542 struct ast_ha *ha; /*!< Access control list */
1543 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1544 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1546 struct sip_st_cfg stimer; /*!< SIP Session-Timers */
1547 int timer_t1; /*!< The maximum T1 value for the peer */
1548 int timer_b; /*!< The maximum timer B (transaction timeouts) */
1549 int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1553 /*! \brief Registrations with other SIP proxies
1554 * Created by sip_register(), the entry is linked in the 'regl' list,
1555 * and never deleted (other than at 'sip reload' or module unload times).
1556 * The entry always has a pending timeout, either waiting for an ACK to
1557 * the REGISTER message (in which case we have to retransmit the request),
1558 * or waiting for the next REGISTER message to be sent (either the initial one,
1559 * or once the previously completed registration one expires).
1560 * The registration can be in one of many states, though at the moment
1561 * the handling is a bit mixed.
1562 * Note that the entire evolution of sip_registry (transmissions,
1563 * incoming packets and timeouts) is driven by one single thread,
1564 * do_monitor(), so there is almost no synchronization issue.
1565 * The only exception is the sip_pvt creation/lookup,
1566 * as the dialoglist is also manipulated by other threads.
1568 struct sip_registry {
1569 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1570 AST_DECLARE_STRING_FIELDS(
1571 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1572 AST_STRING_FIELD(realm); /*!< Authorization realm */
1573 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1574 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1575 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1576 AST_STRING_FIELD(domain); /*!< Authorization domain */
1577 AST_STRING_FIELD(username); /*!< Who we are registering as */
1578 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1579 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1580 AST_STRING_FIELD(secret); /*!< Password in clear text */
1581 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1582 AST_STRING_FIELD(callback); /*!< Contact extension */
1583 AST_STRING_FIELD(random);
1585 enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
1586 int portno; /*!< Optional port override */
1587 int expire; /*!< Sched ID of expiration */
1588 int expiry; /*!< Value to use for the Expires header */
1589 int regattempts; /*!< Number of attempts (since the last success) */
1590 int timeout; /*!< sched id of sip_reg_timeout */
1591 int refresh; /*!< How often to refresh */
1592 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1593 enum sipregistrystate regstate; /*!< Registration state (see above) */
1594 struct timeval regtime; /*!< Last successful registration time */
1595 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1596 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1597 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for register */
1598 struct sockaddr_in us; /*!< Who the server thinks we are */
1599 int noncecount; /*!< Nonce-count */
1600 char lastmsg[256]; /*!< Last Message sent/received */
1603 /*! \brief Definition of a thread that handles a socket */
1604 struct sip_threadinfo {
1607 struct ast_tcptls_session_instance *ser;
1608 enum sip_transport type; /*!< We keep a copy of the type here so we can display it in the connection list */
1609 AST_LIST_ENTRY(sip_threadinfo) list;
1612 /* --- Hash tables of various objects --------*/
1615 static int hash_peer_size = 17;
1616 static int hash_dialog_size = 17;
1617 static int hash_user_size = 17;
1619 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
1620 static int hash_dialog_size = 563;
1621 static int hash_user_size = 563;
1624 /*! \brief The thread list of TCP threads */
1625 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
1627 /*! \brief The peer list: Users, Peers and Friends */
1628 struct ao2_container *peers;
1629 struct ao2_container *peers_by_ip;
1631 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1632 static struct ast_register_list {
1633 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1638 * \note The only member of the peer used here is the name field
1640 static int peer_hash_cb(const void *obj, const int flags)
1642 const struct sip_peer *peer = obj;
1644 return ast_str_hash(peer->name);
1648 * \note The only member of the peer used here is the name field
1650 static int peer_cmp_cb(void *obj, void *arg, int flags)
1652 struct sip_peer *peer = obj, *peer2 = arg;
1654 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1658 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1660 static int peer_iphash_cb(const void *obj, const int flags)
1662 const struct sip_peer *peer = obj;
1663 int ret1 = peer->addr.sin_addr.s_addr;
1667 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
1670 return ret1 + peer->addr.sin_port;
1675 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1677 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
1679 struct sip_peer *peer = obj, *peer2 = arg;
1681 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr)
1684 if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
1685 if (peer->addr.sin_port == peer2->addr.sin_port)
1694 * \note The only member of the dialog used here callid string
1696 static int dialog_hash_cb(const void *obj, const int flags)
1698 const struct sip_pvt *pvt = obj;
1700 return ast_str_hash(pvt->callid);
1704 * \note The only member of the dialog used here callid string
1706 static int dialog_cmp_cb(void *obj, void *arg, int flags)
1708 struct sip_pvt *pvt = obj, *pvt2 = arg;
1710 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
1713 static int temp_pvt_init(void *);
1714 static void temp_pvt_cleanup(void *);
1716 /*! \brief A per-thread temporary pvt structure */
1717 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1720 static void ts_ast_rtp_destroy(void *);
1722 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
1723 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
1724 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
1727 /*! \brief Authentication list for realm authentication
1728 * \todo Move the sip_auth list to AST_LIST */
1729 static struct sip_auth *authl = NULL;
1732 /* --- Sockets and networking --------------*/
1734 /*! \brief Main socket for SIP communication.
1736 * sipsock is shared between the SIP manager thread (which handles reload
1737 * requests), the io handler (sipsock_read()) and the user routines that
1738 * issue writes (using __sip_xmit()).
1739 * The socket is -1 only when opening fails (this is a permanent condition),
1740 * or when we are handling a reload() that changes its address (this is
1741 * a transient situation during which we might have a harmless race, see
1742 * below). Because the conditions for the race to be possible are extremely
1743 * rare, we don't want to pay the cost of locking on every I/O.
1744 * Rather, we remember that when the race may occur, communication is
1745 * bound to fail anyways, so we just live with this event and let
1746 * the protocol handle this above us.
1748 static int sipsock = -1;
1750 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
1752 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1753 * internip is initialized picking a suitable address from one of the
1754 * interfaces, and the same port number we bind to. It is used as the
1755 * default address/port in SIP messages, and as the default address
1756 * (but not port) in SDP messages.
1758 static struct sockaddr_in internip;
1760 /*! \brief our external IP address/port for SIP sessions.
1761 * externip.sin_addr is only set when we know we might be behind
1762 * a NAT, and this is done using a variety of (mutually exclusive)
1763 * ways from the config file:
1765 * + with "externip = host[:port]" we specify the address/port explicitly.
1766 * The address is looked up only once when (re)loading the config file;
1768 * + with "externhost = host[:port]" we do a similar thing, but the
1769 * hostname is stored in externhost, and the hostname->IP mapping
1770 * is refreshed every 'externrefresh' seconds;
1772 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1773 * to the specified server, and store the result in externip.
1775 * Other variables (externhost, externexpire, externrefresh) are used
1776 * to support the above functions.
1778 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1780 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1781 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1782 static int externrefresh = 10;
1783 static struct sockaddr_in stunaddr; /*!< stun server address */
1785 /*! \brief List of local networks
1786 * We store "localnet" addresses from the config file into an access list,
1787 * marked as 'DENY', so the call to ast_apply_ha() will return
1788 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1789 * (i.e. presumably public) addresses.
1791 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1793 static int ourport_tcp; /*!< The port used for TCP connections */
1794 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1795 static struct sockaddr_in debugaddr;
1797 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1799 /*! some list management macros. */
1801 #define UNLINK(element, head, prev) do { \
1803 (prev)->next = (element)->next; \
1805 (head) = (element)->next; \
1808 enum t38_action_flag {
1809 SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
1810 SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
1811 SDP_T38_ACCEPT, /*!< Remote side accepted our T38 request */
1814 /*---------------------------- Forward declarations of functions in chan_sip.c */
1815 /* Note: This is added to help splitting up chan_sip.c into several files
1816 in coming releases. */
1818 /*--- PBX interface functions */
1819 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1820 static int sip_devicestate(void *data);
1821 static int sip_sendtext(struct ast_channel *ast, const char *text);
1822 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1823 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1824 static int sip_hangup(struct ast_channel *ast);
1825 static int sip_answer(struct ast_channel *ast);
1826 static struct ast_frame *sip_read(struct ast_channel *ast);
1827 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1828 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1829 static int sip_transfer(struct ast_channel *ast, const char *dest);
1830 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1831 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1832 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1833 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1834 static const char *sip_get_callid(struct ast_channel *chan);
1836 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1837 static int sip_standard_port(struct sip_socket s);
1838 static int sip_prepare_socket(struct sip_pvt *p);
1839 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
1841 /*--- Transmitting responses and requests */
1842 static int sipsock_read(int *id, int fd, short events, void *ignore);
1843 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1844 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1845 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1846 static int retrans_pkt(const void *data);
1847 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);
1848 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1849 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1850 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1851 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
1852 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1853 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);
1854 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1855 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1856 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1857 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1858 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1859 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1860 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1861 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1862 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1863 static int transmit_refer(struct sip_pvt *p, const char *dest);
1864 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1865 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1866 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
1867 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1868 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1869 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1870 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1871 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1872 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1873 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1875 /*--- Dialog management */
1876 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1877 int useglobal_nat, const int intended_method);
1878 static int __sip_autodestruct(const void *data);
1879 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1880 static int sip_cancel_destroy(struct sip_pvt *p);
1881 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1882 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
1883 static void *registry_unref(struct sip_registry *reg, char *tag);
1884 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1885 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1886 static void __sip_pretend_ack(struct sip_pvt *p);
1887 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1888 static int auto_congest(const void *arg);
1889 static int update_call_counter(struct sip_pvt *fup, int event);
1890 static int hangup_sip2cause(int cause);
1891 static const char *hangup_cause2sip(int cause);
1892 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1893 static void free_old_route(struct sip_route *route);
1894 static void list_route(struct sip_route *route);
1895 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1896 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1897 struct sip_request *req, char *uri);
1898 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1899 static void check_pendings(struct sip_pvt *p);
1900 static void *sip_park_thread(void *stuff);
1901 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1902 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1904 /*--- Codec handling / SDP */
1905 static void try_suggested_sip_codec(struct sip_pvt *p);
1906 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1907 static const char *get_sdp(struct sip_request *req, const char *name);
1908 static int find_sdp(struct sip_request *req);
1909 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1910 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1911 struct ast_str **m_buf, struct ast_str **a_buf,
1912 int debug, int *min_packet_size);
1913 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1914 struct ast_str **m_buf, struct ast_str **a_buf,
1916 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp);
1917 static void do_setnat(struct sip_pvt *p, int natflags);
1918 static void stop_media_flows(struct sip_pvt *p);
1920 /*--- Authentication stuff */
1921 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1922 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1923 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1924 const char *secret, const char *md5secret, int sipmethod,
1925 char *uri, enum xmittype reliable, int ignore);
1926 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1927 int sipmethod, char *uri, enum xmittype reliable,
1928 struct sockaddr_in *sin, struct sip_peer **authpeer);
1929 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1931 /*--- Domain handling */
1932 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1933 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1934 static void clear_sip_domains(void);
1936 /*--- SIP realm authentication */
1937 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1938 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1939 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1941 /*--- Misc functions */
1942 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1943 static int sip_do_reload(enum channelreloadreason reason);
1944 static int reload_config(enum channelreloadreason reason);
1945 static int expire_register(const void *data);
1946 static void *do_monitor(void *data);
1947 static int restart_monitor(void);
1948 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1949 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1950 static int sip_refer_allocate(struct sip_pvt *p);
1951 static void ast_quiet_chan(struct ast_channel *chan);
1952 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1954 * \brief generic function for determining if a correct transport is being
1955 * used to contact a peer
1957 * this is done as a macro so that the "tmpl" var can be passed either a
1958 * sip_request or a sip_peer
1960 #define check_request_transport(peer, tmpl) ({ \
1962 if (peer->socket.type == tmpl->socket.type) \
1964 else if (!(peer->transports & tmpl->socket.type)) {\
1965 ast_log(LOG_ERROR, \
1966 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
1967 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer) \
1970 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
1971 ast_log(LOG_WARNING, \
1972 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
1973 peer->name, get_transport(tmpl->socket.type) \
1977 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
1978 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
1985 /*--- Device monitoring and Device/extension state/event handling */
1986 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1987 static int sip_devicestate(void *data);
1988 static int sip_poke_noanswer(const void *data);
1989 static int sip_poke_peer(struct sip_peer *peer, int force);
1990 static void sip_poke_all_peers(void);
1991 static void sip_peer_hold(struct sip_pvt *p, int hold);
1992 static void mwi_event_cb(const struct ast_event *, void *);
1994 /*--- Applications, functions, CLI and manager command helpers */
1995 static const char *sip_nat_mode(const struct sip_pvt *p);
1996 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1997 static char *transfermode2str(enum transfermodes mode) attribute_const;
1998 static const char *nat2str(int nat) attribute_const;
1999 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
2000 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2001 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2002 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2003 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2004 static void print_group(int fd, ast_group_t group, int crlf);
2005 static const char *dtmfmode2str(int mode) attribute_const;
2006 static int str2dtmfmode(const char *str) attribute_unused;
2007 static const char *insecure2str(int mode) attribute_const;
2008 static void cleanup_stale_contexts(char *new, char *old);
2009 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
2010 static const char *domain_mode_to_text(const enum domain_mode mode);
2011 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2012 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2013 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2014 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
2015 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2016 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2017 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2018 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2019 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
2020 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2021 static char *complete_sip_peer(const char *word, int state, int flags2);
2022 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
2023 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
2024 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
2025 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
2026 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
2027 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2028 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2029 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2030 static char *sip_do_debug_ip(int fd, char *arg);
2031 static char *sip_do_debug_peer(int fd, char *arg);
2032 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2033 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2034 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2035 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2036 static int sip_dtmfmode(struct ast_channel *chan, void *data);
2037 static int sip_addheader(struct ast_channel *chan, void *data);
2038 static int sip_do_reload(enum channelreloadreason reason);
2039 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2040 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
2043 Functions for enabling debug per IP or fully, or enabling history logging for
2046 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
2047 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
2048 static inline int sip_debug_test_pvt(struct sip_pvt *p);
2051 /*! \brief Append to SIP dialog history
2052 \return Always returns 0 */
2053 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2054 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
2055 static void sip_dump_history(struct sip_pvt *dialog);
2057 /*--- Device object handling */
2058 static struct sip_peer *temp_peer(const char *name);
2059 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int ispeer);
2060 static int update_call_counter(struct sip_pvt *fup, int event);
2061 static void sip_destroy_peer(struct sip_peer *peer);
2062 static void sip_destroy_peer_fn(void *peer);
2063 static void set_peer_defaults(struct sip_peer *peer);
2064 static struct sip_peer *temp_peer(const char *name);
2065 static void register_peer_exten(struct sip_peer *peer, int onoff);
2066 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch);
2067 static int sip_poke_peer_s(const void *data);
2068 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
2069 static void reg_source_db(struct sip_peer *peer);
2070 static void destroy_association(struct sip_peer *peer);
2071 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
2072 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
2074 /* Realtime device support */
2075 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username);
2076 static void update_peer(struct sip_peer *p, int expire);
2077 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
2078 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
2079 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
2080 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2082 /*--- Internal UA client handling (outbound registrations) */
2083 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
2084 static void sip_registry_destroy(struct sip_registry *reg);
2085 static int sip_register(const char *value, int lineno);
2086 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
2087 static int sip_reregister(const void *data);
2088 static int __sip_do_register(struct sip_registry *r);
2089 static int sip_reg_timeout(const void *data);
2090 static void sip_send_all_registers(void);
2091 static int sip_reinvite_retry(const void *data);
2093 /*--- Parsing SIP requests and responses */
2094 static void append_date(struct sip_request *req); /* Append date to SIP packet */
2095 static int determine_firstline_parts(struct sip_request *req);
2096 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2097 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
2098 static int find_sip_method(const char *msg);
2099 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
2100 static int parse_request(struct sip_request *req);
2101 static const char *get_header(const struct sip_request *req, const char *name);
2102 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
2103 static int method_match(enum sipmethod id, const char *name);
2104 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
2105 static char *get_in_brackets(char *tmp);
2106 static const char *find_alias(const char *name, const char *_default);
2107 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
2108 static int lws2sws(char *msgbuf, int len);
2109 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
2110 static char *remove_uri_parameters(char *uri);
2111 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
2112 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
2113 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
2114 static int set_address_from_contact(struct sip_pvt *pvt);
2115 static void check_via(struct sip_pvt *p, struct sip_request *req);
2116 static char *get_calleridname(const char *input, char *output, size_t outputsize);
2117 static int get_rpid_num(const char *input, char *output, int maxlen);
2118 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
2119 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
2120 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
2121 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
2123 /*-- TCP connection handling ---*/
2124 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser);
2125 static void *sip_tcp_worker_fn(void *);
2127 /*--- Constructing requests and responses */
2128 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
2129 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
2130 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
2131 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
2132 static int init_resp(struct sip_request *resp, const char *msg);
2133 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
2134 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
2135 static void build_via(struct sip_pvt *p);
2136 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
2137 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
2138 static char *generate_random_string(char *buf, size_t size);
2139 static void build_callid_pvt(struct sip_pvt *pvt);
2140 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
2141 static void make_our_tag(char *tagbuf, size_t len);
2142 static int add_header(struct sip_request *req, const char *var, const char *value);
2143 static int add_header_contentLength(struct sip_request *req, int len);
2144 static int add_line(struct sip_request *req, const char *line);
2145 static int add_text(struct sip_request *req, const char *text);
2146 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
2147 static int add_vidupdate(struct sip_request *req);
2148 static void add_route(struct sip_request *req, struct sip_route *route);
2149 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2150 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2151 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
2152 static void set_destination(struct sip_pvt *p, char *uri);
2153 static void append_date(struct sip_request *req);
2154 static void build_contact(struct sip_pvt *p);
2155 static void build_rpid(struct sip_pvt *p);
2157 /*------Request handling functions */
2158 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
2159 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
2160 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
2161 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
2162 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
2163 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
2164 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
2165 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2166 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
2167 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
2168 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
2169 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2170 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
2172 /*------Response handling functions */
2173 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2174 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2175 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2176 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2177 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2179 /*----- RTP interface functions */
2180 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
2181 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2182 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2183 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2184 static int sip_get_codec(struct ast_channel *chan);
2185 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
2187 /*------ T38 Support --------- */
2188 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
2189 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
2190 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
2191 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
2192 static void change_t38_state(struct sip_pvt *p, int state);
2194 /*------ Session-Timers functions --------- */
2195 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
2196 static int proc_session_timer(const void *vp);
2197 static void stop_session_timer(struct sip_pvt *p);
2198 static void start_session_timer(struct sip_pvt *p);
2199 static void restart_session_timer(struct sip_pvt *p);
2200 static const char *strefresher2str(enum st_refresher r);
2201 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
2202 static int parse_minse(const char *p_hdrval, int *const p_interval);
2203 static int st_get_se(struct sip_pvt *, int max);
2204 static enum st_refresher st_get_refresher(struct sip_pvt *);
2205 static enum st_mode st_get_mode(struct sip_pvt *);
2206 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
2209 /*! \brief Definition of this channel for PBX channel registration */
2210 static const struct ast_channel_tech sip_tech = {
2212 .description = "Session Initiation Protocol (SIP)",
2213 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
2214 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
2215 .requester = sip_request_call, /* called with chan unlocked */
2216 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
2217 .call = sip_call, /* called with chan locked */
2218 .send_html = sip_sendhtml,
2219 .hangup = sip_hangup, /* called with chan locked */
2220 .answer = sip_answer, /* called with chan locked */
2221 .read = sip_read, /* called with chan locked */
2222 .write = sip_write, /* called with chan locked */
2223 .write_video = sip_write, /* called with chan locked */
2224 .write_text = sip_write,
2225 .indicate = sip_indicate, /* called with chan locked */
2226 .transfer = sip_transfer, /* called with chan locked */
2227 .fixup = sip_fixup, /* called with chan locked */
2228 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
2229 .send_digit_end = sip_senddigit_end,
2230 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
2231 .early_bridge = ast_rtp_early_bridge,
2232 .send_text = sip_sendtext, /* called with chan locked */
2233 .func_channel_read = acf_channel_read,
2234 .queryoption = sip_queryoption,
2235 .get_pvt_uniqueid = sip_get_callid,
2238 /*! \brief This version of the sip channel tech has no send_digit_begin
2239 * callback so that the core knows that the channel does not want
2240 * DTMF BEGIN frames.
2241 * The struct is initialized just before registering the channel driver,
2242 * and is for use with channels using SIP INFO DTMF.
2244 static struct ast_channel_tech sip_tech_info;
2247 /*! \brief Working TLS connection configuration */
2248 static struct ast_tls_config sip_tls_cfg;
2250 /*! \brief Default TLS connection configuration */
2251 static struct ast_tls_config default_tls_cfg;
2253 /*! \brief The TCP server definition */
2254 static struct server_args sip_tcp_desc = {
2256 .master = AST_PTHREADT_NULL,
2259 .name = "sip tcp server",
2260 .accept_fn = ast_tcptls_server_root,
2261 .worker_fn = sip_tcp_worker_fn,
2264 /*! \brief The TCP/TLS server definition */
2265 static struct server_args sip_tls_desc = {
2267 .master = AST_PTHREADT_NULL,
2268 .tls_cfg = &sip_tls_cfg,
2270 .name = "sip tls server",
2271 .accept_fn = ast_tcptls_server_root,
2272 .worker_fn = sip_tcp_worker_fn,
2275 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
2276 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
2278 /*! \brief map from an integer value to a string.
2279 * If no match is found, return errorstring
2281 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2283 const struct _map_x_s *cur;
2285 for (cur = table; cur->s; cur++)
2291 /*! \brief map from a string to an integer value, case insensitive.
2292 * If no match is found, return errorvalue.
2294 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2296 const struct _map_x_s *cur;
2298 for (cur = table; cur->s; cur++)
2299 if (!strcasecmp(cur->s, s))
2305 /*! \brief Interface structure with callbacks used to connect to RTP module */
2306 static struct ast_rtp_protocol sip_rtp = {
2308 .get_rtp_info = sip_get_rtp_peer,
2309 .get_vrtp_info = sip_get_vrtp_peer,
2310 .get_trtp_info = sip_get_trtp_peer,
2311 .set_rtp_peer = sip_set_rtp_peer,
2312 .get_codec = sip_get_codec,
2316 /*! \brief SIP TCP connection handler */
2317 static void *sip_tcp_worker_fn(void *data)
2319 struct ast_tcptls_session_instance *ser = data;
2321 return _sip_tcp_helper_thread(NULL, ser);
2324 /*! \brief SIP TCP thread management function */
2325 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser)
2328 struct sip_request req = { 0, } , reqcpy = { 0, };
2329 struct sip_threadinfo *me;
2330 char buf[1024] = "";
2332 me = ast_calloc(1, sizeof(*me));
2337 me->threadid = pthread_self();
2340 me->type = SIP_TRANSPORT_TLS;
2342 me->type = SIP_TRANSPORT_TCP;
2344 AST_LIST_LOCK(&threadl);
2345 AST_LIST_INSERT_TAIL(&threadl, me, list);
2346 AST_LIST_UNLOCK(&threadl);
2348 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2350 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2354 ast_str_reset(req.data);
2355 ast_str_reset(reqcpy.data);
2360 req.socket.fd = ser->fd;
2362 req.socket.type = SIP_TRANSPORT_TLS;
2363 req.socket.port = htons(ourport_tls);
2365 req.socket.type = SIP_TRANSPORT_TCP;
2366 req.socket.port = htons(ourport_tcp);
2368 res = ast_wait_for_input(ser->fd, -1);
2370 ast_debug(1, "ast_wait_for_input returned %d\n", res);
2374 /* Read in headers one line at a time */
2375 while (req.len < 4 || strncmp((char *)&req.data->str + req.len - 4, "\r\n\r\n", 4)) {
2376 ast_mutex_lock(&ser->lock);
2377 if (!fgets(buf, sizeof(buf), ser->f)) {
2378 ast_mutex_unlock(&ser->lock);
2381 ast_mutex_unlock(&ser->lock);
2384 ast_str_append(&req.data, 0, "%s", buf);
2385 req.len = req.data->used;
2387 copy_request(&reqcpy, &req);
2388 parse_request(&reqcpy);
2389 if (sscanf(get_header(&reqcpy, "Content-Length"), "%d", &cl)) {
2391 ast_mutex_lock(&ser->lock);
2392 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, ser->f)) {
2393 ast_mutex_unlock(&ser->lock);
2396 ast_mutex_unlock(&ser->lock);
2400 ast_str_append(&req.data, 0, "%s", buf);
2401 req.len = req.data->used;
2404 req.socket.ser = ser;
2405 handle_request_do(&req, &ser->requestor);
2409 AST_LIST_LOCK(&threadl);
2410 AST_LIST_REMOVE(&threadl, me, list);
2411 AST_LIST_UNLOCK(&threadl);
2418 ast_free(reqcpy.data);
2435 * helper functions to unreference various types of objects.
2436 * By handling them this way, we don't have to declare the
2437 * destructor on each call, which removes the chance of errors.
2439 static void *unref_peer(struct sip_peer *peer, char *tag)
2441 ao2_t_ref(peer, -1, tag);
2445 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2447 ao2_t_ref(peer, 1,tag);
2452 * \brief Unlink a dialog from the dialogs container, as well as any other places
2453 * that it may be currently stored.
2455 * \note A reference to the dialog must be held before calling this function, and this
2456 * function does not release that reference.
2458 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2462 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2464 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2466 /* Unlink us from the owner (channel) if we have one */
2467 if (dialog->owner) {
2469 ast_channel_lock(dialog->owner);
2470 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2471 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2473 ast_channel_unlock(dialog->owner);
2475 if (dialog->registry) {
2476 if (dialog->registry->call == dialog)
2477 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2478 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2480 if (dialog->stateid > -1) {
2481 ast_extension_state_del(dialog->stateid, NULL);
2482 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2483 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2485 /* Remove link from peer to subscription of MWI */
2486 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2487 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2488 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2489 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2491 /* remove all current packets in this dialog */
2492 while((cp = dialog->packets)) {
2493 dialog->packets = dialog->packets->next;
2494 AST_SCHED_DEL(sched, cp->retransid);
2495 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2499 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"));
2501 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"));
2503 if (dialog->autokillid > -1)
2504 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"));
2506 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2510 static void *registry_unref(struct sip_registry *reg, char *tag)
2512 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2513 ASTOBJ_UNREF(reg, sip_registry_destroy);
2517 /*! \brief Add object reference to SIP registry */
2518 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2520 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2521 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2524 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2525 static struct ast_udptl_protocol sip_udptl = {
2527 get_udptl_info: sip_get_udptl_peer,
2528 set_udptl_peer: sip_set_udptl_peer,
2531 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2532 __attribute__ ((format (printf, 2, 3)));
2535 /*! \brief Convert transfer status to string */
2536 static const char *referstatus2str(enum referstatus rstatus)
2538 return map_x_s(referstatusstrings, rstatus, "");
2541 /*! \brief Initialize the initital request packet in the pvt structure.
2542 This packet is used for creating replies and future requests in
2544 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2546 if (p->initreq.headers)
2547 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2549 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2550 /* Use this as the basis */
2551 copy_request(&p->initreq, req);
2552 parse_request(&p->initreq);
2554 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2557 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2558 static void sip_alreadygone(struct sip_pvt *dialog)
2560 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2561 dialog->alreadygone = 1;
2564 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2565 static int proxy_update(struct sip_proxy *proxy)
2567 /* if it's actually an IP address and not a name,
2568 there's no need for a managed lookup */
2569 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2570 /* Ok, not an IP address, then let's check if it's a domain or host */
2571 /* XXX Todo - if we have proxy port, don't do SRV */
2572 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
2573 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2577 proxy->last_dnsupdate = time(NULL);
2581 /*! \brief Allocate and initialize sip proxy */
2582 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2584 struct sip_proxy *proxy;
2585 proxy = ast_calloc(1, sizeof(*proxy));
2588 proxy->force = force;
2589 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2590 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2591 proxy_update(proxy);
2595 /*! \brief Get default outbound proxy or global proxy */
2596 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2598 if (peer && peer->outboundproxy) {
2600 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2601 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2602 return peer->outboundproxy;
2604 if (global_outboundproxy.name[0]) {
2606 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2607 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2608 return &global_outboundproxy;
2611 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2615 /*! \brief returns true if 'name' (with optional trailing whitespace)
2616 * matches the sip method 'id'.
2617 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2618 * a case-insensitive comparison to be more tolerant.
2619 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2621 static int method_match(enum sipmethod id, const char *name)
2623 int len = strlen(sip_methods[id].text);
2624 int l_name = name ? strlen(name) : 0;
2625 /* true if the string is long enough, and ends with whitespace, and matches */
2626 return (l_name >= len && name[len] < 33 &&
2627 !strncasecmp(sip_methods[id].text, name, len));
2630 /*! \brief find_sip_method: Find SIP method from header */
2631 static int find_sip_method(const char *msg)
2635 if (ast_strlen_zero(msg))
2637 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2638 if (method_match(i, msg))
2639 res = sip_methods[i].id;
2644 /*! \brief Parse supported header in incoming packet */
2645 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2649 unsigned int profile = 0;
2652 if (ast_strlen_zero(supported) )
2654 temp = ast_strdupa(supported);
2657 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2659 for (next = temp; next; next = sep) {
2661 if ( (sep = strchr(next, ',')) != NULL)
2663 next = ast_skip_blanks(next);
2665 ast_debug(3, "Found SIP option: -%s-\n", next);
2666 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2667 if (!strcasecmp(next, sip_options[i].text)) {
2668 profile |= sip_options[i].id;
2671 ast_debug(3, "Matched SIP option: %s\n", next);
2676 /* This function is used to parse both Suported: and Require: headers.
2677 Let the caller of this function know that an unknown option tag was
2678 encountered, so that if the UAC requires it then the request can be
2679 rejected with a 420 response. */
2681 profile |= SIP_OPT_UNKNOWN;
2683 if (!found && sipdebug) {
2684 if (!strncasecmp(next, "x-", 2))
2685 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2687 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2692 pvt->sipoptions = profile;
2696 /*! \brief See if we pass debug IP filter */
2697 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2701 if (debugaddr.sin_addr.s_addr) {
2702 if (((ntohs(debugaddr.sin_port) != 0)
2703 && (debugaddr.sin_port != addr->sin_port))
2704 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2710 /*! \brief The real destination address for a write */
2711 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2713 if (p->outboundproxy)
2714 return &p->outboundproxy->ip;
2716 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2719 /*! \brief Display SIP nat mode */
2720 static const char *sip_nat_mode(const struct sip_pvt *p)
2722 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2725 /*! \brief Test PVT for debugging output */
2726 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2730 return sip_debug_test_addr(sip_real_dst(p));
2733 static inline const char *get_transport_list(struct sip_peer *peer) {
2734 switch (peer->transports) {
2735 case SIP_TRANSPORT_UDP:
2737 case SIP_TRANSPORT_TCP:
2739 case SIP_TRANSPORT_TLS:
2741 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
2743 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
2745 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
2748 return peer->transports ?
2749 "TLS,TCP,UDP" : "UNKNOWN";
2753 static inline const char *get_transport(enum sip_transport t)
2756 case SIP_TRANSPORT_UDP:
2758 case SIP_TRANSPORT_TCP:
2760 case SIP_TRANSPORT_TLS:
2767 static inline const char *get_transport_pvt(struct sip_pvt *p)
2769 if (p->outboundproxy && p->outboundproxy->transport)
2770 p->socket.type = p->outboundproxy->transport;
2772 return get_transport(p->socket.type);
2775 /*! \brief Transmit SIP message
2776 Sends a SIP request or response on a given socket (in the pvt)
2777 Called by retrans_pkt, send_request, send_response and
2780 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2783 const struct sockaddr_in *dst = sip_real_dst(p);
2785 ast_debug(1, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
2787 if (sip_prepare_socket(p) < 0)
2791 ast_mutex_lock(&p->socket.ser->lock);
2793 if (p->socket.type & SIP_TRANSPORT_UDP)
2794 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2796 if (p->socket.ser->f)
2797 res = ast_tcptls_server_write(p->socket.ser, data->str, len);
2799 ast_debug(1, "No p->socket.ser->f len=%d\n", len);
2803 ast_mutex_unlock(&p->socket.ser->lock);
2807 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2808 case EHOSTUNREACH: /* Host can't be reached */
2809 case ENETDOWN: /* Inteface down */
2810 case ENETUNREACH: /* Network failure */
2811 case ECONNREFUSED: /* ICMP port unreachable */
2812 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2816 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));
2821 /*! \brief Build a Via header for a request */
2822 static void build_via(struct sip_pvt *p)
2824 /* Work around buggy UNIDEN UIP200 firmware */
2825 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2827 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2828 ast_string_field_build(p, via, "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
2829 get_transport_pvt(p),
2830 ast_inet_ntoa(p->ourip.sin_addr),
2831 ntohs(p->ourip.sin_port), p->branch, rport);
2834 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2836 * Using the localaddr structure built up with localnet statements in sip.conf
2837 * apply it to their address to see if we need to substitute our
2838 * externip or can get away with our internal bindaddr
2839 * 'us' is always overwritten.
2841 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2843 struct sockaddr_in theirs;
2844 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2845 * reachable IP address and port. This is done if:
2846 * 1. we have a localaddr list (containing 'internal' addresses marked
2847 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2848 * and AST_SENSE_ALLOW on 'external' ones);
2849 * 2. either stunaddr or externip is set, so we know what to use as the
2850 * externally visible address;
2851 * 3. the remote address, 'them', is external;
2852 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2853 * when passed to ast_apply_ha() so it does need to be remapped.
2854 * This fourth condition is checked later.
2858 *us = internip; /* starting guess for the internal address */
2859 /* now ask the system what would it use to talk to 'them' */
2860 ast_ouraddrfor(them, &us->sin_addr);
2861 theirs.sin_addr = *them;
2863 want_remap = localaddr &&
2864 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2865 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2868 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2869 /* if we used externhost or stun, see if it is time to refresh the info */
2870 if (externexpire && time(NULL) >= externexpire) {
2871 if (stunaddr.sin_addr.s_addr) {
2872 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2874 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2875 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2877 externexpire = time(NULL) + externrefresh;
2879 if (externip.sin_addr.s_addr)
2882 ast_log(LOG_WARNING, "stun failed\n");
2883 ast_debug(1, "Target address %s is not local, substituting externip\n",
2884 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2885 } else if (bindaddr.sin_addr.s_addr) {
2886 /* no remapping, but we bind to a specific address, so use it. */
2891 /*! \brief Append to SIP dialog history with arg list */
2892 static __attribute__((format (printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2894 char buf[80], *c = buf; /* max history length */
2895 struct sip_history *hist;
2898 vsnprintf(buf, sizeof(buf), fmt, ap);
2899 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2900 l = strlen(buf) + 1;
2901 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2903 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2907 memcpy(hist->event, buf, l);
2908 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2909 struct sip_history *oldest;
2910 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2911 p->history_entries--;
2914 AST_LIST_INSERT_TAIL(p->history, hist, list);
2915 p->history_entries++;
2918 /*! \brief Append to SIP dialog history with arg list */
2919 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2926 if (!p->do_history && !recordhistory && !dumphistory)
2930 append_history_va(p, fmt, ap);
2936 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2937 static int retrans_pkt(const void *data)
2939 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2940 int reschedule = DEFAULT_RETRANS;
2943 /* Lock channel PVT */
2944 sip_pvt_lock(pkt->owner);
2946 if (pkt->retrans < MAX_RETRANS) {
2948 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2950 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);
2955 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2959 pkt->timer_a = 2 * pkt->timer_a;
2961 /* For non-invites, a maximum of 4 secs */
2962 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2963 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2966 /* Reschedule re-transmit */
2967 reschedule = siptimer_a;
2968 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);
2971 if (sip_debug_test_pvt(pkt->owner)) {
2972 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2973 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2974 pkt->retrans, sip_nat_mode(pkt->owner),
2975 ast_inet_ntoa(dst->sin_addr),
2976 ntohs(dst->sin_port), pkt->data->str);
2979 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
2980 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2981 sip_pvt_unlock(pkt->owner);
2982 if (xmitres == XMIT_ERROR)
2983 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2987 /* Too many retries */
2988 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2989 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2990 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
2991 pkt->owner->callid, pkt->seqno,
2992 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2993 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2994 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
2997 if (xmitres == XMIT_ERROR) {
2998 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2999 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3001 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3003 pkt->retransid = -1;
3005 if (pkt->is_fatal) {
3006 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3007 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
3009 sip_pvt_lock(pkt->owner);
3012 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
3013 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3015 if (pkt->owner->owner) {
3016 sip_alreadygone(pkt->owner);
3017 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3018 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3019 ast_channel_unlock(pkt->owner->owner);
3021 /* If no channel owner, destroy now */
3023 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3024 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3025 pkt->owner->needdestroy = 1;
3026 sip_alreadygone(pkt->owner);
3027 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3032 if (pkt->method == SIP_BYE) {
3033 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
3034 if (pkt->owner->owner)
3035 ast_channel_unlock(pkt->owner->owner);
3036 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3037 pkt->owner->needdestroy = 1;
3040 /* Remove the packet */
3041 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3043 UNLINK(cur, pkt->owner->packets, prev);
3044 sip_pvt_unlock(pkt->owner);
3046 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3048 ast_free(pkt->data);
3055 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3056 sip_pvt_unlock(pkt->owner);
3060 /*! \brief Transmit packet with retransmits
3061 \return 0 on success, -1 on failure to allocate packet
3063 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)
3065 struct sip_pkt *pkt = NULL;
3066 int siptimer_a = DEFAULT_RETRANS;
3069 if (sipmethod == SIP_INVITE) {
3070 /* Note this is a pending invite */
3071 p->pendinginvite = seqno;
3074 /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3075 /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3076 /* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3077 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3078 xmitres = __sip_xmit(dialog_ref(p, "pasing dialog ptr into callback..."), data, len); /* Send packet */
3079 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3080 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3086 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3088 /* copy data, add a terminator and save length */
3089 if (!(pkt->data = ast_str_create(len))) {
3093 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3094 pkt->packetlen = len;
3095 /* copy other parameters from the caller */
3096 pkt->method = sipmethod;
3098 pkt->is_resp = resp;
3099 pkt->is_fatal = fatal;
3100 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3101 pkt->next = p->packets;
3102 p->packets = pkt; /* Add it to the queue */
3103 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
3104 pkt->retransid = -1;
3106 siptimer_a = pkt->timer_t1 * 2;
3108 /* Schedule retransmission */
3109 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3111 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
3113 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
3115 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3116 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3117 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3119 ast_free(pkt->data);
3126 /*! \brief Kill a SIP dialog (called only by the scheduler)
3127 * The scheduler has a reference to this dialog when p->autokillid != -1,
3128 * and we are called using that reference. So if the event is not
3129 * rescheduled, we need to call dialog_unref().
3131 static int __sip_autodestruct(const void *data)
3133 struct sip_pvt *p = (struct sip_pvt *)data;
3135 /* If this is a subscription, tell the phone that we got a timeout */
3136 if (p->subscribed) {
3137 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
3138 p->subscribed = NONE;
3139 append_history(p, "Subscribestatus", "timeout");
3140 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3141 return 10000; /* Reschedule this destruction so that we know that it's gone */
3144 /* If there are packets still waiting for delivery, delay the destruction */
3146 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3147 append_history(p, "ReliableXmit", "timeout");
3151 if (p->subscribed == MWI_NOTIFICATION)
3153 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) */
3155 /* Reset schedule ID */
3159 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3160 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3161 } else if (p->refer && !p->alreadygone) {
3162 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3163 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3164 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3165 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3167 append_history(p, "AutoDestroy", "%s", p->callid);
3168 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3169 dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3170 /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3171 /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
3172 /* sip_destroy also absorbs the reference */
3174 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3178 /*! \brief Schedule destruction of SIP dialog */
3179 static void sip_scheddestroy(struct sip_pvt *p, int ms)
3182 if (p->timer_t1 == 0) {
3183 p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
3184 p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
3186 ms = p->timer_t1 * 64;
3188 if (sip_debug_test_pvt(p))
3189 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3190 if (sip_cancel_destroy(p))
3191 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3194 append_history(p, "SchedDestroy", "%d ms", ms);
3195 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3197 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
3198 stop_session_timer(p);
3201 /*! \brief Cancel destruction of SIP dialog.
3202 * Be careful as this also absorbs the reference - if you call it
3203 * from within the scheduler, this might be the last reference.
3205 static int sip_cancel_destroy(struct sip_pvt *p)
3208 if (p->autokillid > -1) {
3211 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3212 append_history(p, "CancelDestroy", "");
3214 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3220 /*! \brief Acknowledges receipt of a packet and stops retransmission
3221 * called with p locked*/
3222 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3224 struct sip_pkt *cur, *prev = NULL;
3225 const char *msg = "Not Found"; /* used only for debugging */
3227 /* If we have an outbound proxy for this dialog, then delete it now since
3228 the rest of the requests in this dialog needs to follow the routing.
3229 If obforcing is set, we will keep the outbound proxy during the whole
3230 dialog, regardless of what the SIP rfc says
3232 if (p->outboundproxy && !p->outboundproxy->force)
3233 p->outboundproxy = NULL;
3235 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3236 if (cur->seqno != seqno || cur->is_resp != resp)
3238 if (cur->is_resp || cur->method == sipmethod) {
3240 if (!resp && (seqno == p->pendinginvite)) {
3241 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3242 p->pendinginvite = 0;
3244 if (cur->retransid > -1) {
3246 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3248 /* This odd section is designed to thwart a
3249 * race condition in the packet scheduler. There are
3250 * two conditions under which deleting the packet from the
3251 * scheduler can fail.
3253 * 1. The packet has been removed from the scheduler because retransmission
3254 * is being attempted. The problem is that if the packet is currently attempting
3255 * retransmission and we are at this point in the code, then that MUST mean
3256 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3257 * lock temporarily to allow retransmission.
3259 * 2. The packet has reached its maximum number of retransmissions and has
3260 * been permanently removed from the packet scheduler. If this is the case, then
3261 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3262 * of the retransid to -1 is ensured since in both cases p's lock is held.
3264 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3269 UNLINK(cur, p->packets, prev);
3270 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3272 ast_free(cur->data);
3277 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3278 p->callid, resp ? "Response" : "Request", seqno, msg);
3281 /*! \brief Pretend to ack all packets
3282 * called with p locked */
3283 static void __sip_pretend_ack(struct sip_pvt *p)
3285 struct sip_pkt *cur = NULL;
3287 while (p->packets) {
3289 if (cur == p->packets) {
3290 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
3294 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
3295 __sip_ack(p, cur->seqno, cur->is_resp, method);
3299 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
3300 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3302 struct sip_pkt *cur;
3305 for (cur = p->packets; cur; cur = cur->next) {
3306 if (cur->seqno == seqno && cur->is_resp == resp &&
3307 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
3308 /* this is our baby */
3309 if (cur->retransid > -1) {
3311 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
3313 AST_SCHED_DEL(sched, cur->retransid);
3318 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");
3323 /*! \brief Copy SIP request, parse it */
3324 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3326 copy_request(dst, src);
3330 /*! \brief add a blank line if no body */
3331 static void add_blank(struct sip_request *req)
3334 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3335 ast_str_append(&req->data, 0, "\r\n");
3336 req->len = req->data->used;
3340 /*! \brief Transmit response on SIP request*/
3341 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3346 if (sip_debug_test_pvt(p)) {
3347 const struct sockaddr_in *dst = sip_real_dst(p);
3349 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
3350 reliable ? "Reliably " : "", sip_nat_mode(p),
3351 ast_inet_ntoa(dst->sin_addr),
3352 ntohs(dst->sin_port), req->data->str);
3354 if (p->do_history) {
3355 struct sip_request tmp = { .rlPart1 = NULL, };
3356 parse_copy(&tmp, req);
3357 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
3358 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
3362 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3363 __sip_xmit(p, req->data, req->len);
3364 ast_free(req->data);
3371 /*! \brief Send SIP Request to the other part of the dialogue */
3372 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3376 /* If we have an outbound proxy, reset peer address
3379 if (p->outboundproxy) {
3380 p->sa = p->outboundproxy->ip;
3384 if (sip_debug_test_pvt(p)) {
3385 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
3386 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);
3388 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);
3390 if (p->do_history) {
3391 struct sip_request tmp = { .rlPart1 = NULL, };
3392 parse_copy(&tmp, req);
3393 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3397 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3398 __sip_xmit(p, req->data, req->len);
3400 ast_free(req->data);
3406 /*! \brief Query an option on a SIP dialog */
3407 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3410 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
3411 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
3414 case AST_OPTION_T38_STATE:
3415 /* Make sure we got an ast_t38_state enum passed in */
3416 if (*datalen != sizeof(enum ast_t38_state)) {
3417 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
3423 /* 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 */
3424 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT)) {
3425 switch (p->t38.state) {
3426 case T38_LOCAL_DIRECT:
3427 case T38_LOCAL_REINVITE:
3428 case T38_PEER_DIRECT:
3429 case T38_PEER_REINVITE:
3430 state = T38_STATE_NEGOTIATING;
3433 state = T38_STATE_NEGOTIATED;
3436 state = T38_STATE_UNKNOWN;
3442 *((enum ast_t38_state *) data) = state;
3453 /*! \brief Locate closing quote in a string, skipping escaped quotes.
3454 * optionally with a limit on the search.
3455 * start must be past the first quote.
3457 static const char *find_closing_quote(const char *start, const char *lim)
3459 char last_char = '\0';
3461 for (s = start; *s && s != lim; last_char = *s++) {
3462 if (*s == '"' && last_char != '\\')
3468 /*! \brief Pick out text in brackets from character string
3469 \return pointer to terminated stripped string
3470 \param tmp input string that will be modified
3473 "foo" <bar> valid input, returns bar