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, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
34 * \todo Better support of forking
35 * \todo VIA branch tag transaction checking
36 * \todo Transaction support
38 * \ingroup channel_drivers
40 * \par Overview of the handling of SIP sessions
41 * The SIP channel handles several types of SIP sessions, or dialogs,
42 * not all of them being "telephone calls".
43 * - Incoming calls that will be sent to the PBX core
44 * - Outgoing calls, generated by the PBX
45 * - SIP subscriptions and notifications of states and voicemail messages
46 * - SIP registrations, both inbound and outbound
47 * - SIP peer management (peerpoke, OPTIONS)
50 * In the SIP channel, there's a list of active SIP dialogs, which includes
51 * all of these when they are active. "sip show channels" in the CLI will
52 * show most of these, excluding subscriptions which are shown by
53 * "sip show subscriptions"
55 * \par incoming packets
56 * Incoming packets are received in the monitoring thread, then handled by
57 * sipsock_read(). This function parses the packet and matches an existing
58 * dialog or starts a new SIP dialog.
60 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
61 * If it is a response to an outbound request, the packet is sent to handle_response().
62 * If it is a request, handle_incoming() sends it to one of a list of functions
63 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64 * sipsock_read locks the ast_channel if it exists (an active call) and
65 * unlocks it after we have processed the SIP message.
67 * A new INVITE is sent to handle_request_invite(), that will end up
68 * starting a new channel in the PBX, the new channel after that executing
69 * in a separate channel thread. This is an incoming "call".
70 * When the call is answered, either by a bridged channel or the PBX itself
71 * the sip_answer() function is called.
73 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
86 <depend>res_features</depend>
92 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
95 #include <sys/ioctl.h>
98 #include <sys/signal.h>
101 #include "asterisk/network.h"
102 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
104 #include "asterisk/lock.h"
105 #include "asterisk/channel.h"
106 #include "asterisk/config.h"
107 #include "asterisk/module.h"
108 #include "asterisk/pbx.h"
109 #include "asterisk/sched.h"
110 #include "asterisk/io.h"
111 #include "asterisk/rtp.h"
112 #include "asterisk/udptl.h"
113 #include "asterisk/acl.h"
114 #include "asterisk/manager.h"
115 #include "asterisk/callerid.h"
116 #include "asterisk/cli.h"
117 #include "asterisk/app.h"
118 #include "asterisk/musiconhold.h"
119 #include "asterisk/dsp.h"
120 #include "asterisk/features.h"
121 #include "asterisk/srv.h"
122 #include "asterisk/astdb.h"
123 #include "asterisk/causes.h"
124 #include "asterisk/utils.h"
125 #include "asterisk/file.h"
126 #include "asterisk/astobj.h"
127 #include "asterisk/dnsmgr.h"
128 #include "asterisk/devicestate.h"
129 #include "asterisk/linkedlists.h"
130 #include "asterisk/stringfields.h"
131 #include "asterisk/monitor.h"
132 #include "asterisk/netsock.h"
133 #include "asterisk/localtime.h"
134 #include "asterisk/abstract_jb.h"
135 #include "asterisk/threadstorage.h"
136 #include "asterisk/translate.h"
137 #include "asterisk/version.h"
138 #include "asterisk/event.h"
148 #define XMIT_ERROR -2
150 /* #define VOCAL_DATA_HACK */
152 #define DEFAULT_DEFAULT_EXPIRY 120
153 #define DEFAULT_MIN_EXPIRY 60
154 #define DEFAULT_MAX_EXPIRY 3600
155 #define DEFAULT_REGISTRATION_TIMEOUT 20
156 #define DEFAULT_MAX_FORWARDS "70"
158 /* guard limit must be larger than guard secs */
159 /* guard min must be < 1000, and should be >= 250 */
160 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
161 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
163 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
164 GUARD_PCT turns out to be lower than this, it
165 will use this time instead.
166 This is in milliseconds. */
167 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
168 below EXPIRY_GUARD_LIMIT */
169 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
171 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
172 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
173 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
174 static int expiry = DEFAULT_EXPIRY;
177 #define MAX(a,b) ((a) > (b) ? (a) : (b))
180 #define CALLERID_UNKNOWN "Unknown"
182 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
183 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
184 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
186 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
187 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
188 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
189 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1
190 \todo Use known T1 for timeout (peerpoke)
192 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
193 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
195 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
196 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
197 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
199 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
201 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
202 static struct ast_jb_conf default_jbconf =
206 .resync_threshold = -1,
209 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
211 static const char config[] = "sip.conf"; /*!< Main configuration file */
212 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
217 /*! \brief Authorization scheme for call transfers
218 \note Not a bitfield flag, since there are plans for other modes,
219 like "only allow transfers for authenticated devices" */
221 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
222 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
231 /*! \brief States for the INVITE transaction, not the dialog
232 \note this is for the INVITE that sets up the dialog
235 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
236 INV_CALLING = 1, /*!< Invite sent, no answer */
237 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
238 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
239 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
240 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
241 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
242 The only way out of this is a BYE from one side */
243 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
247 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
248 If it fails, it's critical and will cause a teardown of the session */
249 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
250 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
253 enum parse_register_result {
254 PARSE_REGISTER_FAILED,
255 PARSE_REGISTER_UPDATE,
256 PARSE_REGISTER_QUERY,
259 enum subscriptiontype {
268 /*! \brief Subscription types that we support. We support
269 - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
270 - SIMPLE presence used for device status
271 - Voicemail notification subscriptions
273 static const struct cfsubscription_types {
274 enum subscriptiontype type;
275 const char * const event;
276 const char * const mediatype;
277 const char * const text;
278 } subscription_types[] = {
279 { NONE, "-", "unknown", "unknown" },
280 /* RFC 4235: SIP Dialog event package */
281 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
282 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
283 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
284 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
285 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
289 /*! \brief Authentication types - proxy or www authentication
290 \note Endpoints, like Asterisk, should always use WWW authentication to
291 allow multiple authentications in the same call - to the proxy and
299 /*! \brief Authentication result from check_auth* functions */
300 enum check_auth_result {
301 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
302 /* XXX maybe this is the same as AUTH_NOT_FOUND */
305 AUTH_CHALLENGE_SENT = 1,
306 AUTH_SECRET_FAILED = -1,
307 AUTH_USERNAME_MISMATCH = -2,
308 AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
310 AUTH_UNKNOWN_DOMAIN = -5,
311 AUTH_PEER_NOT_DYNAMIC = -6,
312 AUTH_ACL_FAILED = -7,
315 /*! \brief States for outbound registrations (with register= lines in sip.conf */
316 enum sipregistrystate {
317 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
318 /* Initial state. We should have a timeout scheduled for the initial
319 * (or next) registration transmission, calling sip_reregister
322 REG_STATE_REGSENT, /*!< Registration request sent */
323 /* sent initial request, waiting for an ack or a timeout to
324 * retransmit the initial request.
327 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
328 /* entered after transmit_register with auth info,
329 * waiting for an ack.
332 REG_STATE_REGISTERED, /*!< Registered and done */
334 REG_STATE_REJECTED, /*!< Registration rejected */
335 /* only used when the remote party has an expire larger than
336 * our max-expire. This is a final state from which we do not
337 * recover (not sure how correctly).
340 REG_STATE_TIMEOUT, /*!< Registration timed out */
343 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
344 /* fatal - no chance to proceed */
346 REG_STATE_FAILED, /*!< Registration failed after several tries */
347 /* fatal - no chance to proceed */
350 /*! \brief definition of a sip proxy server
352 * For outbound proxies, this is allocated in the SIP peer dynamically or
353 * statically as the global_outboundproxy. The pointer in a SIP message is just
354 * a pointer and should *not* be de-allocated.
357 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
358 struct sockaddr_in ip; /*!< Currently used IP address and port */
359 time_t last_dnsupdate; /*!< When this was resolved */
360 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
361 /* Room for a SRV record chain based on the name */
364 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
365 enum can_create_dialog {
366 CAN_NOT_CREATE_DIALOG,
368 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
371 /*! \brief SIP Request methods known by Asterisk
373 \note Do _NOT_ make any changes to this enum, or the array following it;
374 if you think you are doing the right thing, you are probably
375 not doing the right thing. If you think there are changes
376 needed, get someone else to review them first _before_
377 submitting a patch. If these two lists do not match properly
378 bad things will happen.
382 SIP_UNKNOWN, /*!< Unknown response */
383 SIP_RESPONSE, /*!< Not request, response to outbound request */
384 SIP_REGISTER, /*!< Registration to the mothership, tell us where you are located */
385 SIP_OPTIONS, /*!< Check capabilities of a device, used for "ping" too */
386 SIP_NOTIFY, /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
387 SIP_INVITE, /*!< Set up a session */
388 SIP_ACK, /*!< End of a three-way handshake started with INVITE. */
389 SIP_PRACK, /*!< Reliable pre-call signalling. Not supported in Asterisk. */
390 SIP_BYE, /*!< End of a session */
391 SIP_REFER, /*!< Refer to another URI (transfer) */
392 SIP_SUBSCRIBE, /*!< Subscribe for updates (voicemail, session status, device status, presence) */
393 SIP_MESSAGE, /*!< Text messaging */
394 SIP_UPDATE, /*!< Update a dialog. We can send UPDATE; but not accept it */
395 SIP_INFO, /*!< Information updates during a session */
396 SIP_CANCEL, /*!< Cancel an INVITE */
397 SIP_PUBLISH, /*!< Not supported in Asterisk */
398 SIP_PING, /*!< Not supported at all, no standard but still implemented out there */
401 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
402 structure and then route the messages according to the type.
404 \note Note that sip_methods[i].id == i must hold or the code breaks */
405 static const struct cfsip_methods {
407 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
409 enum can_create_dialog can_create;
411 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
412 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
413 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
414 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
415 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
416 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
417 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
418 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
419 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
420 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
421 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
422 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
423 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
424 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
425 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
426 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
427 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
430 /*! Define SIP option tags, used in Require: and Supported: headers
431 We need to be aware of these properties in the phones to use
432 the replace: header. We should not do that without knowing
433 that the other end supports it...
434 This is nothing we can configure, we learn by the dialog
435 Supported: header on the REGISTER (peer) or the INVITE
437 We are not using many of these today, but will in the future.
438 This is documented in RFC 3261
441 #define NOT_SUPPORTED 0
444 #define SIP_OPT_REPLACES (1 << 0)
445 #define SIP_OPT_100REL (1 << 1)
446 #define SIP_OPT_TIMER (1 << 2)
447 #define SIP_OPT_EARLY_SESSION (1 << 3)
448 #define SIP_OPT_JOIN (1 << 4)
449 #define SIP_OPT_PATH (1 << 5)
450 #define SIP_OPT_PREF (1 << 6)
451 #define SIP_OPT_PRECONDITION (1 << 7)
452 #define SIP_OPT_PRIVACY (1 << 8)
453 #define SIP_OPT_SDP_ANAT (1 << 9)
454 #define SIP_OPT_SEC_AGREE (1 << 10)
455 #define SIP_OPT_EVENTLIST (1 << 11)
456 #define SIP_OPT_GRUU (1 << 12)
457 #define SIP_OPT_TARGET_DIALOG (1 << 13)
458 #define SIP_OPT_NOREFERSUB (1 << 14)
459 #define SIP_OPT_HISTINFO (1 << 15)
460 #define SIP_OPT_RESPRIORITY (1 << 16)
462 /*! \brief List of well-known SIP options. If we get this in a require,
463 we should check the list and answer accordingly. */
464 static const struct cfsip_options {
465 int id; /*!< Bitmap ID */
466 int supported; /*!< Supported by Asterisk ? */
467 char * const text; /*!< Text id, as in standard */
468 } sip_options[] = { /* XXX used in 3 places */
469 /* RFC3891: Replaces: header for transfer */
470 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
471 /* One version of Polycom firmware has the wrong label */
472 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
473 /* RFC3262: PRACK 100% reliability */
474 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
475 /* RFC4028: SIP Session Timers */
476 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
477 /* RFC3959: SIP Early session support */
478 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
479 /* RFC3911: SIP Join header support */
480 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
481 /* RFC3327: Path support */
482 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
483 /* RFC3840: Callee preferences */
484 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
485 /* RFC3312: Precondition support */
486 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
487 /* RFC3323: Privacy with proxies*/
488 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
489 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
490 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
491 /* RFC3329: Security agreement mechanism */
492 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
493 /* SIMPLE events: RFC4662 */
494 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
495 /* GRUU: Globally Routable User Agent URI's */
496 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
497 /* RFC4538: Target-dialog */
498 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
499 /* Disable the REFER subscription, RFC 4488 */
500 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
501 /* ietf-sip-history-info-06.txt */
502 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
503 /* ietf-sip-resource-priority-10.txt */
504 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
508 /*! \brief SIP Methods we support
509 \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
510 allowsubscribe and allowrefer on in sip.conf.
512 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
514 /*! \brief SIP Extensions we support */
515 #define SUPPORTED_EXTENSIONS "replaces"
517 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
518 #define STANDARD_SIP_PORT 5060
519 /* Note: in many SIP headers, absence of a port number implies port 5060,
520 * and this is why we cannot change the above constant.
521 * There is a limited number of places in asterisk where we could,
522 * in principle, use a different "default" port number, but
523 * we do not support this feature at the moment.
524 * You can run Asterisk with SIP on a different port with a configuration
525 * option. If you change this value, the signalling will be incorrect.
528 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
530 These are default values in the source. There are other recommended values in the
531 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
532 yet encouraging new behaviour on new installations
535 #define DEFAULT_CONTEXT "default"
536 #define DEFAULT_MOHINTERPRET "default"
537 #define DEFAULT_MOHSUGGEST ""
538 #define DEFAULT_VMEXTEN "asterisk"
539 #define DEFAULT_CALLERID "asterisk"
540 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
541 #define DEFAULT_ALLOWGUEST TRUE
542 #define DEFAULT_CALLCOUNTER FALSE
543 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
544 #define DEFAULT_COMPACTHEADERS FALSE
545 #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. */
546 #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. */
547 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
548 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
549 #define DEFAULT_COS_SIP 4
550 #define DEFAULT_COS_AUDIO 5
551 #define DEFAULT_COS_VIDEO 6
552 #define DEFAULT_COS_TEXT 5
553 #define DEFAULT_ALLOW_EXT_DOM TRUE
554 #define DEFAULT_REALM "asterisk"
555 #define DEFAULT_NOTIFYRINGING TRUE
556 #define DEFAULT_PEDANTIC FALSE
557 #define DEFAULT_AUTOCREATEPEER FALSE
558 #define DEFAULT_QUALIFY FALSE
559 #define DEFAULT_REGEXTENONQUALIFY FALSE
560 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
561 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
562 #ifndef DEFAULT_USERAGENT
563 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
564 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
565 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
569 /*! \name DefaultSettings
570 Default setttings are used as a channel setting and as a default when
574 static char default_context[AST_MAX_CONTEXT];
575 static char default_subscribecontext[AST_MAX_CONTEXT];
576 static char default_language[MAX_LANGUAGE];
577 static char default_callerid[AST_MAX_EXTENSION];
578 static char default_fromdomain[AST_MAX_EXTENSION];
579 static char default_notifymime[AST_MAX_EXTENSION];
580 static int default_qualify; /*!< Default Qualify= setting */
581 static char default_vmexten[AST_MAX_EXTENSION];
582 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
583 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
584 * a bridged channel on hold */
585 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
586 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
588 /*! \brief a place to store all global settings for the sip channel driver */
589 struct sip_settings {
590 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
591 int rtsave_sysname; /*!< G: Save system name at registration? */
592 int ignore_regexpire; /*!< G: Ignore expiration of peer */
595 static struct sip_settings sip_cfg;
598 /*! \name GlobalSettings
599 Global settings apply to the channel (often settings you can change in the general section
603 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
604 static int global_limitonpeers; /*!< Match call limit on peers only */
605 static int global_rtautoclear; /*!< Realtime ?? */
606 static int global_notifyringing; /*!< Send notifications on ringing */
607 static int global_notifyhold; /*!< Send notifications on hold */
608 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
609 static int global_srvlookup; /*!< SRV Lookup on or off. Default is on */
610 static int pedanticsipchecking; /*!< Extra checking ? Default off */
611 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
612 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
613 static int global_relaxdtmf; /*!< Relax DTMF */
614 static int global_rtptimeout; /*!< Time out call if no RTP */
615 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
616 static int global_rtpkeepalive; /*!< Send RTP keepalives */
617 static int global_reg_timeout;
618 static int global_regattempts_max; /*!< Registration attempts before giving up */
619 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
620 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
621 call-limit to 999. When we remove the call-limit from the code, we can make it
622 with just a boolean flag in the device structure */
623 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
624 the global setting is in globals_flags[1] */
625 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
626 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
627 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
628 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
629 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
630 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
631 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
632 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
633 static int compactheaders; /*!< send compact sip headers */
634 static int recordhistory; /*!< Record SIP history. Off by default */
635 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
636 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
637 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
638 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
639 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
640 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
641 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
642 static int global_callevents; /*!< Whether we send manager events or not */
643 static int global_t1; /*!< T1 time */
644 static int global_t1min; /*!< T1 roundtrip time minimum */
645 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
646 static int global_regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
647 static int global_autoframing; /*!< Turn autoframing on or off. */
648 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
649 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
651 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
653 /*! \brief Codecs that we support by default: */
654 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
657 /* Object counters */
658 static int suserobjs = 0; /*!< Static users */
659 static int ruserobjs = 0; /*!< Realtime users */
660 static int speerobjs = 0; /*!< Statis peers */
661 static int rpeerobjs = 0; /*!< Realtime peers */
662 static int apeerobjs = 0; /*!< Autocreated peer objects */
663 static int regobjs = 0; /*!< Registry objects */
665 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
666 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
668 AST_MUTEX_DEFINE_STATIC(netlock);
670 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
671 when it's doing something critical. */
673 AST_MUTEX_DEFINE_STATIC(monlock);
675 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
677 /*! \brief This is the thread for the monitor which checks for input on the channels
678 which are not currently in use. */
679 static pthread_t monitor_thread = AST_PTHREADT_NULL;
681 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
682 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
684 static struct sched_context *sched; /*!< The scheduling context */
685 static struct io_context *io; /*!< The IO context */
686 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
688 #define DEC_CALL_LIMIT 0
689 #define INC_CALL_LIMIT 1
690 #define DEC_CALL_RINGING 2
691 #define INC_CALL_RINGING 3
693 /*! \brief The data grabbed from the UDP socket
695 * Incoming messages: we first store the data from the socket in data[],
696 * adding a trailing \0 to make string parsing routines happy.
697 * Then call parse_request() and req.method = find_sip_method();
698 * to initialize the other fields. The \r\n at the end of each line is
699 * replaced by \0, so that data[] is not a conforming SIP message anymore.
700 * After this processing, rlPart1 is set to non-NULL to remember
701 * that we can run get_header() on this kind of packet.
703 * parse_request() splits the first line as follows:
704 * Requests have in the first line method uri SIP/2.0
705 * rlPart1 = method; rlPart2 = uri;
706 * Responses have in the first line SIP/2.0 NNN description
707 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
709 * For outgoing packets, we initialize the fields with init_req() or init_resp()
710 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
711 * and then fill the rest with add_header() and add_line().
712 * The \r\n at the end of the line are still there, so the get_header()
713 * and similar functions don't work on these packets.
717 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
718 char *rlPart2; /*!< The Request URI or Response Status */
719 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
720 int headers; /*!< # of SIP Headers */
721 int method; /*!< Method of this request */
722 int lines; /*!< Body Content */
723 unsigned int sdp_start; /*!< the line number where the SDP begins */
724 unsigned int sdp_end; /*!< the line number where the SDP ends */
725 char debug; /*!< print extra debugging if non zero */
726 char has_to_tag; /*!< non-zero if packet has To: tag */
727 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
728 char *header[SIP_MAX_HEADERS];
729 char *line[SIP_MAX_LINES];
730 char data[SIP_MAX_PACKET];
733 /*! \brief structure used in transfers */
735 struct ast_channel *chan1; /*!< First channel involved */
736 struct ast_channel *chan2; /*!< Second channel involved */
737 struct sip_request req; /*!< Request that caused the transfer (REFER) */
738 int seqno; /*!< Sequence number */
743 /*! \brief Parameters to the transmit_invite function */
744 struct sip_invite_param {
745 int addsipheaders; /*!< Add extra SIP headers */
746 const char *uri_options; /*!< URI options to add to the URI */
747 const char *vxml_url; /*!< VXML url for Cisco phones */
748 char *auth; /*!< Authentication */
749 char *authheader; /*!< Auth header */
750 enum sip_auth_type auth_type; /*!< Authentication type */
751 const char *replaces; /*!< Replaces header for call transfers */
752 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
755 /*! \brief Structure to save routing information for a SIP session */
757 struct sip_route *next;
761 /*! \brief Modes for SIP domain handling in the PBX */
763 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
764 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
767 /*! \brief Domain data structure.
768 \note In the future, we will connect this to a configuration tree specific
772 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
773 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
774 enum domain_mode mode; /*!< How did we find this domain? */
775 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
778 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
781 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
783 AST_LIST_ENTRY(sip_history) list;
784 char event[0]; /* actually more, depending on needs */
787 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
789 /*! \brief sip_auth: Credentials for authentication to other SIP services */
791 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
792 char username[256]; /*!< Username */
793 char secret[256]; /*!< Secret */
794 char md5secret[256]; /*!< MD5Secret */
795 struct sip_auth *next; /*!< Next auth structure in list */
799 Various flags for the flags field in the pvt structure
800 Trying to sort these up (one or more of the following):
804 When flags are used by multiple structures, it is important that
805 they have a common layout so it is easy to copy them.
808 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
809 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
810 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
811 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
812 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
813 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
814 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
815 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
816 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
817 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 11) /*!< D: Do not hangup at first ast_hangup */
819 #define SIP_PROMISCREDIR (1 << 12) /*!< DP: Promiscuous redirection */
820 #define SIP_TRUSTRPID (1 << 13) /*!< DP: Trust RPID headers? */
821 #define SIP_USEREQPHONE (1 << 14) /*!< DP: Add user=phone to numeric URI. Default off */
822 #define SIP_USECLIENTCODE (1 << 15) /*!< DP: Trust X-ClientCode info message */
824 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
825 #define SIP_DTMF (3 << 16) /*!< DP: DTMF Support: four settings, uses two bits */
826 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
827 #define SIP_DTMF_INBAND (1 << 16) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
828 #define SIP_DTMF_INFO (2 << 16) /*!< DP: DTMF Support: SIP Info messages - "info" */
829 #define SIP_DTMF_AUTO (3 << 16) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
830 #define SIP_DTMF_SHORTINFO (4 << 16) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
832 /* NAT settings - see nat2str() */
833 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
834 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
835 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
836 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
837 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
839 /* re-INVITE related settings */
840 #define SIP_REINVITE (7 << 20) /*!< DP: three bits used */
841 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
842 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
843 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
845 /* "insecure" settings - see insecure2str() */
846 #define SIP_INSECURE (3 << 23) /*!< DP: two bits used */
847 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
848 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
850 /* Sending PROGRESS in-band settings */
851 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
852 #define SIP_PROG_INBAND_NEVER (0 << 25)
853 #define SIP_PROG_INBAND_NO (1 << 25)
854 #define SIP_PROG_INBAND_YES (2 << 25)
856 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
857 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
859 /*! \brief Flags to copy from peer/user to dialog */
860 #define SIP_FLAGS_TO_COPY \
861 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
862 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
863 SIP_USEREQPHONE | SIP_INSECURE)
867 a second page of flags (for flags[1] */
870 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
871 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
872 /* Space for addition of other realtime flags in the future */
874 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14) /*!< DP: Video supported if offered? */
875 #define SIP_PAGE2_TEXTSUPPORT (1 << 15) /*!< GDP: Global text enable */
876 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
877 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
878 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
880 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
881 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
882 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
883 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
885 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
886 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
887 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
888 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
890 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
891 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
892 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
894 #define SIP_PAGE2_FLAGS_TO_COPY \
895 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
896 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
897 SIP_PAGE2_TEXTSUPPORT )
901 /*! \name SIPflagsT38
905 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
906 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
907 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
908 /* Rate management */
909 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
910 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
911 /* UDP Error correction */
912 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
913 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
914 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
915 /* T38 Spec version */
916 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
917 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
918 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
919 /* Maximum Fax Rate */
920 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
921 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
922 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
923 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
924 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
925 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
927 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
928 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
931 /*! \brief debugging state
932 * We store separately the debugging requests from the config file
933 * and requests from the CLI. Debugging is enabled if either is set
934 * (which means that if sipdebug is set in the config file, we can
935 * only turn it off by reloading the config).
939 sip_debug_config = 1,
940 sip_debug_console = 2,
943 static enum sip_debug_e sipdebug;
945 /*! \brief extra debugging for 'text' related events.
946 * At thie moment this is set together with sip_debug_console.
947 * It should either go away or be implemented properly.
949 static int sipdebug_text;
951 /*! \brief T38 States for a call */
953 T38_DISABLED = 0, /*!< Not enabled */
954 T38_LOCAL_DIRECT, /*!< Offered from local */
955 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
956 T38_PEER_DIRECT, /*!< Offered from peer */
957 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
958 T38_ENABLED /*!< Negotiated (enabled) */
961 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
962 struct t38properties {
963 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
964 int capability; /*!< Our T38 capability */
965 int peercapability; /*!< Peers T38 capability */
966 int jointcapability; /*!< Supported T38 capability at both ends */
967 enum t38state state; /*!< T.38 state */
970 /*! \brief Parameters to know status of transfer */
972 REFER_IDLE, /*!< No REFER is in progress */
973 REFER_SENT, /*!< Sent REFER to transferee */
974 REFER_RECEIVED, /*!< Received REFER from transferrer */
975 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
976 REFER_ACCEPTED, /*!< Accepted by transferee */
977 REFER_RINGING, /*!< Target Ringing */
978 REFER_200OK, /*!< Answered by transfer target */
979 REFER_FAILED, /*!< REFER declined - go on */
980 REFER_NOAUTH /*!< We had no auth for REFER */
983 /*! \brief generic struct to map between strings and integers.
984 * Fill it with x-s pairs, terminate with an entry with s = NULL;
985 * Then you can call map_x_s(...) to map an integer to a string,
986 * and map_s_x() for the string -> integer mapping.
993 static const struct _map_x_s referstatusstrings[] = {
994 { REFER_IDLE, "<none>" },
995 { REFER_SENT, "Request sent" },
996 { REFER_RECEIVED, "Request received" },
997 { REFER_CONFIRMED, "Confirmed" },
998 { REFER_ACCEPTED, "Accepted" },
999 { REFER_RINGING, "Target ringing" },
1000 { REFER_200OK, "Done" },
1001 { REFER_FAILED, "Failed" },
1002 { REFER_NOAUTH, "Failed - auth failure" },
1003 { -1, NULL} /* terminator */
1006 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1007 \note OEJ: Should be moved to string fields */
1009 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
1010 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
1011 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
1012 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
1013 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1014 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1015 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
1016 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
1017 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
1018 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
1019 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
1020 * dialog owned by someone else, so we should not destroy
1021 * it when the sip_refer object goes.
1023 int attendedtransfer; /*!< Attended or blind transfer? */
1024 int localtransfer; /*!< Transfer to local domain? */
1025 enum referstatus status; /*!< REFER status */
1028 /*! \brief sip_pvt: structures used for each SIP dialog, ie. a call, a registration, a subscribe.
1029 * Created and initialized by sip_alloc(), the descriptor goes into the list of
1030 * descriptors (dialoglist).
1033 struct sip_pvt *next; /*!< Next dialog in chain */
1034 ast_mutex_t pvt_lock; /*!< Dialog private lock */
1035 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
1036 int method; /*!< SIP method that opened this dialog */
1037 AST_DECLARE_STRING_FIELDS(
1038 AST_STRING_FIELD(callid); /*!< Global CallID */
1039 AST_STRING_FIELD(randdata); /*!< Random data */
1040 AST_STRING_FIELD(accountcode); /*!< Account code */
1041 AST_STRING_FIELD(realm); /*!< Authorization realm */
1042 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1043 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1044 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1045 AST_STRING_FIELD(domain); /*!< Authorization domain */
1046 AST_STRING_FIELD(from); /*!< The From: header */
1047 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1048 AST_STRING_FIELD(exten); /*!< Extension where to start */
1049 AST_STRING_FIELD(context); /*!< Context for this call */
1050 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1051 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1052 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1053 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1054 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1055 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1056 AST_STRING_FIELD(todnid); /*!< DNID of this call (overrides host) */
1057 AST_STRING_FIELD(language); /*!< Default language for this call */
1058 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1059 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1060 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1061 AST_STRING_FIELD(redircause); /*!< Referring cause */
1062 AST_STRING_FIELD(theirtag); /*!< Their tag */
1063 AST_STRING_FIELD(username); /*!< [user] name */
1064 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1065 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1066 AST_STRING_FIELD(uri); /*!< Original requested URI */
1067 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1068 AST_STRING_FIELD(peersecret); /*!< Password */
1069 AST_STRING_FIELD(peermd5secret);
1070 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1071 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1072 AST_STRING_FIELD(via); /*!< Via: header */
1073 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1074 /* we only store the part in <brackets> in this field. */
1075 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1076 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1077 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1078 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1080 unsigned int ocseq; /*!< Current outgoing seqno */
1081 unsigned int icseq; /*!< Current incoming seqno */
1082 ast_group_t callgroup; /*!< Call group */
1083 ast_group_t pickupgroup; /*!< Pickup group */
1084 int lastinvite; /*!< Last Cseq of invite */
1085 int lastnoninvite; /*!< Last Cseq of non-invite */
1086 struct ast_flags flags[2]; /*!< SIP_ flags */
1088 /* boolean or small integers that don't belong in flags */
1089 char do_history; /*!< Set if we want to record history */
1090 char alreadygone; /*!< already destroyed by our peer */
1091 char needdestroy; /*!< need to be destroyed by the monitor thread */
1092 char outgoing_call; /*!< this is an outgoing call */
1093 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1094 char novideo; /*!< Didn't get video in invite, don't offer */
1095 char notext; /*!< Text not supported (?) */
1097 int timer_t1; /*!< SIP timer T1, ms rtt */
1098 int timer_b; /*!< SIP timer B, ms */
1099 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1100 struct ast_codec_pref prefs; /*!< codec prefs */
1101 int capability; /*!< Special capability (codec) */
1102 int jointcapability; /*!< Supported capability at both ends (codecs) */
1103 int peercapability; /*!< Supported peer capability */
1104 int prefcodec; /*!< Preferred codec (outbound only) */
1105 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1106 int jointnoncodeccapability; /*!< Joint Non codec capability */
1107 int redircodecs; /*!< Redirect codecs */
1108 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1109 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
1110 struct t38properties t38; /*!< T38 settings */
1111 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1112 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1113 int callingpres; /*!< Calling presentation */
1114 int authtries; /*!< Times we've tried to authenticate */
1115 int expiry; /*!< How long we take to expire */
1116 long branch; /*!< The branch identifier of this session */
1117 char tag[11]; /*!< Our tag for this session */
1118 int sessionid; /*!< SDP Session ID */
1119 int sessionversion; /*!< SDP Session Version */
1120 struct sockaddr_in sa; /*!< Our peer */
1121 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1122 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1123 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1124 time_t lastrtprx; /*!< Last RTP received */
1125 time_t lastrtptx; /*!< Last RTP sent */
1126 int rtptimeout; /*!< RTP timeout time */
1127 struct sockaddr_in recv; /*!< Received as */
1128 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1129 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1130 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1131 int route_persistant; /*!< Is this the "real" route? */
1132 struct sip_auth *peerauth; /*!< Realm authentication */
1133 int noncecount; /*!< Nonce-count */
1134 char lastmsg[256]; /*!< Last Message sent/received */
1135 int amaflags; /*!< AMA Flags */
1136 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
1137 struct sip_request initreq; /*!< Latest request that opened a new transaction
1139 NOT the request that opened the dialog
1142 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1143 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1144 int autokillid; /*!< Auto-kill ID (scheduler) */
1145 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1146 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1147 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1148 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1149 int laststate; /*!< SUBSCRIBE: Last known extension state */
1150 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1152 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1154 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1155 Used in peerpoke, mwi subscriptions */
1156 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1157 struct ast_rtp *rtp; /*!< RTP Session */
1158 struct ast_rtp *vrtp; /*!< Video RTP session */
1159 struct ast_rtp *trtp; /*!< Text RTP session */
1160 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1161 struct sip_history_head *history; /*!< History of this SIP dialog */
1162 size_t history_entries; /*!< Number of entires in the history */
1163 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1164 struct sip_invite_param *options; /*!< Options for INVITE */
1165 int autoframing; /*!< The number of Asters we group in a Pyroflax
1166 before strolling to the Grokyzpå
1167 (A bit unsure of this, please correct if
1171 /*! Max entires in the history list for a sip_pvt */
1172 #define MAX_HISTORY_ENTRIES 50
1175 * Here we implement the container for dialogs (sip_pvt), defining
1176 * generic wrapper functions to ease the transition from the current
1177 * implementation (a single linked list) to a different container.
1178 * In addition to a reference to the container, we need functions to lock/unlock
1179 * the container and individual items, and functions to add/remove
1180 * references to the individual items.
1182 static struct sip_pvt *dialoglist = NULL;
1184 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1185 AST_MUTEX_DEFINE_STATIC(dialoglock);
1187 #ifndef DETECT_DEADLOCKS
1188 /*! \brief hide the way the list is locked/unlocked */
1189 static void dialoglist_lock(void)
1191 ast_mutex_lock(&dialoglock);
1194 static void dialoglist_unlock(void)
1196 ast_mutex_unlock(&dialoglock);
1199 /* we don't want to HIDE the information about where the lock was requested if trying to debug
1200 * deadlocks! So, just make these macros! */
1201 #define dialoglist_lock(x) ast_mutex_lock(&dialoglock)
1202 #define dialoglist_unlock(x) ast_mutex_unlock(&dialoglock)
1206 * when we create or delete references, make sure to use these
1207 * functions so we keep track of the refcounts.
1208 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1210 static struct sip_pvt *dialog_ref(struct sip_pvt *p)
1215 static struct sip_pvt *dialog_unref(struct sip_pvt *p)
1220 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1221 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1222 * Each packet holds a reference to the parent struct sip_pvt.
1223 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1224 * require retransmissions.
1227 struct sip_pkt *next; /*!< Next packet in linked list */
1228 int retrans; /*!< Retransmission number */
1229 int method; /*!< SIP method for this packet */
1230 int seqno; /*!< Sequence number */
1231 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1232 char is_fatal; /*!< non-zero if there is a fatal error */
1233 struct sip_pvt *owner; /*!< Owner AST call */
1234 int retransid; /*!< Retransmission ID */
1235 int timer_a; /*!< SIP timer A, retransmission timer */
1236 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1237 int packetlen; /*!< Length of packet */
1241 /*! \brief Structure for SIP user data. User's place calls to us */
1243 /* Users who can access various contexts */
1244 ASTOBJ_COMPONENTS(struct sip_user);
1245 char secret[80]; /*!< Password */
1246 char md5secret[80]; /*!< Password in md5 */
1247 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1248 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1249 char cid_num[80]; /*!< Caller ID num */
1250 char cid_name[80]; /*!< Caller ID name */
1251 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1252 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1253 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1254 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1255 char useragent[256]; /*!< User agent in SIP request */
1256 struct ast_codec_pref prefs; /*!< codec prefs */
1257 ast_group_t callgroup; /*!< Call group */
1258 ast_group_t pickupgroup; /*!< Pickup Group */
1259 unsigned int sipoptions; /*!< Supported SIP options */
1260 struct ast_flags flags[2]; /*!< SIP_ flags */
1262 /* things that don't belong in flags */
1263 char is_realtime; /*!< this is a 'realtime' user */
1265 int amaflags; /*!< AMA flags for billing */
1266 int callingpres; /*!< Calling id presentation */
1267 int capability; /*!< Codec capability */
1268 int inUse; /*!< Number of calls in use */
1269 int call_limit; /*!< Limit of concurrent calls */
1270 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1271 struct ast_ha *ha; /*!< ACL setting */
1272 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1273 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1278 * \brief A peer's mailbox
1280 * We could use STRINGFIELDS here, but for only two strings, it seems like
1281 * too much effort ...
1283 struct sip_mailbox {
1286 /*! Associated MWI subscription */
1287 struct ast_event_sub *event_sub;
1288 AST_LIST_ENTRY(sip_mailbox) entry;
1291 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1292 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1294 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1295 /*!< peer->name is the unique name of this object */
1296 char secret[80]; /*!< Password */
1297 char md5secret[80]; /*!< Password in MD5 */
1298 struct sip_auth *auth; /*!< Realm authentication list */
1299 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1300 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1301 char username[80]; /*!< Temporary username until registration */
1302 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1303 int amaflags; /*!< AMA Flags (for billing) */
1304 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1305 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1306 char fromuser[80]; /*!< From: user when calling this peer */
1307 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1308 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1309 char cid_num[80]; /*!< Caller ID num */
1310 char cid_name[80]; /*!< Caller ID name */
1311 int callingpres; /*!< Calling id presentation */
1312 int inUse; /*!< Number of calls in use */
1313 int inRinging; /*!< Number of calls ringing */
1314 int onHold; /*!< Peer has someone on hold */
1315 int call_limit; /*!< Limit of concurrent calls */
1316 int busy_level; /*!< Level of active channels where we signal busy */
1317 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1318 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1319 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1320 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1321 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1322 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1323 struct ast_codec_pref prefs; /*!< codec prefs */
1325 unsigned int sipoptions; /*!< Supported SIP options */
1326 struct ast_flags flags[2]; /*!< SIP_ flags */
1328 /*! Mailboxes that this peer cares about */
1329 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1331 /* things that don't belong in flags */
1332 char is_realtime; /*!< this is a 'realtime' peer */
1333 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1334 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1335 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1337 int expire; /*!< When to expire this peer registration */
1338 int capability; /*!< Codec capability */
1339 int rtptimeout; /*!< RTP timeout */
1340 int rtpholdtimeout; /*!< RTP Hold Timeout */
1341 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1342 ast_group_t callgroup; /*!< Call group */
1343 ast_group_t pickupgroup; /*!< Pickup group */
1344 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1345 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1346 struct sockaddr_in addr; /*!< IP address of peer */
1347 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1350 struct sip_pvt *call; /*!< Call pointer */
1351 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1352 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1353 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1354 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1355 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1356 struct ast_ha *ha; /*!< Access control list */
1357 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1358 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1360 int timer_t1; /*!< The maximum T1 value for the peer */
1361 int timer_b; /*!< The maximum timer B (transaction timeouts) */
1365 /*! \brief Registrations with other SIP proxies
1366 * Created by sip_register(), the entry is linked in the 'regl' list,
1367 * and never deleted (other than at 'sip reload' or module unload times).
1368 * The entry always has a pending timeout, either waiting for an ACK to
1369 * the REGISTER message (in which case we have to retransmit the request),
1370 * or waiting for the next REGISTER message to be sent (either the initial one,
1371 * or once the previously completed registration one expires).
1372 * The registration can be in one of many states, though at the moment
1373 * the handling is a bit mixed.
1374 * Note that the entire evolution of sip_registry (transmissions,
1375 * incoming packets and timeouts) is driven by one single thread,
1376 * do_monitor(), so there is almost no synchronization issue.
1377 * The only exception is the sip_pvt creation/lookup,
1378 * as the dialoglist is also manipulated by other threads.
1380 struct sip_registry {
1381 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1382 AST_DECLARE_STRING_FIELDS(
1383 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1384 AST_STRING_FIELD(realm); /*!< Authorization realm */
1385 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1386 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1387 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1388 AST_STRING_FIELD(domain); /*!< Authorization domain */
1389 AST_STRING_FIELD(username); /*!< Who we are registering as */
1390 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1391 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1392 AST_STRING_FIELD(secret); /*!< Password in clear text */
1393 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1394 AST_STRING_FIELD(callback); /*!< Contact extension */
1395 AST_STRING_FIELD(random);
1397 int portno; /*!< Optional port override */
1398 int expire; /*!< Sched ID of expiration */
1399 int expiry; /*!< Value to use for the Expires header */
1400 int regattempts; /*!< Number of attempts (since the last success) */
1401 int timeout; /*!< sched id of sip_reg_timeout */
1402 int refresh; /*!< How often to refresh */
1403 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1404 enum sipregistrystate regstate; /*!< Registration state (see above) */
1405 struct timeval regtime; /*!< Last successful registration time */
1406 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1407 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1408 struct sockaddr_in us; /*!< Who the server thinks we are */
1409 int noncecount; /*!< Nonce-count */
1410 char lastmsg[256]; /*!< Last Message sent/received */
1413 /* --- Linked lists of various objects --------*/
1415 /*! \brief The user list: Users and friends */
1416 static struct ast_user_list {
1417 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1420 /*! \brief The peer list: Peers and Friends */
1421 static struct ast_peer_list {
1422 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1425 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1426 static struct ast_register_list {
1427 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1431 static int temp_pvt_init(void *);
1432 static void temp_pvt_cleanup(void *);
1434 /*! \brief A per-thread temporary pvt structure */
1435 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1437 /*! \brief Authentication list for realm authentication
1438 * \todo Move the sip_auth list to AST_LIST */
1439 static struct sip_auth *authl = NULL;
1442 /* --- Sockets and networking --------------*/
1444 /*! \brief Main socket for SIP communication.
1445 * sipsock is shared between the manager thread (which handles reload
1446 * requests), the io handler (sipsock_read()) and the user routines that
1447 * issue writes (using __sip_xmit()).
1448 * The socket is -1 only when opening fails (this is a permanent condition),
1449 * or when we are handling a reload() that changes its address (this is
1450 * a transient situation during which we might have a harmless race, see
1451 * below). Because the conditions for the race to be possible are extremely
1452 * rare, we don't want to pay the cost of locking on every I/O.
1453 * Rather, we remember that when the race may occur, communication is
1454 * bound to fail anyways, so we just live with this event and let
1455 * the protocol handle this above us.
1457 static int sipsock = -1;
1459 static struct sockaddr_in bindaddr; /*!< The address we bind to */
1461 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1462 * internip is initialized picking a suitable address from one of the
1463 * interfaces, and the same port number we bind to. It is used as the
1464 * default address/port in SIP messages, and as the default address
1465 * (but not port) in SDP messages.
1467 static struct sockaddr_in internip;
1469 /*! \brief our external IP address/port for SIP sessions.
1470 * externip.sin_addr is only set when we know we might be behind
1471 * a NAT, and this is done using a variety of (mutually exclusive)
1472 * ways from the config file:
1474 * + with "externip = host[:port]" we specify the address/port explicitly.
1475 * The address is looked up only once when (re)loading the config file;
1477 * + with "externhost = host[:port]" we do a similar thing, but the
1478 * hostname is stored in externhost, and the hostname->IP mapping
1479 * is refreshed every 'externrefresh' seconds;
1481 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1482 * to the specified server, and store the result in externip.
1484 * Other variables (externhost, externexpire, externrefresh) are used
1485 * to support the above functions.
1487 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1489 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1490 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1491 static int externrefresh = 10;
1492 static struct sockaddr_in stunaddr; /*!< stun server address */
1494 /*! \brief List of local networks
1495 * We store "localnet" addresses from the config file into an access list,
1496 * marked as 'DENY', so the call to ast_apply_ha() will return
1497 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1498 * (i.e. presumably public) addresses.
1500 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1502 static struct sockaddr_in debugaddr;
1504 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1506 /*! some list management macros. */
1508 #define UNLINK(element, head, prev) do { \
1510 (prev)->next = (element)->next; \
1512 (head) = (element)->next; \
1515 /*---------------------------- Forward declarations of functions in chan_sip.c */
1516 /*! \note This is added to help splitting up chan_sip.c into several files
1517 in coming releases */
1519 /*--- PBX interface functions */
1520 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1521 static int sip_devicestate(void *data);
1522 static int sip_sendtext(struct ast_channel *ast, const char *text);
1523 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1524 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1525 static int sip_hangup(struct ast_channel *ast);
1526 static int sip_answer(struct ast_channel *ast);
1527 static struct ast_frame *sip_read(struct ast_channel *ast);
1528 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1529 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1530 static int sip_transfer(struct ast_channel *ast, const char *dest);
1531 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1532 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1533 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1535 /*--- Transmitting responses and requests */
1536 static int sipsock_read(int *id, int fd, short events, void *ignore);
1537 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1538 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1539 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1540 static int retrans_pkt(const void *data);
1541 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1542 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);
1543 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1544 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1545 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1546 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1547 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1548 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);
1549 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1550 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1551 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1552 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1553 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1554 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1555 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1556 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1557 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1558 static int transmit_refer(struct sip_pvt *p, const char *dest);
1559 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1560 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1561 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1562 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1563 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1564 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1565 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1566 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1567 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1569 /*--- Dialog management */
1570 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1571 int useglobal_nat, const int intended_method);
1572 static int __sip_autodestruct(const void *data);
1573 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1574 static void sip_cancel_destroy(struct sip_pvt *p);
1575 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1576 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1577 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1578 static void __sip_pretend_ack(struct sip_pvt *p);
1579 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1580 static int auto_congest(const void *arg);
1581 static int update_call_counter(struct sip_pvt *fup, int event);
1582 static int hangup_sip2cause(int cause);
1583 static const char *hangup_cause2sip(int cause);
1584 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1585 static void free_old_route(struct sip_route *route);
1586 static void list_route(struct sip_route *route);
1587 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1588 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1589 struct sip_request *req, char *uri);
1590 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1591 static void check_pendings(struct sip_pvt *p);
1592 static void *sip_park_thread(void *stuff);
1593 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1594 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1596 /*--- Codec handling / SDP */
1597 static void try_suggested_sip_codec(struct sip_pvt *p);
1598 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1599 static const char *get_sdp(struct sip_request *req, const char *name);
1600 static int find_sdp(struct sip_request *req);
1601 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1602 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1603 struct ast_str **m_buf, struct ast_str **a_buf,
1604 int debug, int *min_packet_size);
1605 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1606 struct ast_str **m_buf, struct ast_str **a_buf,
1608 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1609 static void do_setnat(struct sip_pvt *p, int natflags);
1610 static void stop_media_flows(struct sip_pvt *p);
1612 /*--- Authentication stuff */
1613 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1614 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1615 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1616 const char *secret, const char *md5secret, int sipmethod,
1617 char *uri, enum xmittype reliable, int ignore);
1618 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1619 int sipmethod, char *uri, enum xmittype reliable,
1620 struct sockaddr_in *sin, struct sip_peer **authpeer);
1621 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1623 /*--- Domain handling */
1624 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1625 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1626 static void clear_sip_domains(void);
1628 /*--- SIP realm authentication */
1629 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1630 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1631 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1633 /*--- Misc functions */
1634 static int sip_do_reload(enum channelreloadreason reason);
1635 static int reload_config(enum channelreloadreason reason);
1636 static int expire_register(const void *data);
1637 static void *do_monitor(void *data);
1638 static int restart_monitor(void);
1639 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1640 static int sip_refer_allocate(struct sip_pvt *p);
1641 static void ast_quiet_chan(struct ast_channel *chan);
1642 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1644 /*--- Device monitoring and Device/extension state/event handling */
1645 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1646 static int sip_devicestate(void *data);
1647 static int sip_poke_noanswer(const void *data);
1648 static int sip_poke_peer(struct sip_peer *peer);
1649 static void sip_poke_all_peers(void);
1650 static void sip_peer_hold(struct sip_pvt *p, int hold);
1651 static void mwi_event_cb(const struct ast_event *, void *);
1653 /*--- Applications, functions, CLI and manager command helpers */
1654 static const char *sip_nat_mode(const struct sip_pvt *p);
1655 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1656 static char *transfermode2str(enum transfermodes mode) attribute_const;
1657 static const char *nat2str(int nat) attribute_const;
1658 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1659 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1660 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1661 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1662 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1663 static void print_group(int fd, ast_group_t group, int crlf);
1664 static const char *dtmfmode2str(int mode) attribute_const;
1665 static int str2dtmfmode(const char *str) attribute_unused;
1666 static const char *insecure2str(int mode) attribute_const;
1667 static void cleanup_stale_contexts(char *new, char *old);
1668 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1669 static const char *domain_mode_to_text(const enum domain_mode mode);
1670 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1671 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1672 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1673 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1674 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1675 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1676 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1677 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1678 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1679 static char *complete_sip_peer(const char *word, int state, int flags2);
1680 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1681 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1682 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1683 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1684 static char *complete_sip_user(const char *word, int state, int flags2);
1685 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1686 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1687 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1688 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1689 static char *sip_do_debug_ip(int fd, char *arg);
1690 static char *sip_do_debug_peer(int fd, char *arg);
1691 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1692 static char *sip_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1693 static char *sip_do_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1694 static char *sip_no_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1695 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1696 static int sip_addheader(struct ast_channel *chan, void *data);
1697 static int sip_do_reload(enum channelreloadreason reason);
1698 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1699 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1702 Functions for enabling debug per IP or fully, or enabling history logging for
1705 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1706 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1707 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1708 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1709 static void sip_dump_history(struct sip_pvt *dialog);
1711 /*--- Device object handling */
1712 static struct sip_peer *temp_peer(const char *name);
1713 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1714 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1715 static int update_call_counter(struct sip_pvt *fup, int event);
1716 static void sip_destroy_peer(struct sip_peer *peer);
1717 static void sip_destroy_user(struct sip_user *user);
1718 static int sip_poke_peer(struct sip_peer *peer);
1719 static void set_peer_defaults(struct sip_peer *peer);
1720 static struct sip_peer *temp_peer(const char *name);
1721 static void register_peer_exten(struct sip_peer *peer, int onoff);
1722 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1723 static struct sip_user *find_user(const char *name, int realtime);
1724 static int sip_poke_peer_s(const void *data);
1725 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1726 static void reg_source_db(struct sip_peer *peer);
1727 static void destroy_association(struct sip_peer *peer);
1728 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1729 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1731 /* Realtime device support */
1732 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1733 static struct sip_user *realtime_user(const char *username);
1734 static void update_peer(struct sip_peer *p, int expiry);
1735 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1736 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1737 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1738 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1740 /*--- Internal UA client handling (outbound registrations) */
1741 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
1742 static void sip_registry_destroy(struct sip_registry *reg);
1743 static int sip_register(const char *value, int lineno);
1744 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1745 static int sip_reregister(const void *data);
1746 static int __sip_do_register(struct sip_registry *r);
1747 static int sip_reg_timeout(const void *data);
1748 static void sip_send_all_registers(void);
1750 /*--- Parsing SIP requests and responses */
1751 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1752 static int determine_firstline_parts(struct sip_request *req);
1753 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1754 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1755 static int find_sip_method(const char *msg);
1756 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1757 static void parse_request(struct sip_request *req);
1758 static const char *get_header(const struct sip_request *req, const char *name);
1759 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1760 static int method_match(enum sipmethod id, const char *name);
1761 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1762 static char *get_in_brackets(char *tmp);
1763 static const char *find_alias(const char *name, const char *_default);
1764 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1765 static int lws2sws(char *msgbuf, int len);
1766 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1767 static char *remove_uri_parameters(char *uri);
1768 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1769 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1770 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1771 static int set_address_from_contact(struct sip_pvt *pvt);
1772 static void check_via(struct sip_pvt *p, struct sip_request *req);
1773 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1774 static int get_rpid_num(const char *input, char *output, int maxlen);
1775 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1776 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1777 static int get_msg_text(char *buf, int len, struct sip_request *req);
1778 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1780 /*--- Constructing requests and responses */
1781 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1782 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1783 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1784 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1785 static int init_resp(struct sip_request *resp, const char *msg);
1786 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1787 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1788 static void build_via(struct sip_pvt *p);
1789 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1790 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1791 static char *generate_random_string(char *buf, size_t size);
1792 static void build_callid_pvt(struct sip_pvt *pvt);
1793 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1794 static void make_our_tag(char *tagbuf, size_t len);
1795 static int add_header(struct sip_request *req, const char *var, const char *value);
1796 static int add_header_contentLength(struct sip_request *req, int len);
1797 static int add_line(struct sip_request *req, const char *line);
1798 static int add_text(struct sip_request *req, const char *text);
1799 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1800 static int add_vidupdate(struct sip_request *req);
1801 static void add_route(struct sip_request *req, struct sip_route *route);
1802 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1803 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1804 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1805 static void set_destination(struct sip_pvt *p, char *uri);
1806 static void append_date(struct sip_request *req);
1807 static void build_contact(struct sip_pvt *p);
1808 static void build_rpid(struct sip_pvt *p);
1810 /*------Request handling functions */
1811 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1812 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);
1813 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1814 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1815 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1816 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1817 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1818 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1819 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1820 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1821 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
1822 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1823 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1825 /*------Response handling functions */
1826 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1827 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1828 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1829 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1831 /*----- RTP interface functions */
1832 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);
1833 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1834 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1835 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1836 static int sip_get_codec(struct ast_channel *chan);
1837 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1839 /*------ T38 Support --------- */
1840 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
1841 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1842 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1843 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1845 /*! \brief Definition of this channel for PBX channel registration */
1846 static const struct ast_channel_tech sip_tech = {
1848 .description = "Session Initiation Protocol (SIP)",
1849 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
1850 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1851 .requester = sip_request_call, /* called with chan unlocked */
1852 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1853 .call = sip_call, /* called with chan locked */
1854 .send_html = sip_sendhtml,
1855 .hangup = sip_hangup, /* called with chan locked */
1856 .answer = sip_answer, /* called with chan locked */
1857 .read = sip_read, /* called with chan locked */
1858 .write = sip_write, /* called with chan locked */
1859 .write_video = sip_write, /* called with chan locked */
1860 .write_text = sip_write,
1861 .indicate = sip_indicate, /* called with chan locked */
1862 .transfer = sip_transfer, /* called with chan locked */
1863 .fixup = sip_fixup, /* called with chan locked */
1864 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1865 .send_digit_end = sip_senddigit_end,
1866 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
1867 .early_bridge = ast_rtp_early_bridge,
1868 .send_text = sip_sendtext, /* called with chan locked */
1869 .func_channel_read = acf_channel_read,
1872 /*! \brief This version of the sip channel tech has no send_digit_begin
1873 * callback so that the core knows that the channel does not want
1874 * DTMF BEGIN frames.
1875 * The struct is initialized just before registering the channel driver,
1876 * and is for use with channels using SIP INFO DTMF.
1878 static struct ast_channel_tech sip_tech_info;
1880 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
1881 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
1883 /*! \brief map from an integer value to a string.
1884 * If no match is found, return errorstring
1886 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
1888 const struct _map_x_s *cur;
1890 for (cur = table; cur->s; cur++)
1896 /*! \brief map from a string to an integer value, case insensitive.
1897 * If no match is found, return errorvalue.
1899 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
1901 const struct _map_x_s *cur;
1903 for (cur = table; cur->s; cur++)
1904 if (!strcasecmp(cur->s, s))
1910 /*! \brief Interface structure with callbacks used to connect to RTP module */
1911 static struct ast_rtp_protocol sip_rtp = {
1913 .get_rtp_info = sip_get_rtp_peer,
1914 .get_vrtp_info = sip_get_vrtp_peer,
1915 .get_trtp_info = sip_get_trtp_peer,
1916 .set_rtp_peer = sip_set_rtp_peer,
1917 .get_codec = sip_get_codec,
1920 #define sip_pvt_lock(x) ast_mutex_lock(&x->pvt_lock)
1921 #define sip_pvt_unlock(x) ast_mutex_unlock(&x->pvt_lock)
1924 * helper functions to unreference various types of objects.
1925 * By handling them this way, we don't have to declare the
1926 * destructor on each call, which removes the chance of errors.
1928 static void unref_peer(struct sip_peer *peer)
1930 ASTOBJ_UNREF(peer, sip_destroy_peer);
1933 static void unref_user(struct sip_user *user)
1935 ASTOBJ_UNREF(user, sip_destroy_user);
1938 static void *registry_unref(struct sip_registry *reg)
1940 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
1941 ASTOBJ_UNREF(reg, sip_registry_destroy);
1945 /*! \brief Add object reference to SIP registry */
1946 static struct sip_registry *registry_addref(struct sip_registry *reg)
1948 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
1949 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
1952 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1953 static struct ast_udptl_protocol sip_udptl = {
1955 get_udptl_info: sip_get_udptl_peer,
1956 set_udptl_peer: sip_set_udptl_peer,
1959 /*! \brief Append to SIP dialog history
1960 \return Always returns 0 */
1961 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1963 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1964 __attribute__ ((format (printf, 2, 3)));
1967 /*! \brief Convert transfer status to string */
1968 static const char *referstatus2str(enum referstatus rstatus)
1970 return map_x_s(referstatusstrings, rstatus, "");
1973 /*! \brief Initialize the initital request packet in the pvt structure.
1974 This packet is used for creating replies and future requests in
1976 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1978 if (p->initreq.headers)
1979 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1981 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1982 /* Use this as the basis */
1983 copy_request(&p->initreq, req);
1984 parse_request(&p->initreq);
1986 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1989 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1990 static void sip_alreadygone(struct sip_pvt *dialog)
1992 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1993 dialog->alreadygone = 1;
1996 /*! Resolve DNS srv name or host name in a sip_proxy structure */
1997 static int proxy_update(struct sip_proxy *proxy)
1999 /* if it's actually an IP address and not a name,
2000 there's no need for a managed lookup */
2001 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2002 /* Ok, not an IP address, then let's check if it's a domain or host */
2003 /* XXX Todo - if we have proxy port, don't do SRV */
2004 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
2005 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2009 proxy->last_dnsupdate = time(NULL);
2013 /*! \brief Allocate and initialize sip proxy */
2014 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2016 struct sip_proxy *proxy;
2017 proxy = ast_calloc(1, sizeof(*proxy));
2020 proxy->force = force;
2021 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2022 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2023 proxy_update(proxy);
2027 /*! \brief Get default outbound proxy or global proxy */
2028 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2030 if (peer && peer->outboundproxy) {
2032 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2033 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2034 return peer->outboundproxy;
2036 if (global_outboundproxy.name[0]) {
2038 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2039 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2040 return &global_outboundproxy;
2043 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2047 /*! \brief returns true if 'name' (with optional trailing whitespace)
2048 * matches the sip method 'id'.
2049 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2050 * a case-insensitive comparison to be more tolerant.
2051 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2053 static int method_match(enum sipmethod id, const char *name)
2055 int len = strlen(sip_methods[id].text);
2056 int l_name = name ? strlen(name) : 0;
2057 /* true if the string is long enough, and ends with whitespace, and matches */
2058 return (l_name >= len && name[len] < 33 &&
2059 !strncasecmp(sip_methods[id].text, name, len));
2062 /*! \brief find_sip_method: Find SIP method from header */
2063 static int find_sip_method(const char *msg)
2067 if (ast_strlen_zero(msg))
2069 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
2070 if (method_match(i, msg))
2071 res = sip_methods[i].id;
2076 /*! \brief Parse supported header in incoming packet */
2077 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2081 unsigned int profile = 0;
2084 if (ast_strlen_zero(supported) )
2086 temp = ast_strdupa(supported);
2089 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2091 for (next = temp; next; next = sep) {
2093 if ( (sep = strchr(next, ',')) != NULL)
2095 next = ast_skip_blanks(next);
2097 ast_debug(3, "Found SIP option: -%s-\n", next);
2098 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
2099 if (!strcasecmp(next, sip_options[i].text)) {
2100 profile |= sip_options[i].id;
2103 ast_debug(3, "Matched SIP option: %s\n", next);
2107 if (!found && sipdebug) {
2108 if (!strncasecmp(next, "x-", 2))
2109 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2111 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2116 pvt->sipoptions = profile;
2120 /*! \brief See if we pass debug IP filter */
2121 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2125 if (debugaddr.sin_addr.s_addr) {
2126 if (((ntohs(debugaddr.sin_port) != 0)
2127 && (debugaddr.sin_port != addr->sin_port))
2128 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2134 /*! \brief The real destination address for a write */
2135 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2137 if (p->outboundproxy)
2138 return &p->outboundproxy->ip;
2140 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2143 /*! \brief Display SIP nat mode */
2144 static const char *sip_nat_mode(const struct sip_pvt *p)
2146 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2149 /*! \brief Test PVT for debugging output */
2150 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2154 return sip_debug_test_addr(sip_real_dst(p));
2157 /*! \brief Transmit SIP message */
2158 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
2161 const struct sockaddr_in *dst = sip_real_dst(p);
2162 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2166 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2167 case EHOSTUNREACH: /* Host can't be reached */
2168 case ENETDOWN: /* Interface down */
2169 case ENETUNREACH: /* Network failure */
2170 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2174 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));
2179 /*! \brief Build a Via header for a request */
2180 static void build_via(struct sip_pvt *p)
2182 /* Work around buggy UNIDEN UIP200 firmware */
2183 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2185 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2186 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
2187 ast_inet_ntoa(p->ourip.sin_addr),
2188 ntohs(p->ourip.sin_port), p->branch, rport);
2191 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2193 * Using the localaddr structure built up with localnet statements in sip.conf
2194 * apply it to their address to see if we need to substitute our
2195 * externip or can get away with our internal bindaddr
2196 * 'us' is always overwritten.
2198 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2200 struct sockaddr_in theirs;
2201 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2202 * reachable IP address and port. This is done if:
2203 * 1. we have a localaddr list (containing 'internal' addresses marked
2204 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2205 * and AST_SENSE_ALLOW on 'external' ones);
2206 * 2. either stunaddr or externip is set, so we know what to use as the
2207 * externally visible address;
2208 * 3. the remote address, 'them', is external;
2209 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2210 * when passed to ast_apply_ha() so it does need to be remapped.
2211 * This fourth condition is checked later.
2215 *us = internip; /* starting guess for the internal address */
2216 /* now ask the system what would it use to talk to 'them' */
2217 ast_ouraddrfor(them, &us->sin_addr);
2218 theirs.sin_addr = *them;
2220 want_remap = localaddr &&
2221 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2222 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2225 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2226 /* if we used externhost or stun, see if it is time to refresh the info */
2227 if (externexpire && time(NULL) >= externexpire) {
2228 if (stunaddr.sin_addr.s_addr) {
2229 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2231 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2232 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2234 externexpire = time(NULL) + externrefresh;
2236 if (externip.sin_addr.s_addr)
2239 ast_log(LOG_WARNING, "stun failed\n");
2240 ast_debug(1, "Target address %s is not local, substituting externip\n",
2241 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2242 } else if (bindaddr.sin_addr.s_addr) {
2243 /* no remapping, but we bind to a specific address, so use it. */
2248 /*! \brief Append to SIP dialog history with arg list */
2249 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2251 char buf[80], *c = buf; /* max history length */
2252 struct sip_history *hist;
2255 vsnprintf(buf, sizeof(buf), fmt, ap);
2256 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2257 l = strlen(buf) + 1;
2258 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2260 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2264 memcpy(hist->event, buf, l);
2265 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2266 struct sip_history *oldest;
2267 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2268 p->history_entries--;
2271 AST_LIST_INSERT_TAIL(p->history, hist, list);
2272 p->history_entries++;
2275 /*! \brief Append to SIP dialog history with arg list */
2276 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2283 if (!p->do_history && !recordhistory && !dumphistory)
2287 append_history_va(p, fmt, ap);
2293 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2294 static int retrans_pkt(const void *data)
2296 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2297 int reschedule = DEFAULT_RETRANS;
2300 /* Lock channel PVT */
2301 sip_pvt_lock(pkt->owner);
2303 if (pkt->retrans < MAX_RETRANS) {
2305 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2307 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);
2312 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2316 pkt->timer_a = 2 * pkt->timer_a;
2318 /* For non-invites, a maximum of 4 secs */
2319 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2320 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2323 /* Reschedule re-transmit */
2324 reschedule = siptimer_a;
2325 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);
2328 if (sip_debug_test_pvt(pkt->owner)) {
2329 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2330 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2331 pkt->retrans, sip_nat_mode(pkt->owner),
2332 ast_inet_ntoa(dst->sin_addr),
2333 ntohs(dst->sin_port), pkt->data);
2336 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
2337 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2338 sip_pvt_unlock(pkt->owner);
2339 if (xmitres == XMIT_ERROR)
2340 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2344 /* Too many retries */
2345 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2346 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2347 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n",
2348 pkt->owner->callid, pkt->seqno,
2349 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2350 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2351 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2354 if (xmitres == XMIT_ERROR) {
2355 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2356 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2358 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2360 pkt->retransid = -1;
2362 if (pkt->is_fatal) {
2363 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2364 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2366 sip_pvt_lock(pkt->owner);
2369 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
2370 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2372 if (pkt->owner->owner) {
2373 sip_alreadygone(pkt->owner);
2374 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2375 ast_queue_hangup(pkt->owner->owner);
2376 ast_channel_unlock(pkt->owner->owner);
2378 /* If no channel owner, destroy now */
2380 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2381 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2382 pkt->owner->needdestroy = 1;
2383 sip_alreadygone(pkt->owner);
2384 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2389 if (pkt->method == SIP_BYE) {
2390 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
2391 if (pkt->owner->owner)
2392 ast_channel_unlock(pkt->owner->owner);
2393 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2394 pkt->owner->needdestroy = 1;
2397 /* Remove the packet */
2398 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2400 UNLINK(cur, pkt->owner->packets, prev);
2401 sip_pvt_unlock(pkt->owner);
2407 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2408 sip_pvt_unlock(pkt->owner);
2412 /*! \brief Transmit packet with retransmits
2413 \return 0 on success, -1 on failure to allocate packet
2415 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2417 struct sip_pkt *pkt;
2418 int siptimer_a = DEFAULT_RETRANS;
2421 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2423 /* copy data, add a terminator and save length */
2424 memcpy(pkt->data, data, len);
2425 pkt->data[len] = '\0';
2426 pkt->packetlen = len;
2427 /* copy other parameters from the caller */
2428 pkt->method = sipmethod;
2430 pkt->is_resp = resp;
2431 pkt->is_fatal = fatal;
2432 pkt->owner = dialog_ref(p);
2433 pkt->next = p->packets;
2435 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2437 siptimer_a = pkt->timer_t1 * 2;
2439 /* Schedule retransmission */
2440 pkt->retransid = ast_sched_replace_variable(pkt->retransid, sched,
2441 siptimer_a, retrans_pkt, pkt, 1);
2443 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2444 if (sipmethod == SIP_INVITE) {
2445 /* Note this is a pending invite */
2446 p->pendinginvite = seqno;
2449 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2451 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2452 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2453 ast_sched_del(sched, pkt->retransid); /* No more retransmission */
2454 pkt->retransid = -1;
2460 /*! \brief Kill a SIP dialog (called only by the scheduler)
2461 * The scheduler has a reference to this dialog when p->autokillid != -1,
2462 * and we are called using that reference. So if the event is not
2463 * rescheduled, we need to call dialog_unref().
2465 static int __sip_autodestruct(const void *data)
2467 struct sip_pvt *p = (struct sip_pvt *)data;
2469 /* If this is a subscription, tell the phone that we got a timeout */
2470 if (p->subscribed) {
2471 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2472 p->subscribed = NONE;
2473 append_history(p, "Subscribestatus", "timeout");
2474 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
2475 return 10000; /* Reschedule this destruction so that we know that it's gone */
2478 /* If there are packets still waiting for delivery, delay the destruction */
2480 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2481 append_history(p, "ReliableXmit", "timeout");
2485 if (p->subscribed == MWI_NOTIFICATION)
2487 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2489 /* Reset schedule ID */
2493 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2494 ast_queue_hangup(p->owner);
2496 } else if (p->refer) {
2497 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
2498 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2499 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2500 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2503 append_history(p, "AutoDestroy", "%s", p->callid);
2504 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
2505 sip_destroy(p); /* Go ahead and destroy dialog. All attempts to recover is done */
2506 /* sip_destroy also absorbs the reference */
2511 /*! \brief Schedule destruction of SIP dialog */
2512 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2515 if (p->timer_t1 == 0) {
2516 p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
2517 p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
2519 ms = p->timer_t1 * 64;
2521 if (sip_debug_test_pvt(p))
2522 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2523 sip_cancel_destroy(p);
2525 append_history(p, "SchedDestroy", "%d ms", ms);
2526 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p));
2529 /*! \brief Cancel destruction of SIP dialog.
2530 * Be careful as this also absorbs the reference - if you call it
2531 * from within the scheduler, this might be the last reference.
2533 static void sip_cancel_destroy(struct sip_pvt *p)
2535 if (p->autokillid > -1) {
2536 ast_sched_del(sched, p->autokillid);
2537 append_history(p, "CancelDestroy", "");
2543 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2544 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2546 struct sip_pkt *cur, *prev = NULL;
2547 const char *msg = "Not Found"; /* used only for debugging */
2551 /* If we have an outbound proxy for this dialog, then delete it now since
2552 the rest of the requests in this dialog needs to follow the routing.
2553 If obforcing is set, we will keep the outbound proxy during the whole
2554 dialog, regardless of what the SIP rfc says
2556 if (p->outboundproxy && !p->outboundproxy->force)
2557 p->outboundproxy = NULL;
2559 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2560 if (cur->seqno != seqno || cur->is_resp != resp)
2562 if (cur->is_resp || cur->method == sipmethod) {
2564 if (!resp && (seqno == p->pendinginvite)) {
2565 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
2566 p->pendinginvite = 0;
2568 if (cur->retransid > -1) {
2570 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2571 ast_sched_del(sched, cur->retransid);
2572 cur->retransid = -1;
2574 UNLINK(cur, p->packets, prev);
2575 dialog_unref(cur->owner);
2581 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2582 p->callid, resp ? "Response" : "Request", seqno, msg);
2585 /*! \brief Pretend to ack all packets
2586 * maybe the lock on p is not strictly necessary but there might be a race */
2587 static void __sip_pretend_ack(struct sip_pvt *p)
2589 struct sip_pkt *cur = NULL;
2591 while (p->packets) {
2593 if (cur == p->packets) {
2594 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2598 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2599 __sip_ack(p, cur->seqno, cur->is_resp, method);
2603 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2604 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2606 struct sip_pkt *cur;
2609 for (cur = p->packets; cur; cur = cur->next) {
2610 if (cur->seqno == seqno && cur->is_resp == resp &&
2611 (cur->is_resp || method_match(sipmethod, cur->data))) {
2612 /* this is our baby */
2613 if (cur->retransid > -1) {
2615 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2616 ast_sched_del(sched, cur->retransid);
2617 cur->retransid = -1;
2623 ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2628 /*! \brief Copy SIP request, parse it */
2629 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2631 memset(dst, 0, sizeof(*dst));
2632 memcpy(dst->data, src->data, sizeof(dst->data));
2633 dst->len = src->len;
2637 /*! \brief add a blank line if no body */
2638 static void add_blank(struct sip_request *req)
2641 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2642 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
2643 req->len += strlen(req->data + req->len);
2647 /*! \brief Transmit response on SIP request*/
2648 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2653 if (sip_debug_test_pvt(p)) {
2654 const struct sockaddr_in *dst = sip_real_dst(p);
2656 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2657 reliable ? "Reliably " : "", sip_nat_mode(p),
2658 ast_inet_ntoa(dst->sin_addr),
2659 ntohs(dst->sin_port), req->data);
2661 if (p->do_history) {
2662 struct sip_request tmp;
2663 parse_copy(&tmp, req);
2664 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2665 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2668 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2669 __sip_xmit(p, req->data, req->len);
2675 /*! \brief Send SIP Request to the other part of the dialogue */
2676 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2680 /* If we have an outbound proxy, reset peer address
2683 if (p->outboundproxy) {
2684 p->sa = p->outboundproxy->ip;
2688 if (sip_debug_test_pvt(p)) {
2689 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2690 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);
2692 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);
2694 if (p->do_history) {
2695 struct sip_request tmp;
2696 parse_copy(&tmp, req);
2697 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2700 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2701 __sip_xmit(p, req->data, req->len);
2705 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2706 * optionally with a limit on the search.
2707 * start must be past the first quote.
2709 static const char *find_closing_quote(const char *start, const char *lim)
2711 char last_char = '\0';
2713 for (s = start; *s && s != lim; last_char = *s++) {
2714 if (*s == '"' && last_char != '\\')
2720 /*! \brief Pick out text in brackets from character string
2721 \return pointer to terminated stripped string
2722 \param tmp input string that will be modified
2725 "foo" <bar> valid input, returns bar
2726 foo returns the whole string
2727 < "foo ... > returns the string between brackets
2728 < "foo... bogus (missing closing bracket), returns the whole string
2729 XXX maybe should still skip the opening bracket
2732 static char *get_in_brackets(char *tmp)
2734 const char *parse = tmp;
2735 char *first_bracket;
2738 * Skip any quoted text until we find the part in brackets.
2739 * On any error give up and return the full string.
2741 while ( (first_bracket = strchr(parse, '<')) ) {
2742 char *first_quote = strchr(parse, '"');
2744 if (!first_quote || first_quote > first_bracket)
2745 break; /* no need to look at quoted part */
2746 /* the bracket is within quotes, so ignore it */
2747 parse = find_closing_quote(first_quote + 1, NULL);
2748 if (!*parse) { /* not found, return full string ? */
2749 /* XXX or be robust and return in-bracket part ? */
2750 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2755 if (first_bracket) {
2756 char *second_bracket = strchr(first_bracket + 1, '>');
2757 if (second_bracket) {
2758 *second_bracket = '\0';
2759 tmp = first_bracket + 1;
2761 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2767 /*! \brief * parses a URI in its components.
2770 * - If scheme is specified, drop it from the top.
2771 * - If a component is not requested, do not split around it.
2773 * This means that if we don't have domain, we cannot split
2774 * name:pass and domain:port.
2775 * It is safe to call with ret_name, pass, domain, port
2776 * pointing all to the same place.
2777 * Init pointers to empty string so we never get NULL dereferencing.
2778 * Overwrites the string.
2779 * return 0 on success, other values on error.
2781 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
2784 static int parse_uri(char *uri, char *scheme,
2785 char **ret_name, char **pass, char **domain, char **port, char **options)
2790 /* init field as required */
2796 int l = strlen(scheme);
2797 if (!strncasecmp(uri, scheme, l))
2800 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, uri);
2805 /* if we don't want to split around domain, keep everything as a name,
2806 * so we need to do nothing here, except remember why.
2809 /* store the result in a temp. variable to avoid it being
2810 * overwritten if arguments point to the same place.
2814 if ((c = strchr(uri, '@')) == NULL) {
2815 /* domain-only URI, according to the SIP RFC. */
2824 /* Remove options in domain and name */
2825 dom = strsep(&dom, ";");
2826 name = strsep(&name, ";");
2828 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2832 if (pass && (c = strchr(name, ':'))) { /* user:password */
2838 if (ret_name) /* same as for domain, store the result only at the end */
2841 *options = uri ? uri : "";
2846 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
2847 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2849 struct sip_pvt *p = chan->tech_pvt;
2851 if (subclass != AST_HTML_URL)
2854 ast_string_field_build(p, url, "<%s>;mode=active", data);
2856 if (sip_debug_test_pvt(p))
2857 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
2859 switch (chan->_state) {
2860 case AST_STATE_RING:
2861 transmit_response(p, "100 Trying", &p->initreq);
2863 case AST_STATE_RINGING:
2864 transmit_response(p, "180 Ringing", &p->initreq);
2867 if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
2868 transmit_reinvite_with_sdp(p, FALSE);
2869 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
2870 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
2874 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
2880 /*! \brief Send SIP MESSAGE text within a call
2881 Called from PBX core sendtext() application */
2882 static int sip_sendtext(struct ast_channel *ast, const char *text)
2884 struct sip_pvt *p = ast->tech_pvt;
2885 int debug = sip_debug_test_pvt(p);
2888 ast_verbose("Sending text %s on %s\n", text, ast->name);
2891 if (ast_strlen_zero(text))
2894 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2895 transmit_message_with_text(p, text);
2899 /*! \brief Update peer object in realtime storage
2900 If the Asterisk system name is set in asterisk.conf, we will use
2901 that name and store that in the "regserver" field in the sippeers
2902 table to facilitate multi-server setups.
2904 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, int expirey)
2907 char ipaddr[INET_ADDRSTRLEN];
2908 char regseconds[20];
2909 char *tablename = NULL;
2911 const char *sysname = ast_config_AST_SYSTEM_NAME;
2912 char *syslabel = NULL;
2914 time_t nowtime = time(NULL) + expirey;
2915 const char *fc = fullcontact ? "fullcontact" : NULL;
2917 int realtimeregs = ast_check_realtime("sipregs");
2919 tablename = realtimeregs ? "sipregs" : "sippeers";
2921 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2922 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2923 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2925 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2927 else if (sip_cfg.rtsave_sysname)
2928 syslabel = "regserver";
2931 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2932 "port", port, "regseconds", regseconds,
2933 "defaultuser", defaultuser, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2935 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2936 "port", port, "regseconds", regseconds,
2937 "defaultuser", defaultuser, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2940 /*! \brief Automatically add peer extension to dial plan */
2941 static void register_peer_exten(struct sip_peer *peer, int onoff)
2944 char *stringp, *ext, *context;
2946 /* XXX note that global_regcontext is both a global 'enable' flag and
2947 * the name of the global regexten context, if not specified
2950 if (ast_strlen_zero(global_regcontext))
2953 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2955 while ((ext = strsep(&stringp, "&"))) {
2956 if ((context = strchr(ext, '@'))) {
2957 *context++ = '\0'; /* split ext@context */
2958 if (!ast_context_find(context)) {
2959 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2963 context = global_regcontext;
2966 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2967 ast_strdup(peer->name), ast_free_ptr, "SIP");
2969 ast_context_remove_extension(context, ext, 1, NULL);
2973 /*! Destroy mailbox subscriptions */
2974 static void destroy_mailbox(struct sip_mailbox *mailbox)
2976 if (mailbox->mailbox)
2977 ast_free(mailbox->mailbox);
2978 if (mailbox->context)
2979 ast_free(mailbox->context);
2980 if (mailbox->event_sub)
2981 ast_event_unsubscribe(mailbox->event_sub);
2985 /*! Destroy all peer-related mailbox subscriptions */
2986 static void clear_peer_mailboxes(struct sip_peer *peer)
2988 struct sip_mailbox *mailbox;
2990 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
2991 destroy_mailbox(mailbox);
2994 /*! \brief Destroy peer object from memory */
2995 static void sip_destroy_peer(struct sip_peer *peer)
2997 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
2999 if (peer->outboundproxy)
3000 ast_free(peer->outboundproxy);
3001 peer->outboundproxy = NULL;
3003 /* Delete it, it needs to disappear */
3005 peer->call = sip_destroy(peer->call);
3007 if (peer->mwipvt) /* We have an active subscription, delete it */
3008 peer->mwipvt = sip_destroy(peer->mwipvt);
3010 if (peer->chanvars) {
3011 ast_variables_destroy(peer->chanvars);
3012 peer->chanvars = NULL;
3014 if (peer->expire > -1)
3015 ast_sched_del(sched, peer->expire);
3017 if (peer->pokeexpire > -1)
3018 ast_sched_del(sched, peer->pokeexpire);
3019 register_peer_exten(peer, FALSE);
3020 ast_free_ha(peer->ha);
3021 if (peer->selfdestruct)
3023 else if (peer->is_realtime) {
3025 ast_debug(3,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
3028 clear_realm_authentication(peer->auth);
3031 ast_dnsmgr_release(peer->dnsmgr);
3032 clear_peer_mailboxes(peer);
3036 /*! \brief Update peer data in database (if used) */
3037 static void update_peer(struct sip_peer *p, int expiry)
3039 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);