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
88 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
91 #include <sys/ioctl.h>
94 #include <sys/signal.h>
97 #include "asterisk/network.h"
98 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
100 #include "asterisk/lock.h"
101 #include "asterisk/channel.h"
102 #include "asterisk/config.h"
103 #include "asterisk/module.h"
104 #include "asterisk/pbx.h"
105 #include "asterisk/sched.h"
106 #include "asterisk/io.h"
107 #include "asterisk/rtp.h"
108 #include "asterisk/udptl.h"
109 #include "asterisk/acl.h"
110 #include "asterisk/manager.h"
111 #include "asterisk/callerid.h"
112 #include "asterisk/cli.h"
113 #include "asterisk/app.h"
114 #include "asterisk/musiconhold.h"
115 #include "asterisk/dsp.h"
116 #include "asterisk/features.h"
117 #include "asterisk/srv.h"
118 #include "asterisk/astdb.h"
119 #include "asterisk/causes.h"
120 #include "asterisk/utils.h"
121 #include "asterisk/file.h"
122 #include "asterisk/astobj.h"
123 #include "asterisk/dnsmgr.h"
124 #include "asterisk/devicestate.h"
125 #include "asterisk/linkedlists.h"
126 #include "asterisk/stringfields.h"
127 #include "asterisk/monitor.h"
128 #include "asterisk/netsock.h"
129 #include "asterisk/localtime.h"
130 #include "asterisk/abstract_jb.h"
131 #include "asterisk/threadstorage.h"
132 #include "asterisk/translate.h"
133 #include "asterisk/version.h"
134 #include "asterisk/event.h"
144 #define XMIT_ERROR -2
146 /* #define VOCAL_DATA_HACK */
148 #define DEFAULT_DEFAULT_EXPIRY 120
149 #define DEFAULT_MIN_EXPIRY 60
150 #define DEFAULT_MAX_EXPIRY 3600
151 #define DEFAULT_REGISTRATION_TIMEOUT 20
152 #define DEFAULT_MAX_FORWARDS "70"
154 /* guard limit must be larger than guard secs */
155 /* guard min must be < 1000, and should be >= 250 */
156 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
157 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
159 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
160 GUARD_PCT turns out to be lower than this, it
161 will use this time instead.
162 This is in milliseconds. */
163 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
164 below EXPIRY_GUARD_LIMIT */
165 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
167 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
168 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
169 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
170 static int expiry = DEFAULT_EXPIRY;
173 #define MAX(a,b) ((a) > (b) ? (a) : (b))
176 #define CALLERID_UNKNOWN "Unknown"
178 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
179 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
180 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
182 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
183 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
184 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
185 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1
186 \todo Use known T1 for timeout (peerpoke)
188 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
189 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
191 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
192 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
193 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
195 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
197 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
198 static struct ast_jb_conf default_jbconf =
202 .resync_threshold = -1,
205 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
207 static const char config[] = "sip.conf"; /*!< Main configuration file */
208 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
213 /*! \brief Authorization scheme for call transfers
214 \note Not a bitfield flag, since there are plans for other modes,
215 like "only allow transfers for authenticated devices" */
217 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
218 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
227 /*! \brief States for the INVITE transaction, not the dialog
228 \note this is for the INVITE that sets up the dialog
231 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
232 INV_CALLING = 1, /*!< Invite sent, no answer */
233 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
234 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
235 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
236 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
237 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
238 The only way out of this is a BYE from one side */
239 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
243 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
244 If it fails, it's critical and will cause a teardown of the session */
245 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
246 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
249 enum parse_register_result {
250 PARSE_REGISTER_FAILED,
251 PARSE_REGISTER_UPDATE,
252 PARSE_REGISTER_QUERY,
255 enum subscriptiontype {
264 /*! \brief Subscription types that we support. We support
265 - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
266 - SIMPLE presence used for device status
267 - Voicemail notification subscriptions
269 static const struct cfsubscription_types {
270 enum subscriptiontype type;
271 const char * const event;
272 const char * const mediatype;
273 const char * const text;
274 } subscription_types[] = {
275 { NONE, "-", "unknown", "unknown" },
276 /* RFC 4235: SIP Dialog event package */
277 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
278 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
279 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
280 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
281 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
285 /*! \brief Authentication types - proxy or www authentication
286 \note Endpoints, like Asterisk, should always use WWW authentication to
287 allow multiple authentications in the same call - to the proxy and
295 /*! \brief Authentication result from check_auth* functions */
296 enum check_auth_result {
297 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
298 /* XXX maybe this is the same as AUTH_NOT_FOUND */
301 AUTH_CHALLENGE_SENT = 1,
302 AUTH_SECRET_FAILED = -1,
303 AUTH_USERNAME_MISMATCH = -2,
304 AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
306 AUTH_UNKNOWN_DOMAIN = -5,
307 AUTH_PEER_NOT_DYNAMIC = -6,
308 AUTH_ACL_FAILED = -7,
311 /*! \brief States for outbound registrations (with register= lines in sip.conf */
312 enum sipregistrystate {
313 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
314 /* Initial state. We should have a timeout scheduled for the initial
315 * (or next) registration transmission, calling sip_reregister
318 REG_STATE_REGSENT, /*!< Registration request sent */
319 /* sent initial request, waiting for an ack or a timeout to
320 * retransmit the initial request.
323 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
324 /* entered after transmit_register with auth info,
325 * waiting for an ack.
328 REG_STATE_REGISTERED, /*!< Registered and done */
330 REG_STATE_REJECTED, /*!< Registration rejected */
331 /* only used when the remote party has an expire larger than
332 * our max-expire. This is a final state from which we do not
333 * recover (not sure how correctly).
336 REG_STATE_TIMEOUT, /*!< Registration timed out */
339 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
340 /* fatal - no chance to proceed */
342 REG_STATE_FAILED, /*!< Registration failed after several tries */
343 /* fatal - no chance to proceed */
346 /*! \brief definition of a sip proxy server
348 * For outbound proxies, this is allocated in the SIP peer dynamically or
349 * statically as the global_outboundproxy. The pointer in a SIP message is just
350 * a pointer and should *not* be de-allocated.
353 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
354 struct sockaddr_in ip; /*!< Currently used IP address and port */
355 time_t last_dnsupdate; /*!< When this was resolved */
356 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
357 /* Room for a SRV record chain based on the name */
360 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
361 enum can_create_dialog {
362 CAN_NOT_CREATE_DIALOG,
364 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
367 /*! \brief SIP Request methods known by Asterisk
369 \note Do _NOT_ make any changes to this enum, or the array following it;
370 if you think you are doing the right thing, you are probably
371 not doing the right thing. If you think there are changes
372 needed, get someone else to review them first _before_
373 submitting a patch. If these two lists do not match properly
374 bad things will happen.
378 SIP_UNKNOWN, /*!< Unknown response */
379 SIP_RESPONSE, /*!< Not request, response to outbound request */
380 SIP_REGISTER, /*!< Registration to the mothership, tell us where you are located */
381 SIP_OPTIONS, /*!< Check capabilities of a device, used for "ping" too */
382 SIP_NOTIFY, /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
383 SIP_INVITE, /*!< Set up a session */
384 SIP_ACK, /*!< End of a three-way handshake started with INVITE. */
385 SIP_PRACK, /*!< Reliable pre-call signalling. Not supported in Asterisk. */
386 SIP_BYE, /*!< End of a session */
387 SIP_REFER, /*!< Refer to another URI (transfer) */
388 SIP_SUBSCRIBE, /*!< Subscribe for updates (voicemail, session status, device status, presence) */
389 SIP_MESSAGE, /*!< Text messaging */
390 SIP_UPDATE, /*!< Update a dialog. We can send UPDATE; but not accept it */
391 SIP_INFO, /*!< Information updates during a session */
392 SIP_CANCEL, /*!< Cancel an INVITE */
393 SIP_PUBLISH, /*!< Not supported in Asterisk */
394 SIP_PING, /*!< Not supported at all, no standard but still implemented out there */
397 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
398 structure and then route the messages according to the type.
400 \note Note that sip_methods[i].id == i must hold or the code breaks */
401 static const struct cfsip_methods {
403 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
405 enum can_create_dialog can_create;
407 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
408 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
409 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
410 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
411 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
412 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
413 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
414 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
415 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
416 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
417 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
418 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
419 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
420 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
421 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
422 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
423 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
426 /*! Define SIP option tags, used in Require: and Supported: headers
427 We need to be aware of these properties in the phones to use
428 the replace: header. We should not do that without knowing
429 that the other end supports it...
430 This is nothing we can configure, we learn by the dialog
431 Supported: header on the REGISTER (peer) or the INVITE
433 We are not using many of these today, but will in the future.
434 This is documented in RFC 3261
437 #define NOT_SUPPORTED 0
440 #define SIP_OPT_REPLACES (1 << 0)
441 #define SIP_OPT_100REL (1 << 1)
442 #define SIP_OPT_TIMER (1 << 2)
443 #define SIP_OPT_EARLY_SESSION (1 << 3)
444 #define SIP_OPT_JOIN (1 << 4)
445 #define SIP_OPT_PATH (1 << 5)
446 #define SIP_OPT_PREF (1 << 6)
447 #define SIP_OPT_PRECONDITION (1 << 7)
448 #define SIP_OPT_PRIVACY (1 << 8)
449 #define SIP_OPT_SDP_ANAT (1 << 9)
450 #define SIP_OPT_SEC_AGREE (1 << 10)
451 #define SIP_OPT_EVENTLIST (1 << 11)
452 #define SIP_OPT_GRUU (1 << 12)
453 #define SIP_OPT_TARGET_DIALOG (1 << 13)
454 #define SIP_OPT_NOREFERSUB (1 << 14)
455 #define SIP_OPT_HISTINFO (1 << 15)
456 #define SIP_OPT_RESPRIORITY (1 << 16)
458 /*! \brief List of well-known SIP options. If we get this in a require,
459 we should check the list and answer accordingly. */
460 static const struct cfsip_options {
461 int id; /*!< Bitmap ID */
462 int supported; /*!< Supported by Asterisk ? */
463 char * const text; /*!< Text id, as in standard */
464 } sip_options[] = { /* XXX used in 3 places */
465 /* RFC3891: Replaces: header for transfer */
466 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
467 /* One version of Polycom firmware has the wrong label */
468 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
469 /* RFC3262: PRACK 100% reliability */
470 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
471 /* RFC4028: SIP Session Timers */
472 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
473 /* RFC3959: SIP Early session support */
474 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
475 /* RFC3911: SIP Join header support */
476 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
477 /* RFC3327: Path support */
478 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
479 /* RFC3840: Callee preferences */
480 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
481 /* RFC3312: Precondition support */
482 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
483 /* RFC3323: Privacy with proxies*/
484 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
485 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
486 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
487 /* RFC3329: Security agreement mechanism */
488 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
489 /* SIMPLE events: RFC4662 */
490 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
491 /* GRUU: Globally Routable User Agent URI's */
492 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
493 /* RFC4538: Target-dialog */
494 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
495 /* Disable the REFER subscription, RFC 4488 */
496 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
497 /* ietf-sip-history-info-06.txt */
498 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
499 /* ietf-sip-resource-priority-10.txt */
500 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
504 /*! \brief SIP Methods we support
505 \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
506 allowsubscribe and allowrefer on in sip.conf.
508 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
510 /*! \brief SIP Extensions we support */
511 #define SUPPORTED_EXTENSIONS "replaces"
513 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
514 #define STANDARD_SIP_PORT 5060
515 /* Note: in many SIP headers, absence of a port number implies port 5060,
516 * and this is why we cannot change the above constant.
517 * There is a limited number of places in asterisk where we could,
518 * in principle, use a different "default" port number, but
519 * we do not support this feature at the moment.
520 * You can run Asterisk with SIP on a different port with a configuration
521 * option. If you change this value, the signalling will be incorrect.
524 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
526 These are default values in the source. There are other recommended values in the
527 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
528 yet encouraging new behaviour on new installations
531 #define DEFAULT_CONTEXT "default"
532 #define DEFAULT_MOHINTERPRET "default"
533 #define DEFAULT_MOHSUGGEST ""
534 #define DEFAULT_VMEXTEN "asterisk"
535 #define DEFAULT_CALLERID "asterisk"
536 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
537 #define DEFAULT_ALLOWGUEST TRUE
538 #define DEFAULT_CALLCOUNTER FALSE
539 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
540 #define DEFAULT_COMPACTHEADERS FALSE
541 #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. */
542 #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. */
543 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
544 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
545 #define DEFAULT_COS_SIP 4
546 #define DEFAULT_COS_AUDIO 5
547 #define DEFAULT_COS_VIDEO 6
548 #define DEFAULT_COS_TEXT 5
549 #define DEFAULT_ALLOW_EXT_DOM TRUE
550 #define DEFAULT_REALM "asterisk"
551 #define DEFAULT_NOTIFYRINGING TRUE
552 #define DEFAULT_PEDANTIC FALSE
553 #define DEFAULT_AUTOCREATEPEER FALSE
554 #define DEFAULT_QUALIFY FALSE
555 #define DEFAULT_REGEXTENONQUALIFY FALSE
556 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
557 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
558 #ifndef DEFAULT_USERAGENT
559 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
560 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
561 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
565 /*! \name DefaultSettings
566 Default setttings are used as a channel setting and as a default when
570 static char default_context[AST_MAX_CONTEXT];
571 static char default_subscribecontext[AST_MAX_CONTEXT];
572 static char default_language[MAX_LANGUAGE];
573 static char default_callerid[AST_MAX_EXTENSION];
574 static char default_fromdomain[AST_MAX_EXTENSION];
575 static char default_notifymime[AST_MAX_EXTENSION];
576 static int default_qualify; /*!< Default Qualify= setting */
577 static char default_vmexten[AST_MAX_EXTENSION];
578 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
579 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
580 * a bridged channel on hold */
581 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
582 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
584 /*! \brief a place to store all global settings for the sip channel driver */
585 struct sip_settings {
586 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
587 int rtsave_sysname; /*!< G: Save system name at registration? */
588 int ignore_regexpire; /*!< G: Ignore expiration of peer */
591 static struct sip_settings sip_cfg;
594 /*! \name GlobalSettings
595 Global settings apply to the channel (often settings you can change in the general section
599 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
600 static int global_limitonpeers; /*!< Match call limit on peers only */
601 static int global_rtautoclear; /*!< Realtime ?? */
602 static int global_notifyringing; /*!< Send notifications on ringing */
603 static int global_notifyhold; /*!< Send notifications on hold */
604 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
605 static int global_srvlookup; /*!< SRV Lookup on or off. Default is on */
606 static int pedanticsipchecking; /*!< Extra checking ? Default off */
607 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
608 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
609 static int global_relaxdtmf; /*!< Relax DTMF */
610 static int global_rtptimeout; /*!< Time out call if no RTP */
611 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
612 static int global_rtpkeepalive; /*!< Send RTP keepalives */
613 static int global_reg_timeout;
614 static int global_regattempts_max; /*!< Registration attempts before giving up */
615 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
616 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
617 call-limit to 999. When we remove the call-limit from the code, we can make it
618 with just a boolean flag in the device structure */
619 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
620 the global setting is in globals_flags[1] */
621 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
622 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
623 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
624 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
625 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
626 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
627 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
628 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
629 static int compactheaders; /*!< send compact sip headers */
630 static int recordhistory; /*!< Record SIP history. Off by default */
631 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
632 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
633 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
634 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
635 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
636 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
637 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
638 static int global_callevents; /*!< Whether we send manager events or not */
639 static int global_t1; /*!< T1 time */
640 static int global_t1min; /*!< T1 roundtrip time minimum */
641 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
642 static int global_regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
643 static int global_autoframing; /*!< Turn autoframing on or off. */
644 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
645 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
647 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
649 /*! \brief Codecs that we support by default: */
650 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
653 /* Object counters */
654 static int suserobjs = 0; /*!< Static users */
655 static int ruserobjs = 0; /*!< Realtime users */
656 static int speerobjs = 0; /*!< Statis peers */
657 static int rpeerobjs = 0; /*!< Realtime peers */
658 static int apeerobjs = 0; /*!< Autocreated peer objects */
659 static int regobjs = 0; /*!< Registry objects */
661 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
662 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
664 AST_MUTEX_DEFINE_STATIC(netlock);
666 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
667 when it's doing something critical. */
669 AST_MUTEX_DEFINE_STATIC(monlock);
671 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
673 /*! \brief This is the thread for the monitor which checks for input on the channels
674 which are not currently in use. */
675 static pthread_t monitor_thread = AST_PTHREADT_NULL;
677 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
678 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
680 static struct sched_context *sched; /*!< The scheduling context */
681 static struct io_context *io; /*!< The IO context */
682 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
684 #define DEC_CALL_LIMIT 0
685 #define INC_CALL_LIMIT 1
686 #define DEC_CALL_RINGING 2
687 #define INC_CALL_RINGING 3
689 /*! \brief The data grabbed from the UDP socket
691 * Incoming messages: we first store the data from the socket in data[],
692 * adding a trailing \0 to make string parsing routines happy.
693 * Then call parse_request() and req.method = find_sip_method();
694 * to initialize the other fields. The \r\n at the end of each line is
695 * replaced by \0, so that data[] is not a conforming SIP message anymore.
696 * After this processing, rlPart1 is set to non-NULL to remember
697 * that we can run get_header() on this kind of packet.
699 * parse_request() splits the first line as follows:
700 * Requests have in the first line method uri SIP/2.0
701 * rlPart1 = method; rlPart2 = uri;
702 * Responses have in the first line SIP/2.0 NNN description
703 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
705 * For outgoing packets, we initialize the fields with init_req() or init_resp()
706 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
707 * and then fill the rest with add_header() and add_line().
708 * The \r\n at the end of the line are still there, so the get_header()
709 * and similar functions don't work on these packets.
713 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
714 char *rlPart2; /*!< The Request URI or Response Status */
715 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
716 int headers; /*!< # of SIP Headers */
717 int method; /*!< Method of this request */
718 int lines; /*!< Body Content */
719 unsigned int sdp_start; /*!< the line number where the SDP begins */
720 unsigned int sdp_end; /*!< the line number where the SDP ends */
721 char debug; /*!< print extra debugging if non zero */
722 char has_to_tag; /*!< non-zero if packet has To: tag */
723 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
724 char *header[SIP_MAX_HEADERS];
725 char *line[SIP_MAX_LINES];
726 char data[SIP_MAX_PACKET];
729 /*! \brief structure used in transfers */
731 struct ast_channel *chan1; /*!< First channel involved */
732 struct ast_channel *chan2; /*!< Second channel involved */
733 struct sip_request req; /*!< Request that caused the transfer (REFER) */
734 int seqno; /*!< Sequence number */
739 /*! \brief Parameters to the transmit_invite function */
740 struct sip_invite_param {
741 int addsipheaders; /*!< Add extra SIP headers */
742 const char *uri_options; /*!< URI options to add to the URI */
743 const char *vxml_url; /*!< VXML url for Cisco phones */
744 char *auth; /*!< Authentication */
745 char *authheader; /*!< Auth header */
746 enum sip_auth_type auth_type; /*!< Authentication type */
747 const char *replaces; /*!< Replaces header for call transfers */
748 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
751 /*! \brief Structure to save routing information for a SIP session */
753 struct sip_route *next;
757 /*! \brief Modes for SIP domain handling in the PBX */
759 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
760 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
763 /*! \brief Domain data structure.
764 \note In the future, we will connect this to a configuration tree specific
768 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
769 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
770 enum domain_mode mode; /*!< How did we find this domain? */
771 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
774 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
777 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
779 AST_LIST_ENTRY(sip_history) list;
780 char event[0]; /* actually more, depending on needs */
783 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
785 /*! \brief sip_auth: Credentials for authentication to other SIP services */
787 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
788 char username[256]; /*!< Username */
789 char secret[256]; /*!< Secret */
790 char md5secret[256]; /*!< MD5Secret */
791 struct sip_auth *next; /*!< Next auth structure in list */
795 Various flags for the flags field in the pvt structure
796 Trying to sort these up (one or more of the following):
800 When flags are used by multiple structures, it is important that
801 they have a common layout so it is easy to copy them.
804 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
805 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
806 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
807 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
808 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
809 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
810 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
811 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
812 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
813 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 11) /*!< D: Do not hangup at first ast_hangup */
815 #define SIP_PROMISCREDIR (1 << 12) /*!< DP: Promiscuous redirection */
816 #define SIP_TRUSTRPID (1 << 13) /*!< DP: Trust RPID headers? */
817 #define SIP_USEREQPHONE (1 << 14) /*!< DP: Add user=phone to numeric URI. Default off */
818 #define SIP_USECLIENTCODE (1 << 15) /*!< DP: Trust X-ClientCode info message */
820 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
821 #define SIP_DTMF (3 << 16) /*!< DP: DTMF Support: four settings, uses two bits */
822 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
823 #define SIP_DTMF_INBAND (1 << 16) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
824 #define SIP_DTMF_INFO (2 << 16) /*!< DP: DTMF Support: SIP Info messages - "info" */
825 #define SIP_DTMF_AUTO (3 << 16) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
826 #define SIP_DTMF_SHORTINFO (4 << 16) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
828 /* NAT settings - see nat2str() */
829 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
830 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
831 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
832 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
833 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
835 /* re-INVITE related settings */
836 #define SIP_REINVITE (7 << 20) /*!< DP: three bits used */
837 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
838 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
839 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
841 /* "insecure" settings - see insecure2str() */
842 #define SIP_INSECURE (3 << 23) /*!< DP: two bits used */
843 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
844 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
846 /* Sending PROGRESS in-band settings */
847 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
848 #define SIP_PROG_INBAND_NEVER (0 << 25)
849 #define SIP_PROG_INBAND_NO (1 << 25)
850 #define SIP_PROG_INBAND_YES (2 << 25)
852 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
853 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
855 /*! \brief Flags to copy from peer/user to dialog */
856 #define SIP_FLAGS_TO_COPY \
857 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
858 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
859 SIP_USEREQPHONE | SIP_INSECURE)
863 a second page of flags (for flags[1] */
866 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
867 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
868 /* Space for addition of other realtime flags in the future */
870 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14) /*!< DP: Video supported if offered? */
871 #define SIP_PAGE2_TEXTSUPPORT (1 << 15) /*!< GDP: Global text enable */
872 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
873 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
874 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
876 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
877 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
878 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
879 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
881 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
882 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
883 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
884 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
886 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
887 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
888 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
890 #define SIP_PAGE2_FLAGS_TO_COPY \
891 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
892 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
893 SIP_PAGE2_TEXTSUPPORT )
897 /*! \name SIPflagsT38
901 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
902 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
903 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
904 /* Rate management */
905 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
906 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
907 /* UDP Error correction */
908 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
909 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
910 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
911 /* T38 Spec version */
912 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
913 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
914 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
915 /* Maximum Fax Rate */
916 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
917 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
918 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
919 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
920 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
921 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
923 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
924 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
927 /*! \brief debugging state
928 * We store separately the debugging requests from the config file
929 * and requests from the CLI. Debugging is enabled if either is set
930 * (which means that if sipdebug is set in the config file, we can
931 * only turn it off by reloading the config).
935 sip_debug_config = 1,
936 sip_debug_console = 2,
939 static enum sip_debug_e sipdebug;
941 /*! \brief extra debugging for 'text' related events.
942 * At thie moment this is set together with sip_debug_console.
943 * It should either go away or be implemented properly.
945 static int sipdebug_text;
947 /*! \brief T38 States for a call */
949 T38_DISABLED = 0, /*!< Not enabled */
950 T38_LOCAL_DIRECT, /*!< Offered from local */
951 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
952 T38_PEER_DIRECT, /*!< Offered from peer */
953 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
954 T38_ENABLED /*!< Negotiated (enabled) */
957 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
958 struct t38properties {
959 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
960 int capability; /*!< Our T38 capability */
961 int peercapability; /*!< Peers T38 capability */
962 int jointcapability; /*!< Supported T38 capability at both ends */
963 enum t38state state; /*!< T.38 state */
966 /*! \brief Parameters to know status of transfer */
968 REFER_IDLE, /*!< No REFER is in progress */
969 REFER_SENT, /*!< Sent REFER to transferee */
970 REFER_RECEIVED, /*!< Received REFER from transferrer */
971 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
972 REFER_ACCEPTED, /*!< Accepted by transferee */
973 REFER_RINGING, /*!< Target Ringing */
974 REFER_200OK, /*!< Answered by transfer target */
975 REFER_FAILED, /*!< REFER declined - go on */
976 REFER_NOAUTH /*!< We had no auth for REFER */
979 /*! \brief generic struct to map between strings and integers.
980 * Fill it with x-s pairs, terminate with an entry with s = NULL;
981 * Then you can call map_x_s(...) to map an integer to a string,
982 * and map_s_x() for the string -> integer mapping.
989 static const struct _map_x_s referstatusstrings[] = {
990 { REFER_IDLE, "<none>" },
991 { REFER_SENT, "Request sent" },
992 { REFER_RECEIVED, "Request received" },
993 { REFER_CONFIRMED, "Confirmed" },
994 { REFER_ACCEPTED, "Accepted" },
995 { REFER_RINGING, "Target ringing" },
996 { REFER_200OK, "Done" },
997 { REFER_FAILED, "Failed" },
998 { REFER_NOAUTH, "Failed - auth failure" },
999 { -1, NULL} /* terminator */
1002 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1003 \note OEJ: Should be moved to string fields */
1005 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
1006 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
1007 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
1008 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
1009 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1010 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1011 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
1012 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
1013 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
1014 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
1015 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
1016 * dialog owned by someone else, so we should not destroy
1017 * it when the sip_refer object goes.
1019 int attendedtransfer; /*!< Attended or blind transfer? */
1020 int localtransfer; /*!< Transfer to local domain? */
1021 enum referstatus status; /*!< REFER status */
1024 /*! \brief sip_pvt: structures used for each SIP dialog, ie. a call, a registration, a subscribe.
1025 * Created and initialized by sip_alloc(), the descriptor goes into the list of
1026 * descriptors (dialoglist).
1029 struct sip_pvt *next; /*!< Next dialog in chain */
1030 ast_mutex_t pvt_lock; /*!< Dialog private lock */
1031 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
1032 int method; /*!< SIP method that opened this dialog */
1033 AST_DECLARE_STRING_FIELDS(
1034 AST_STRING_FIELD(callid); /*!< Global CallID */
1035 AST_STRING_FIELD(randdata); /*!< Random data */
1036 AST_STRING_FIELD(accountcode); /*!< Account code */
1037 AST_STRING_FIELD(realm); /*!< Authorization realm */
1038 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1039 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1040 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1041 AST_STRING_FIELD(domain); /*!< Authorization domain */
1042 AST_STRING_FIELD(from); /*!< The From: header */
1043 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1044 AST_STRING_FIELD(exten); /*!< Extension where to start */
1045 AST_STRING_FIELD(context); /*!< Context for this call */
1046 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1047 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1048 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1049 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1050 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1051 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1052 AST_STRING_FIELD(language); /*!< Default language for this call */
1053 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1054 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1055 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1056 AST_STRING_FIELD(redircause); /*!< Referring cause */
1057 AST_STRING_FIELD(theirtag); /*!< Their tag */
1058 AST_STRING_FIELD(username); /*!< [user] name */
1059 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1060 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1061 AST_STRING_FIELD(uri); /*!< Original requested URI */
1062 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1063 AST_STRING_FIELD(peersecret); /*!< Password */
1064 AST_STRING_FIELD(peermd5secret);
1065 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1066 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1067 AST_STRING_FIELD(via); /*!< Via: header */
1068 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1069 /* we only store the part in <brackets> in this field. */
1070 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1071 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1072 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1073 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1075 unsigned int ocseq; /*!< Current outgoing seqno */
1076 unsigned int icseq; /*!< Current incoming seqno */
1077 ast_group_t callgroup; /*!< Call group */
1078 ast_group_t pickupgroup; /*!< Pickup group */
1079 int lastinvite; /*!< Last Cseq of invite */
1080 int lastnoninvite; /*!< Last Cseq of non-invite */
1081 struct ast_flags flags[2]; /*!< SIP_ flags */
1083 /* boolean or small integers that don't belong in flags */
1084 char do_history; /*!< Set if we want to record history */
1085 char alreadygone; /*!< already destroyed by our peer */
1086 char needdestroy; /*!< need to be destroyed by the monitor thread */
1087 char outgoing_call; /*!< this is an outgoing call */
1088 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1089 char novideo; /*!< Didn't get video in invite, don't offer */
1090 char notext; /*!< Text not supported (?) */
1092 int timer_t1; /*!< SIP timer T1, ms rtt */
1093 int timer_b; /*!< SIP timer B, ms */
1094 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1095 struct ast_codec_pref prefs; /*!< codec prefs */
1096 int capability; /*!< Special capability (codec) */
1097 int jointcapability; /*!< Supported capability at both ends (codecs) */
1098 int peercapability; /*!< Supported peer capability */
1099 int prefcodec; /*!< Preferred codec (outbound only) */
1100 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1101 int jointnoncodeccapability; /*!< Joint Non codec capability */
1102 int redircodecs; /*!< Redirect codecs */
1103 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1104 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
1105 struct t38properties t38; /*!< T38 settings */
1106 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1107 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1108 int callingpres; /*!< Calling presentation */
1109 int authtries; /*!< Times we've tried to authenticate */
1110 int expiry; /*!< How long we take to expire */
1111 long branch; /*!< The branch identifier of this session */
1112 char tag[11]; /*!< Our tag for this session */
1113 int sessionid; /*!< SDP Session ID */
1114 int sessionversion; /*!< SDP Session Version */
1115 struct sockaddr_in sa; /*!< Our peer */
1116 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1117 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1118 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1119 time_t lastrtprx; /*!< Last RTP received */
1120 time_t lastrtptx; /*!< Last RTP sent */
1121 int rtptimeout; /*!< RTP timeout time */
1122 struct sockaddr_in recv; /*!< Received as */
1123 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1124 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1125 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1126 int route_persistant; /*!< Is this the "real" route? */
1127 struct sip_auth *peerauth; /*!< Realm authentication */
1128 int noncecount; /*!< Nonce-count */
1129 char lastmsg[256]; /*!< Last Message sent/received */
1130 int amaflags; /*!< AMA Flags */
1131 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
1132 struct sip_request initreq; /*!< Latest request that opened a new transaction
1134 NOT the request that opened the dialog
1137 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1138 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1139 int autokillid; /*!< Auto-kill ID (scheduler) */
1140 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1141 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1142 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1143 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1144 int laststate; /*!< SUBSCRIBE: Last known extension state */
1145 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1147 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1149 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1150 Used in peerpoke, mwi subscriptions */
1151 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1152 struct ast_rtp *rtp; /*!< RTP Session */
1153 struct ast_rtp *vrtp; /*!< Video RTP session */
1154 struct ast_rtp *trtp; /*!< Text RTP session */
1155 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1156 struct sip_history_head *history; /*!< History of this SIP dialog */
1157 size_t history_entries; /*!< Number of entires in the history */
1158 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1159 struct sip_invite_param *options; /*!< Options for INVITE */
1160 int autoframing; /*!< The number of Asters we group in a Pyroflax
1161 before strolling to the Grokyzpå
1162 (A bit unsure of this, please correct if
1166 /*! Max entires in the history list for a sip_pvt */
1167 #define MAX_HISTORY_ENTRIES 50
1170 * Here we implement the container for dialogs (sip_pvt), defining
1171 * generic wrapper functions to ease the transition from the current
1172 * implementation (a single linked list) to a different container.
1173 * In addition to a reference to the container, we need functions to lock/unlock
1174 * the container and individual items, and functions to add/remove
1175 * references to the individual items.
1177 static struct sip_pvt *dialoglist = NULL;
1179 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1180 AST_MUTEX_DEFINE_STATIC(dialoglock);
1182 #ifndef DETECT_DEADLOCKS
1183 /*! \brief hide the way the list is locked/unlocked */
1184 static void dialoglist_lock(void)
1186 ast_mutex_lock(&dialoglock);
1189 static void dialoglist_unlock(void)
1191 ast_mutex_unlock(&dialoglock);
1194 /* we don't want to HIDE the information about where the lock was requested if trying to debug
1195 * deadlocks! So, just make these macros! */
1196 #define dialoglist_lock(x) ast_mutex_lock(&dialoglock)
1197 #define dialoglist_unlock(x) ast_mutex_unlock(&dialoglock)
1201 * when we create or delete references, make sure to use these
1202 * functions so we keep track of the refcounts.
1203 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1205 static struct sip_pvt *dialog_ref(struct sip_pvt *p)
1210 static struct sip_pvt *dialog_unref(struct sip_pvt *p)
1215 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1216 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1217 * Each packet holds a reference to the parent struct sip_pvt.
1218 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1219 * require retransmissions.
1222 struct sip_pkt *next; /*!< Next packet in linked list */
1223 int retrans; /*!< Retransmission number */
1224 int method; /*!< SIP method for this packet */
1225 int seqno; /*!< Sequence number */
1226 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1227 char is_fatal; /*!< non-zero if there is a fatal error */
1228 struct sip_pvt *owner; /*!< Owner AST call */
1229 int retransid; /*!< Retransmission ID */
1230 int timer_a; /*!< SIP timer A, retransmission timer */
1231 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1232 int packetlen; /*!< Length of packet */
1236 /*! \brief Structure for SIP user data. User's place calls to us */
1238 /* Users who can access various contexts */
1239 ASTOBJ_COMPONENTS(struct sip_user);
1240 char secret[80]; /*!< Password */
1241 char md5secret[80]; /*!< Password in md5 */
1242 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1243 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1244 char cid_num[80]; /*!< Caller ID num */
1245 char cid_name[80]; /*!< Caller ID name */
1246 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1247 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1248 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1249 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1250 char useragent[256]; /*!< User agent in SIP request */
1251 struct ast_codec_pref prefs; /*!< codec prefs */
1252 ast_group_t callgroup; /*!< Call group */
1253 ast_group_t pickupgroup; /*!< Pickup Group */
1254 unsigned int sipoptions; /*!< Supported SIP options */
1255 struct ast_flags flags[2]; /*!< SIP_ flags */
1257 /* things that don't belong in flags */
1258 char is_realtime; /*!< this is a 'realtime' user */
1260 int amaflags; /*!< AMA flags for billing */
1261 int callingpres; /*!< Calling id presentation */
1262 int capability; /*!< Codec capability */
1263 int inUse; /*!< Number of calls in use */
1264 int call_limit; /*!< Limit of concurrent calls */
1265 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1266 struct ast_ha *ha; /*!< ACL setting */
1267 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1268 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1273 * \brief A peer's mailbox
1275 * We could use STRINGFIELDS here, but for only two strings, it seems like
1276 * too much effort ...
1278 struct sip_mailbox {
1281 /*! Associated MWI subscription */
1282 struct ast_event_sub *event_sub;
1283 AST_LIST_ENTRY(sip_mailbox) entry;
1286 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1287 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1289 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1290 /*!< peer->name is the unique name of this object */
1291 char secret[80]; /*!< Password */
1292 char md5secret[80]; /*!< Password in MD5 */
1293 struct sip_auth *auth; /*!< Realm authentication list */
1294 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1295 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1296 char username[80]; /*!< Temporary username until registration */
1297 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1298 int amaflags; /*!< AMA Flags (for billing) */
1299 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1300 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1301 char fromuser[80]; /*!< From: user when calling this peer */
1302 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1303 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1304 char cid_num[80]; /*!< Caller ID num */
1305 char cid_name[80]; /*!< Caller ID name */
1306 int callingpres; /*!< Calling id presentation */
1307 int inUse; /*!< Number of calls in use */
1308 int inRinging; /*!< Number of calls ringing */
1309 int onHold; /*!< Peer has someone on hold */
1310 int call_limit; /*!< Limit of concurrent calls */
1311 int busy_level; /*!< Level of active channels where we signal busy */
1312 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1313 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1314 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1315 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1316 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1317 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1318 struct ast_codec_pref prefs; /*!< codec prefs */
1320 unsigned int sipoptions; /*!< Supported SIP options */
1321 struct ast_flags flags[2]; /*!< SIP_ flags */
1323 /*! Mailboxes that this peer cares about */
1324 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1326 /* things that don't belong in flags */
1327 char is_realtime; /*!< this is a 'realtime' peer */
1328 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1329 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1330 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1332 int expire; /*!< When to expire this peer registration */
1333 int capability; /*!< Codec capability */
1334 int rtptimeout; /*!< RTP timeout */
1335 int rtpholdtimeout; /*!< RTP Hold Timeout */
1336 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1337 ast_group_t callgroup; /*!< Call group */
1338 ast_group_t pickupgroup; /*!< Pickup group */
1339 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1340 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1341 struct sockaddr_in addr; /*!< IP address of peer */
1342 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1345 struct sip_pvt *call; /*!< Call pointer */
1346 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1347 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1348 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1349 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1350 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1351 struct ast_ha *ha; /*!< Access control list */
1352 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1353 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1355 int timer_t1; /*!< The maximum T1 value for the peer */
1356 int timer_b; /*!< The maximum timer B (transaction timeouts) */
1360 /*! \brief Registrations with other SIP proxies
1361 * Created by sip_register(), the entry is linked in the 'regl' list,
1362 * and never deleted (other than at 'sip reload' or module unload times).
1363 * The entry always has a pending timeout, either waiting for an ACK to
1364 * the REGISTER message (in which case we have to retransmit the request),
1365 * or waiting for the next REGISTER message to be sent (either the initial one,
1366 * or once the previously completed registration one expires).
1367 * The registration can be in one of many states, though at the moment
1368 * the handling is a bit mixed.
1369 * Note that the entire evolution of sip_registry (transmissions,
1370 * incoming packets and timeouts) is driven by one single thread,
1371 * do_monitor(), so there is almost no synchronization issue.
1372 * The only exception is the sip_pvt creation/lookup,
1373 * as the dialoglist is also manipulated by other threads.
1375 struct sip_registry {
1376 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1377 AST_DECLARE_STRING_FIELDS(
1378 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1379 AST_STRING_FIELD(realm); /*!< Authorization realm */
1380 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1381 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1382 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1383 AST_STRING_FIELD(domain); /*!< Authorization domain */
1384 AST_STRING_FIELD(username); /*!< Who we are registering as */
1385 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1386 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1387 AST_STRING_FIELD(secret); /*!< Password in clear text */
1388 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1389 AST_STRING_FIELD(callback); /*!< Contact extension */
1390 AST_STRING_FIELD(random);
1392 int portno; /*!< Optional port override */
1393 int expire; /*!< Sched ID of expiration */
1394 int expiry; /*!< Value to use for the Expires header */
1395 int regattempts; /*!< Number of attempts (since the last success) */
1396 int timeout; /*!< sched id of sip_reg_timeout */
1397 int refresh; /*!< How often to refresh */
1398 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1399 enum sipregistrystate regstate; /*!< Registration state (see above) */
1400 struct timeval regtime; /*!< Last successful registration time */
1401 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1402 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1403 struct sockaddr_in us; /*!< Who the server thinks we are */
1404 int noncecount; /*!< Nonce-count */
1405 char lastmsg[256]; /*!< Last Message sent/received */
1408 /* --- Linked lists of various objects --------*/
1410 /*! \brief The user list: Users and friends */
1411 static struct ast_user_list {
1412 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1415 /*! \brief The peer list: Peers and Friends */
1416 static struct ast_peer_list {
1417 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1420 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1421 static struct ast_register_list {
1422 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1426 static int temp_pvt_init(void *);
1427 static void temp_pvt_cleanup(void *);
1429 /*! \brief A per-thread temporary pvt structure */
1430 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1432 /*! \brief Authentication list for realm authentication
1433 * \todo Move the sip_auth list to AST_LIST */
1434 static struct sip_auth *authl = NULL;
1437 /* --- Sockets and networking --------------*/
1439 /*! \brief Main socket for SIP communication.
1440 * sipsock is shared between the manager thread (which handles reload
1441 * requests), the io handler (sipsock_read()) and the user routines that
1442 * issue writes (using __sip_xmit()).
1443 * The socket is -1 only when opening fails (this is a permanent condition),
1444 * or when we are handling a reload() that changes its address (this is
1445 * a transient situation during which we might have a harmless race, see
1446 * below). Because the conditions for the race to be possible are extremely
1447 * rare, we don't want to pay the cost of locking on every I/O.
1448 * Rather, we remember that when the race may occur, communication is
1449 * bound to fail anyways, so we just live with this event and let
1450 * the protocol handle this above us.
1452 static int sipsock = -1;
1454 static struct sockaddr_in bindaddr; /*!< The address we bind to */
1456 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1457 * internip is initialized picking a suitable address from one of the
1458 * interfaces, and the same port number we bind to. It is used as the
1459 * default address/port in SIP messages, and as the default address
1460 * (but not port) in SDP messages.
1462 static struct sockaddr_in internip;
1464 /*! \brief our external IP address/port for SIP sessions.
1465 * externip.sin_addr is only set when we know we might be behind
1466 * a NAT, and this is done using a variety of (mutually exclusive)
1467 * ways from the config file:
1469 * + with "externip = host[:port]" we specify the address/port explicitly.
1470 * The address is looked up only once when (re)loading the config file;
1472 * + with "externhost = host[:port]" we do a similar thing, but the
1473 * hostname is stored in externhost, and the hostname->IP mapping
1474 * is refreshed every 'externrefresh' seconds;
1476 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1477 * to the specified server, and store the result in externip.
1479 * Other variables (externhost, externexpire, externrefresh) are used
1480 * to support the above functions.
1482 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1484 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1485 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1486 static int externrefresh = 10;
1487 static struct sockaddr_in stunaddr; /*!< stun server address */
1489 /*! \brief List of local networks
1490 * We store "localnet" addresses from the config file into an access list,
1491 * marked as 'DENY', so the call to ast_apply_ha() will return
1492 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1493 * (i.e. presumably public) addresses.
1495 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1497 static struct sockaddr_in debugaddr;
1499 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1501 /*! some list management macros. */
1503 #define UNLINK(element, head, prev) do { \
1505 (prev)->next = (element)->next; \
1507 (head) = (element)->next; \
1510 /*---------------------------- Forward declarations of functions in chan_sip.c */
1511 /*! \note This is added to help splitting up chan_sip.c into several files
1512 in coming releases */
1514 /*--- PBX interface functions */
1515 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1516 static int sip_devicestate(void *data);
1517 static int sip_sendtext(struct ast_channel *ast, const char *text);
1518 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1519 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1520 static int sip_hangup(struct ast_channel *ast);
1521 static int sip_answer(struct ast_channel *ast);
1522 static struct ast_frame *sip_read(struct ast_channel *ast);
1523 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1524 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1525 static int sip_transfer(struct ast_channel *ast, const char *dest);
1526 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1527 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1528 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1530 /*--- Transmitting responses and requests */
1531 static int sipsock_read(int *id, int fd, short events, void *ignore);
1532 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1533 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1534 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1535 static int retrans_pkt(const void *data);
1536 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1537 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);
1538 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1539 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1540 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1541 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1542 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1543 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);
1544 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1545 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1546 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1547 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1548 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1549 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1550 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1551 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1552 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1553 static int transmit_refer(struct sip_pvt *p, const char *dest);
1554 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1555 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1556 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1557 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1558 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1559 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1560 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1561 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1562 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1564 /*--- Dialog management */
1565 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1566 int useglobal_nat, const int intended_method);
1567 static int __sip_autodestruct(const void *data);
1568 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1569 static void sip_cancel_destroy(struct sip_pvt *p);
1570 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1571 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1572 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1573 static void __sip_pretend_ack(struct sip_pvt *p);
1574 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1575 static int auto_congest(const void *arg);
1576 static int update_call_counter(struct sip_pvt *fup, int event);
1577 static int hangup_sip2cause(int cause);
1578 static const char *hangup_cause2sip(int cause);
1579 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1580 static void free_old_route(struct sip_route *route);
1581 static void list_route(struct sip_route *route);
1582 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1583 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1584 struct sip_request *req, char *uri);
1585 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1586 static void check_pendings(struct sip_pvt *p);
1587 static void *sip_park_thread(void *stuff);
1588 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1589 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1591 /*--- Codec handling / SDP */
1592 static void try_suggested_sip_codec(struct sip_pvt *p);
1593 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1594 static const char *get_sdp(struct sip_request *req, const char *name);
1595 static int find_sdp(struct sip_request *req);
1596 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1597 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1598 struct ast_str **m_buf, struct ast_str **a_buf,
1599 int debug, int *min_packet_size);
1600 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1601 struct ast_str **m_buf, struct ast_str **a_buf,
1603 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1604 static void do_setnat(struct sip_pvt *p, int natflags);
1605 static void stop_media_flows(struct sip_pvt *p);
1607 /*--- Authentication stuff */
1608 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1609 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1610 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1611 const char *secret, const char *md5secret, int sipmethod,
1612 char *uri, enum xmittype reliable, int ignore);
1613 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1614 int sipmethod, char *uri, enum xmittype reliable,
1615 struct sockaddr_in *sin, struct sip_peer **authpeer);
1616 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1618 /*--- Domain handling */
1619 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1620 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1621 static void clear_sip_domains(void);
1623 /*--- SIP realm authentication */
1624 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1625 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1626 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1628 /*--- Misc functions */
1629 static int sip_do_reload(enum channelreloadreason reason);
1630 static int reload_config(enum channelreloadreason reason);
1631 static int expire_register(const void *data);
1632 static void *do_monitor(void *data);
1633 static int restart_monitor(void);
1634 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1635 static int sip_refer_allocate(struct sip_pvt *p);
1636 static void ast_quiet_chan(struct ast_channel *chan);
1637 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1639 /*--- Device monitoring and Device/extension state/event handling */
1640 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1641 static int sip_devicestate(void *data);
1642 static int sip_poke_noanswer(const void *data);
1643 static int sip_poke_peer(struct sip_peer *peer);
1644 static void sip_poke_all_peers(void);
1645 static void sip_peer_hold(struct sip_pvt *p, int hold);
1646 static void mwi_event_cb(const struct ast_event *, void *);
1648 /*--- Applications, functions, CLI and manager command helpers */
1649 static const char *sip_nat_mode(const struct sip_pvt *p);
1650 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1651 static char *transfermode2str(enum transfermodes mode) attribute_const;
1652 static const char *nat2str(int nat) attribute_const;
1653 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1654 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1655 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1656 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1657 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1658 static void print_group(int fd, ast_group_t group, int crlf);
1659 static const char *dtmfmode2str(int mode) attribute_const;
1660 static int str2dtmfmode(const char *str) attribute_unused;
1661 static const char *insecure2str(int mode) attribute_const;
1662 static void cleanup_stale_contexts(char *new, char *old);
1663 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1664 static const char *domain_mode_to_text(const enum domain_mode mode);
1665 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1666 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1667 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1668 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1669 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1670 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1671 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1672 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1673 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1674 static char *complete_sip_peer(const char *word, int state, int flags2);
1675 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1676 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1677 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1678 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1679 static char *complete_sip_user(const char *word, int state, int flags2);
1680 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1681 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1682 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1683 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1684 static char *sip_do_debug_ip(int fd, char *arg);
1685 static char *sip_do_debug_peer(int fd, char *arg);
1686 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1687 static char *sip_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1688 static char *sip_do_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1689 static char *sip_no_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1690 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1691 static int sip_addheader(struct ast_channel *chan, void *data);
1692 static int sip_do_reload(enum channelreloadreason reason);
1693 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1694 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1697 Functions for enabling debug per IP or fully, or enabling history logging for
1700 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1701 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1702 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1703 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1704 static void sip_dump_history(struct sip_pvt *dialog);
1706 /*--- Device object handling */
1707 static struct sip_peer *temp_peer(const char *name);
1708 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1709 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1710 static int update_call_counter(struct sip_pvt *fup, int event);
1711 static void sip_destroy_peer(struct sip_peer *peer);
1712 static void sip_destroy_user(struct sip_user *user);
1713 static int sip_poke_peer(struct sip_peer *peer);
1714 static void set_peer_defaults(struct sip_peer *peer);
1715 static struct sip_peer *temp_peer(const char *name);
1716 static void register_peer_exten(struct sip_peer *peer, int onoff);
1717 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1718 static struct sip_user *find_user(const char *name, int realtime);
1719 static int sip_poke_peer_s(const void *data);
1720 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1721 static void reg_source_db(struct sip_peer *peer);
1722 static void destroy_association(struct sip_peer *peer);
1723 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1724 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1726 /* Realtime device support */
1727 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1728 static struct sip_user *realtime_user(const char *username);
1729 static void update_peer(struct sip_peer *p, int expiry);
1730 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1731 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1732 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1733 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1735 /*--- Internal UA client handling (outbound registrations) */
1736 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
1737 static void sip_registry_destroy(struct sip_registry *reg);
1738 static int sip_register(const char *value, int lineno);
1739 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1740 static int sip_reregister(const void *data);
1741 static int __sip_do_register(struct sip_registry *r);
1742 static int sip_reg_timeout(const void *data);
1743 static void sip_send_all_registers(void);
1745 /*--- Parsing SIP requests and responses */
1746 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1747 static int determine_firstline_parts(struct sip_request *req);
1748 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1749 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1750 static int find_sip_method(const char *msg);
1751 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1752 static void parse_request(struct sip_request *req);
1753 static const char *get_header(const struct sip_request *req, const char *name);
1754 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1755 static int method_match(enum sipmethod id, const char *name);
1756 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1757 static char *get_in_brackets(char *tmp);
1758 static const char *find_alias(const char *name, const char *_default);
1759 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1760 static int lws2sws(char *msgbuf, int len);
1761 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1762 static char *remove_uri_parameters(char *uri);
1763 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1764 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1765 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1766 static int set_address_from_contact(struct sip_pvt *pvt);
1767 static void check_via(struct sip_pvt *p, struct sip_request *req);
1768 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1769 static int get_rpid_num(const char *input, char *output, int maxlen);
1770 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1771 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1772 static int get_msg_text(char *buf, int len, struct sip_request *req);
1773 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1775 /*--- Constructing requests and responses */
1776 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1777 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1778 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1779 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1780 static int init_resp(struct sip_request *resp, const char *msg);
1781 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1782 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1783 static void build_via(struct sip_pvt *p);
1784 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1785 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1786 static char *generate_random_string(char *buf, size_t size);
1787 static void build_callid_pvt(struct sip_pvt *pvt);
1788 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1789 static void make_our_tag(char *tagbuf, size_t len);
1790 static int add_header(struct sip_request *req, const char *var, const char *value);
1791 static int add_header_contentLength(struct sip_request *req, int len);
1792 static int add_line(struct sip_request *req, const char *line);
1793 static int add_text(struct sip_request *req, const char *text);
1794 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1795 static int add_vidupdate(struct sip_request *req);
1796 static void add_route(struct sip_request *req, struct sip_route *route);
1797 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1798 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1799 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1800 static void set_destination(struct sip_pvt *p, char *uri);
1801 static void append_date(struct sip_request *req);
1802 static void build_contact(struct sip_pvt *p);
1803 static void build_rpid(struct sip_pvt *p);
1805 /*------Request handling functions */
1806 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1807 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);
1808 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1809 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1810 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1811 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1812 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1813 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1814 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1815 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1816 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
1817 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1818 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1820 /*------Response handling functions */
1821 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1822 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1823 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1824 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1826 /*----- RTP interface functions */
1827 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);
1828 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1829 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1830 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1831 static int sip_get_codec(struct ast_channel *chan);
1832 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1834 /*------ T38 Support --------- */
1835 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
1836 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1837 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1838 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1840 /*! \brief Definition of this channel for PBX channel registration */
1841 static const struct ast_channel_tech sip_tech = {
1843 .description = "Session Initiation Protocol (SIP)",
1844 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
1845 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1846 .requester = sip_request_call, /* called with chan unlocked */
1847 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1848 .call = sip_call, /* called with chan locked */
1849 .send_html = sip_sendhtml,
1850 .hangup = sip_hangup, /* called with chan locked */
1851 .answer = sip_answer, /* called with chan locked */
1852 .read = sip_read, /* called with chan locked */
1853 .write = sip_write, /* called with chan locked */
1854 .write_video = sip_write, /* called with chan locked */
1855 .write_text = sip_write,
1856 .indicate = sip_indicate, /* called with chan locked */
1857 .transfer = sip_transfer, /* called with chan locked */
1858 .fixup = sip_fixup, /* called with chan locked */
1859 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1860 .send_digit_end = sip_senddigit_end,
1861 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
1862 .early_bridge = ast_rtp_early_bridge,
1863 .send_text = sip_sendtext, /* called with chan locked */
1864 .func_channel_read = acf_channel_read,
1867 /*! \brief This version of the sip channel tech has no send_digit_begin
1868 * callback so that the core knows that the channel does not want
1869 * DTMF BEGIN frames.
1870 * The struct is initialized just before registering the channel driver,
1871 * and is for use with channels using SIP INFO DTMF.
1873 static struct ast_channel_tech sip_tech_info;
1875 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
1876 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
1878 /*! \brief map from an integer value to a string.
1879 * If no match is found, return errorstring
1881 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
1883 const struct _map_x_s *cur;
1885 for (cur = table; cur->s; cur++)
1891 /*! \brief map from a string to an integer value, case insensitive.
1892 * If no match is found, return errorvalue.
1894 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
1896 const struct _map_x_s *cur;
1898 for (cur = table; cur->s; cur++)
1899 if (!strcasecmp(cur->s, s))
1905 /*! \brief Interface structure with callbacks used to connect to RTP module */
1906 static struct ast_rtp_protocol sip_rtp = {
1908 .get_rtp_info = sip_get_rtp_peer,
1909 .get_vrtp_info = sip_get_vrtp_peer,
1910 .get_trtp_info = sip_get_trtp_peer,
1911 .set_rtp_peer = sip_set_rtp_peer,
1912 .get_codec = sip_get_codec,
1915 #define sip_pvt_lock(x) ast_mutex_lock(&x->pvt_lock)
1916 #define sip_pvt_unlock(x) ast_mutex_unlock(&x->pvt_lock)
1919 * helper functions to unreference various types of objects.
1920 * By handling them this way, we don't have to declare the
1921 * destructor on each call, which removes the chance of errors.
1923 static void unref_peer(struct sip_peer *peer)
1925 ASTOBJ_UNREF(peer, sip_destroy_peer);
1928 static void unref_user(struct sip_user *user)
1930 ASTOBJ_UNREF(user, sip_destroy_user);
1933 static void *registry_unref(struct sip_registry *reg)
1935 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
1936 ASTOBJ_UNREF(reg, sip_registry_destroy);
1940 /*! \brief Add object reference to SIP registry */
1941 static struct sip_registry *registry_addref(struct sip_registry *reg)
1943 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
1944 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
1947 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1948 static struct ast_udptl_protocol sip_udptl = {
1950 get_udptl_info: sip_get_udptl_peer,
1951 set_udptl_peer: sip_set_udptl_peer,
1954 /*! \brief Append to SIP dialog history
1955 \return Always returns 0 */
1956 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1958 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1959 __attribute__ ((format (printf, 2, 3)));
1962 /*! \brief Convert transfer status to string */
1963 static const char *referstatus2str(enum referstatus rstatus)
1965 return map_x_s(referstatusstrings, rstatus, "");
1968 /*! \brief Initialize the initital request packet in the pvt structure.
1969 This packet is used for creating replies and future requests in
1971 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1973 if (p->initreq.headers)
1974 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1976 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1977 /* Use this as the basis */
1978 copy_request(&p->initreq, req);
1979 parse_request(&p->initreq);
1981 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1984 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1985 static void sip_alreadygone(struct sip_pvt *dialog)
1987 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1988 dialog->alreadygone = 1;
1991 /*! Resolve DNS srv name or host name in a sip_proxy structure */
1992 static int proxy_update(struct sip_proxy *proxy)
1994 /* if it's actually an IP address and not a name,
1995 there's no need for a managed lookup */
1996 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
1997 /* Ok, not an IP address, then let's check if it's a domain or host */
1998 /* XXX Todo - if we have proxy port, don't do SRV */
1999 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
2000 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2004 proxy->last_dnsupdate = time(NULL);
2008 /*! \brief Allocate and initialize sip proxy */
2009 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2011 struct sip_proxy *proxy;
2012 proxy = ast_calloc(1, sizeof(*proxy));
2015 proxy->force = force;
2016 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2017 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2018 proxy_update(proxy);
2022 /*! \brief Get default outbound proxy or global proxy */
2023 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2025 if (peer && peer->outboundproxy) {
2027 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2028 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2029 return peer->outboundproxy;
2031 if (global_outboundproxy.name[0]) {
2033 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2034 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2035 return &global_outboundproxy;
2038 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2042 /*! \brief returns true if 'name' (with optional trailing whitespace)
2043 * matches the sip method 'id'.
2044 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2045 * a case-insensitive comparison to be more tolerant.
2046 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2048 static int method_match(enum sipmethod id, const char *name)
2050 int len = strlen(sip_methods[id].text);
2051 int l_name = name ? strlen(name) : 0;
2052 /* true if the string is long enough, and ends with whitespace, and matches */
2053 return (l_name >= len && name[len] < 33 &&
2054 !strncasecmp(sip_methods[id].text, name, len));
2057 /*! \brief find_sip_method: Find SIP method from header */
2058 static int find_sip_method(const char *msg)
2062 if (ast_strlen_zero(msg))
2064 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
2065 if (method_match(i, msg))
2066 res = sip_methods[i].id;
2071 /*! \brief Parse supported header in incoming packet */
2072 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2076 unsigned int profile = 0;
2079 if (ast_strlen_zero(supported) )
2081 temp = ast_strdupa(supported);
2084 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2086 for (next = temp; next; next = sep) {
2088 if ( (sep = strchr(next, ',')) != NULL)
2090 next = ast_skip_blanks(next);
2092 ast_debug(3, "Found SIP option: -%s-\n", next);
2093 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
2094 if (!strcasecmp(next, sip_options[i].text)) {
2095 profile |= sip_options[i].id;
2098 ast_debug(3, "Matched SIP option: %s\n", next);
2102 if (!found && sipdebug) {
2103 if (!strncasecmp(next, "x-", 2))
2104 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2106 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2111 pvt->sipoptions = profile;
2115 /*! \brief See if we pass debug IP filter */
2116 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2120 if (debugaddr.sin_addr.s_addr) {
2121 if (((ntohs(debugaddr.sin_port) != 0)
2122 && (debugaddr.sin_port != addr->sin_port))
2123 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2129 /*! \brief The real destination address for a write */
2130 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2132 if (p->outboundproxy)
2133 return &p->outboundproxy->ip;
2135 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2138 /*! \brief Display SIP nat mode */
2139 static const char *sip_nat_mode(const struct sip_pvt *p)
2141 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2144 /*! \brief Test PVT for debugging output */
2145 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2149 return sip_debug_test_addr(sip_real_dst(p));
2152 /*! \brief Transmit SIP message */
2153 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
2156 const struct sockaddr_in *dst = sip_real_dst(p);
2157 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2161 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2162 case EHOSTUNREACH: /* Host can't be reached */
2163 case ENETDOWN: /* Interface down */
2164 case ENETUNREACH: /* Network failure */
2165 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2169 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));
2174 /*! \brief Build a Via header for a request */
2175 static void build_via(struct sip_pvt *p)
2177 /* Work around buggy UNIDEN UIP200 firmware */
2178 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2180 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2181 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
2182 ast_inet_ntoa(p->ourip.sin_addr),
2183 ntohs(p->ourip.sin_port), p->branch, rport);
2186 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2188 * Using the localaddr structure built up with localnet statements in sip.conf
2189 * apply it to their address to see if we need to substitute our
2190 * externip or can get away with our internal bindaddr
2191 * 'us' is always overwritten.
2193 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2195 struct sockaddr_in theirs;
2196 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2197 * reachable IP address and port. This is done if:
2198 * 1. we have a localaddr list (containing 'internal' addresses marked
2199 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2200 * and AST_SENSE_ALLOW on 'external' ones);
2201 * 2. either stunaddr or externip is set, so we know what to use as the
2202 * externally visible address;
2203 * 3. the remote address, 'them', is external;
2204 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2205 * when passed to ast_apply_ha() so it does need to be remapped.
2206 * This fourth condition is checked later.
2210 *us = internip; /* starting guess for the internal address */
2211 /* now ask the system what would it use to talk to 'them' */
2212 ast_ouraddrfor(them, &us->sin_addr);
2213 theirs.sin_addr = *them;
2215 want_remap = localaddr &&
2216 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2217 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2220 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2221 /* if we used externhost or stun, see if it is time to refresh the info */
2222 if (externexpire && time(NULL) >= externexpire) {
2223 if (stunaddr.sin_addr.s_addr) {
2224 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2226 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2227 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2229 externexpire = time(NULL) + externrefresh;
2231 if (externip.sin_addr.s_addr)
2234 ast_log(LOG_WARNING, "stun failed\n");
2235 ast_debug(1, "Target address %s is not local, substituting externip\n",
2236 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2237 } else if (bindaddr.sin_addr.s_addr) {
2238 /* no remapping, but we bind to a specific address, so use it. */
2243 /*! \brief Append to SIP dialog history with arg list */
2244 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2246 char buf[80], *c = buf; /* max history length */
2247 struct sip_history *hist;
2250 vsnprintf(buf, sizeof(buf), fmt, ap);
2251 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2252 l = strlen(buf) + 1;
2253 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2255 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2259 memcpy(hist->event, buf, l);
2260 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2261 struct sip_history *oldest;
2262 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2263 p->history_entries--;
2266 AST_LIST_INSERT_TAIL(p->history, hist, list);
2267 p->history_entries++;
2270 /*! \brief Append to SIP dialog history with arg list */
2271 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2278 if (!p->do_history && !recordhistory && !dumphistory)
2282 append_history_va(p, fmt, ap);
2288 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2289 static int retrans_pkt(const void *data)
2291 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2292 int reschedule = DEFAULT_RETRANS;
2295 /* Lock channel PVT */
2296 sip_pvt_lock(pkt->owner);
2298 if (pkt->retrans < MAX_RETRANS) {
2300 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2302 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);
2307 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2311 pkt->timer_a = 2 * pkt->timer_a;
2313 /* For non-invites, a maximum of 4 secs */
2314 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2315 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2318 /* Reschedule re-transmit */
2319 reschedule = siptimer_a;
2320 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);
2323 if (sip_debug_test_pvt(pkt->owner)) {
2324 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2325 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2326 pkt->retrans, sip_nat_mode(pkt->owner),
2327 ast_inet_ntoa(dst->sin_addr),
2328 ntohs(dst->sin_port), pkt->data);
2331 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
2332 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2333 sip_pvt_unlock(pkt->owner);
2334 if (xmitres == XMIT_ERROR)
2335 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2339 /* Too many retries */
2340 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2341 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2342 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n",
2343 pkt->owner->callid, pkt->seqno,
2344 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2345 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2346 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2349 if (xmitres == XMIT_ERROR) {
2350 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2351 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2353 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2355 pkt->retransid = -1;
2357 if (pkt->is_fatal) {
2358 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2359 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2361 sip_pvt_lock(pkt->owner);
2364 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
2365 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2367 if (pkt->owner->owner) {
2368 sip_alreadygone(pkt->owner);
2369 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2370 ast_queue_hangup(pkt->owner->owner);
2371 ast_channel_unlock(pkt->owner->owner);
2373 /* If no channel owner, destroy now */
2375 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2376 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2377 pkt->owner->needdestroy = 1;
2378 sip_alreadygone(pkt->owner);
2379 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2384 if (pkt->method == SIP_BYE) {
2385 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
2386 if (pkt->owner->owner)
2387 ast_channel_unlock(pkt->owner->owner);
2388 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2389 pkt->owner->needdestroy = 1;
2392 /* Remove the packet */
2393 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2395 UNLINK(cur, pkt->owner->packets, prev);
2396 sip_pvt_unlock(pkt->owner);
2402 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2403 sip_pvt_unlock(pkt->owner);
2407 /*! \brief Transmit packet with retransmits
2408 \return 0 on success, -1 on failure to allocate packet
2410 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2412 struct sip_pkt *pkt;
2413 int siptimer_a = DEFAULT_RETRANS;
2416 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2418 /* copy data, add a terminator and save length */
2419 memcpy(pkt->data, data, len);
2420 pkt->data[len] = '\0';
2421 pkt->packetlen = len;
2422 /* copy other parameters from the caller */
2423 pkt->method = sipmethod;
2425 pkt->is_resp = resp;
2426 pkt->is_fatal = fatal;
2427 pkt->owner = dialog_ref(p);
2428 pkt->next = p->packets;
2430 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2432 siptimer_a = pkt->timer_t1 * 2;
2434 /* Schedule retransmission */
2435 pkt->retransid = ast_sched_replace_variable(pkt->retransid, sched,
2436 siptimer_a, retrans_pkt, pkt, 1);
2438 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2439 if (sipmethod == SIP_INVITE) {
2440 /* Note this is a pending invite */
2441 p->pendinginvite = seqno;
2444 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2446 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2447 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2448 ast_sched_del(sched, pkt->retransid); /* No more retransmission */
2449 pkt->retransid = -1;
2455 /*! \brief Kill a SIP dialog (called only by the scheduler)
2456 * The scheduler has a reference to this dialog when p->autokillid != -1,
2457 * and we are called using that reference. So if the event is not
2458 * rescheduled, we need to call dialog_unref().
2460 static int __sip_autodestruct(const void *data)
2462 struct sip_pvt *p = (struct sip_pvt *)data;
2464 /* If this is a subscription, tell the phone that we got a timeout */
2465 if (p->subscribed) {
2466 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2467 p->subscribed = NONE;
2468 append_history(p, "Subscribestatus", "timeout");
2469 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
2470 return 10000; /* Reschedule this destruction so that we know that it's gone */
2473 /* If there are packets still waiting for delivery, delay the destruction */
2475 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2476 append_history(p, "ReliableXmit", "timeout");
2480 if (p->subscribed == MWI_NOTIFICATION)
2482 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2484 /* Reset schedule ID */
2488 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2489 ast_queue_hangup(p->owner);
2491 } else if (p->refer) {
2492 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
2493 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2494 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2495 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2498 append_history(p, "AutoDestroy", "%s", p->callid);
2499 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
2500 sip_destroy(p); /* Go ahead and destroy dialog. All attempts to recover is done */
2501 /* sip_destroy also absorbs the reference */
2506 /*! \brief Schedule destruction of SIP dialog */
2507 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2510 if (p->timer_t1 == 0) {
2511 p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
2512 p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
2514 ms = p->timer_t1 * 64;
2516 if (sip_debug_test_pvt(p))
2517 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2518 sip_cancel_destroy(p);
2520 append_history(p, "SchedDestroy", "%d ms", ms);
2521 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p));
2524 /*! \brief Cancel destruction of SIP dialog.
2525 * Be careful as this also absorbs the reference - if you call it
2526 * from within the scheduler, this might be the last reference.
2528 static void sip_cancel_destroy(struct sip_pvt *p)
2530 if (p->autokillid > -1) {
2531 ast_sched_del(sched, p->autokillid);
2532 append_history(p, "CancelDestroy", "");
2538 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2539 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2541 struct sip_pkt *cur, *prev = NULL;
2542 const char *msg = "Not Found"; /* used only for debugging */
2546 /* If we have an outbound proxy for this dialog, then delete it now since
2547 the rest of the requests in this dialog needs to follow the routing.
2548 If obforcing is set, we will keep the outbound proxy during the whole
2549 dialog, regardless of what the SIP rfc says
2551 if (p->outboundproxy && !p->outboundproxy->force)
2552 p->outboundproxy = NULL;
2554 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2555 if (cur->seqno != seqno || cur->is_resp != resp)
2557 if (cur->is_resp || cur->method == sipmethod) {
2559 if (!resp && (seqno == p->pendinginvite)) {
2560 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
2561 p->pendinginvite = 0;
2563 if (cur->retransid > -1) {
2565 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2566 ast_sched_del(sched, cur->retransid);
2567 cur->retransid = -1;
2569 UNLINK(cur, p->packets, prev);
2570 dialog_unref(cur->owner);
2576 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2577 p->callid, resp ? "Response" : "Request", seqno, msg);
2580 /*! \brief Pretend to ack all packets
2581 * maybe the lock on p is not strictly necessary but there might be a race */
2582 static void __sip_pretend_ack(struct sip_pvt *p)
2584 struct sip_pkt *cur = NULL;
2586 while (p->packets) {
2588 if (cur == p->packets) {
2589 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2593 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2594 __sip_ack(p, cur->seqno, cur->is_resp, method);
2598 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2599 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2601 struct sip_pkt *cur;
2604 for (cur = p->packets; cur; cur = cur->next) {
2605 if (cur->seqno == seqno && cur->is_resp == resp &&
2606 (cur->is_resp || method_match(sipmethod, cur->data))) {
2607 /* this is our baby */
2608 if (cur->retransid > -1) {
2610 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2611 ast_sched_del(sched, cur->retransid);
2612 cur->retransid = -1;
2618 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");
2623 /*! \brief Copy SIP request, parse it */
2624 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2626 memset(dst, 0, sizeof(*dst));
2627 memcpy(dst->data, src->data, sizeof(dst->data));
2628 dst->len = src->len;
2632 /*! \brief add a blank line if no body */
2633 static void add_blank(struct sip_request *req)
2636 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2637 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
2638 req->len += strlen(req->data + req->len);
2642 /*! \brief Transmit response on SIP request*/
2643 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2648 if (sip_debug_test_pvt(p)) {
2649 const struct sockaddr_in *dst = sip_real_dst(p);
2651 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2652 reliable ? "Reliably " : "", sip_nat_mode(p),
2653 ast_inet_ntoa(dst->sin_addr),
2654 ntohs(dst->sin_port), req->data);
2656 if (p->do_history) {
2657 struct sip_request tmp;
2658 parse_copy(&tmp, req);
2659 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2660 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2663 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2664 __sip_xmit(p, req->data, req->len);
2670 /*! \brief Send SIP Request to the other part of the dialogue */
2671 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2675 /* If we have an outbound proxy, reset peer address
2678 if (p->outboundproxy) {
2679 p->sa = p->outboundproxy->ip;
2683 if (sip_debug_test_pvt(p)) {
2684 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2685 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);
2687 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);
2689 if (p->do_history) {
2690 struct sip_request tmp;
2691 parse_copy(&tmp, req);
2692 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2695 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2696 __sip_xmit(p, req->data, req->len);
2700 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2701 * optionally with a limit on the search.
2702 * start must be past the first quote.
2704 static const char *find_closing_quote(const char *start, const char *lim)
2706 char last_char = '\0';
2708 for (s = start; *s && s != lim; last_char = *s++) {
2709 if (*s == '"' && last_char != '\\')
2715 /*! \brief Pick out text in brackets from character string
2716 \return pointer to terminated stripped string
2717 \param tmp input string that will be modified
2720 "foo" <bar> valid input, returns bar
2721 foo returns the whole string
2722 < "foo ... > returns the string between brackets
2723 < "foo... bogus (missing closing bracket), returns the whole string
2724 XXX maybe should still skip the opening bracket
2727 static char *get_in_brackets(char *tmp)
2729 const char *parse = tmp;
2730 char *first_bracket;
2733 * Skip any quoted text until we find the part in brackets.
2734 * On any error give up and return the full string.
2736 while ( (first_bracket = strchr(parse, '<')) ) {
2737 char *first_quote = strchr(parse, '"');
2739 if (!first_quote || first_quote > first_bracket)
2740 break; /* no need to look at quoted part */
2741 /* the bracket is within quotes, so ignore it */
2742 parse = find_closing_quote(first_quote + 1, NULL);
2743 if (!*parse) { /* not found, return full string ? */
2744 /* XXX or be robust and return in-bracket part ? */
2745 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2750 if (first_bracket) {
2751 char *second_bracket = strchr(first_bracket + 1, '>');
2752 if (second_bracket) {
2753 *second_bracket = '\0';
2754 tmp = first_bracket + 1;
2756 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2762 /*! \brief * parses a URI in its components.
2765 * - If scheme is specified, drop it from the top.
2766 * - If a component is not requested, do not split around it.
2768 * This means that if we don't have domain, we cannot split
2769 * name:pass and domain:port.
2770 * It is safe to call with ret_name, pass, domain, port
2771 * pointing all to the same place.
2772 * Init pointers to empty string so we never get NULL dereferencing.
2773 * Overwrites the string.
2774 * return 0 on success, other values on error.
2776 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
2779 static int parse_uri(char *uri, char *scheme,
2780 char **ret_name, char **pass, char **domain, char **port, char **options)
2785 /* init field as required */
2791 int l = strlen(scheme);
2792 if (!strncasecmp(uri, scheme, l))
2795 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, uri);
2800 /* if we don't want to split around domain, keep everything as a name,
2801 * so we need to do nothing here, except remember why.
2804 /* store the result in a temp. variable to avoid it being
2805 * overwritten if arguments point to the same place.
2809 if ((c = strchr(uri, '@')) == NULL) {
2810 /* domain-only URI, according to the SIP RFC. */
2819 /* Remove options in domain and name */
2820 dom = strsep(&dom, ";");
2821 name = strsep(&name, ";");
2823 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2827 if (pass && (c = strchr(name, ':'))) { /* user:password */
2833 if (ret_name) /* same as for domain, store the result only at the end */
2836 *options = uri ? uri : "";
2841 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
2842 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2844 struct sip_pvt *p = chan->tech_pvt;
2846 if (subclass != AST_HTML_URL)
2849 ast_string_field_build(p, url, "<%s>;mode=active", data);
2851 if (sip_debug_test_pvt(p))
2852 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
2854 switch (chan->_state) {
2855 case AST_STATE_RING:
2856 transmit_response(p, "100 Trying", &p->initreq);
2858 case AST_STATE_RINGING:
2859 transmit_response(p, "180 Ringing", &p->initreq);
2862 if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
2863 transmit_reinvite_with_sdp(p, FALSE);
2864 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
2865 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
2869 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
2875 /*! \brief Send SIP MESSAGE text within a call
2876 Called from PBX core sendtext() application */
2877 static int sip_sendtext(struct ast_channel *ast, const char *text)
2879 struct sip_pvt *p = ast->tech_pvt;
2880 int debug = sip_debug_test_pvt(p);
2883 ast_verbose("Sending text %s on %s\n", text, ast->name);
2886 if (ast_strlen_zero(text))
2889 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2890 transmit_message_with_text(p, text);
2894 /*! \brief Update peer object in realtime storage
2895 If the Asterisk system name is set in asterisk.conf, we will use
2896 that name and store that in the "regserver" field in the sippeers
2897 table to facilitate multi-server setups.
2899 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, int expirey)
2902 char ipaddr[INET_ADDRSTRLEN];
2903 char regseconds[20];
2904 char *tablename = NULL;
2906 char *sysname = ast_config_AST_SYSTEM_NAME;
2907 char *syslabel = NULL;
2909 time_t nowtime = time(NULL) + expirey;
2910 const char *fc = fullcontact ? "fullcontact" : NULL;
2912 int realtimeregs = ast_check_realtime("sipregs");
2914 tablename = realtimeregs ? "sipregs" : "sippeers";
2916 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2917 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2918 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2920 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2922 else if (sip_cfg.rtsave_sysname)
2923 syslabel = "regserver";
2926 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2927 "port", port, "regseconds", regseconds,
2928 "defaultuser", defaultuser, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2930 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2931 "port", port, "regseconds", regseconds,
2932 "defaultuser", defaultuser, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2935 /*! \brief Automatically add peer extension to dial plan */
2936 static void register_peer_exten(struct sip_peer *peer, int onoff)
2939 char *stringp, *ext, *context;
2941 /* XXX note that global_regcontext is both a global 'enable' flag and
2942 * the name of the global regexten context, if not specified
2945 if (ast_strlen_zero(global_regcontext))
2948 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2950 while ((ext = strsep(&stringp, "&"))) {
2951 if ((context = strchr(ext, '@'))) {
2952 *context++ = '\0'; /* split ext@context */
2953 if (!ast_context_find(context)) {
2954 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2958 context = global_regcontext;
2961 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2962 ast_strdup(peer->name), ast_free_ptr, "SIP");
2964 ast_context_remove_extension(context, ext, 1, NULL);
2968 /*! Destroy mailbox subscriptions */
2969 static void destroy_mailbox(struct sip_mailbox *mailbox)
2971 if (mailbox->mailbox)
2972 ast_free(mailbox->mailbox);
2973 if (mailbox->context)
2974 ast_free(mailbox->context);
2975 if (mailbox->event_sub)
2976 ast_event_unsubscribe(mailbox->event_sub);
2980 /*! Destroy all peer-related mailbox subscriptions */
2981 static void clear_peer_mailboxes(struct sip_peer *peer)
2983 struct sip_mailbox *mailbox;
2985 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
2986 destroy_mailbox(mailbox);
2989 /*! \brief Destroy peer object from memory */
2990 static void sip_destroy_peer(struct sip_peer *peer)
2992 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
2994 if (peer->outboundproxy)
2995 ast_free(peer->outboundproxy);
2996 peer->outboundproxy = NULL;
2998 /* Delete it, it needs to disappear */
3000 peer->call = sip_destroy(peer->call);
3002 if (peer->mwipvt) /* We have an active subscription, delete it */
3003 peer->mwipvt = sip_destroy(peer->mwipvt);
3005 if (peer->chanvars) {
3006 ast_variables_destroy(peer->chanvars);
3007 peer->chanvars = NULL;
3009 if (peer->expire > -1)
3010 ast_sched_del(sched, peer->expire);
3012 if (peer->pokeexpire > -1)
3013 ast_sched_del(sched, peer->pokeexpire);
3014 register_peer_exten(peer, FALSE);
3015 ast_free_ha(peer->ha);
3016 if (peer->selfdestruct)
3018 else if (peer->is_realtime) {
3020 ast_debug(3,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
3023 clear_realm_authentication(peer->auth);
3026 ast_dnsmgr_release(peer->dnsmgr);
3027 clear_peer_mailboxes(peer);
3031 /*! \brief Update peer data in database (if used) */
3032 static void update_peer(struct sip_peer *p, int expiry)
3034 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
3035 if (sip_cfg.peer_rtupdate &&
3036 (p->is_realtime || rtcachefriends)) {
3037 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
3041 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config)
3043 struct ast_variable *var = NULL;
3044 struct ast_flags flags = {0};
3046 const char *insecure;
3047 while ((cat = ast_category_browse(config, cat))) {
3048 insecure = ast_variable_retrieve(config, cat, "insecure");
3049 set_insecure_flags(&flags, insecure, -1);
3050 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
3051 var = ast_category_root(config, cat);
3058 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
3060 struct ast_variable *tmp;
3061 for (tmp = var; tmp; tmp = tmp->next) {
3062 if (!newpeername && !strcasecmp(tmp->name, "name"))
3063 newpeername = tmp->value;
3068 /*! \brief realtime_peer: Get peer from realtime storage
3069 * Checks the "sippeers" realtime family from extconfig.conf
3070 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
3072 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
3074 struct sip_peer *peer;
3075 struct ast_variable *var = NULL;
3076 struct ast_variable *varregs = NULL;
3077 struct ast_variable *tmp;
3078 struct ast_config *peerlist = NULL;
3079 char ipaddr[INET_ADDRSTRLEN];
3080 char portstring[6]; /*up to 5 digits plus null terminator*/
3082 unsigned short portnum;
3083 int realtimeregs = ast_check_realtime("sipregs");
3085 /* First check on peer name */
3087 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3089 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3090 } else if (sin) { /* Then check on IP address for dynamic peers */
3091 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3092 portnum = ntohs(sin->sin_port);
3093 sprintf(portstring, "%u", portnum);
3094 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, NULL); /* First check for fixed IP hosts */
3097 newpeername = get_name_from_variable(var, newpeername);
3098 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3102 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
3104 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
3106 newpeername = get_name_from_variable(varregs, newpeername);
3107 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3110 if(!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
3111 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, NULL);
3113 var = get_insecure_variable_from_config(peerlist);
3116 newpeername = get_name_from_variable(var, newpeername);
3117 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3119 } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
3122 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
3124 var = get_insecure_variable_from_config(peerlist);
3127 newpeername = get_name_from_variable(var, newpeername);
3128 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3135 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, NULL);
3137 varregs = get_insecure_variable_from_config(peerlist);
3139 newpeername = get_name_from_variable(varregs, newpeername);
3140 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3144 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
3146 var = get_insecure_variable_from_config(peerlist);
3148 newpeername = get_name_from_variable(var, newpeername);
3149 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3159 ast_config_destroy(peerlist);
3163 for (tmp = var; tmp; tmp = tmp->next) {
3164 /* If this is type=user, then skip this object. */
3165 if (!strcasecmp(tmp->name, "type") &&
3166 !strcasecmp(tmp->value, "user")) {
3168 ast_config_destroy(peerlist);
3170 ast_variables_destroy(var);
3171 ast_variables_destroy(varregs);
3174 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
3175 newpeername = tmp->value;
3179 if (!newpeername) { /* Did not find peer in realtime */
3180 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
3182 ast_config_destroy(peerlist);
3184 ast_variables_destroy(var);
3189 /* Peer found in realtime, now build it in memory */
3190 peer = build_peer(newpeername, var, varregs, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
3193 ast_config_destroy(peerlist);
3195 ast_variables_destroy(var);
3196 ast_variables_destroy(varregs);
3201 ast_debug(3,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
3203 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
3205 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
3206 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
3207 peer->expire = ast_sched_replace(peer->expire, sched,
3208 global_rtautoclear * 1000, expire_register, (void *) peer);
3210 ASTOBJ_CONTAINER_LINK(&peerl,peer);
3212 peer->is_realtime = 1;
3215 ast_config_destroy(peerlist);
3217 ast_variables_destroy(var);
3218 ast_variables_destroy(varregs);
3224 /*! \brief Support routine for find_peer */
3225 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
3227 /* We know name is the first field, so we can cast */
3228 struct sip_peer *p = (struct sip_peer *) name;
3229 return !(!inaddrcmp(&p->addr, sin) ||
3230 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
3231 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
3234 /*! \brief Locate peer by name or ip address
3235 * This is used on incoming SIP message to find matching peer on ip
3236 or outgoing message to find matching peer on name
3237 \note Avoid using this function in new functions if there's a way to avoid it, i
3238 since it causes a database lookup or a traversal of the in-memory peer list.
3240 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
3242 struct sip_peer *p = NULL;
3245 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
3247 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
3250 p = realtime_peer(peer, sin);
3255 /*! \brief Remove user object from in-memory storage */
3256 static void sip_destroy_user(struct sip_user *user)
3258 ast_debug(3, "Destroying user object from memory: %s\n", user->name);
3259 ast_free_ha(user->ha);
3260 if (user->chanvars) {
3261 ast_variables_destroy(user->chanvars);
3262 user->chanvars = NULL;
3264 if (user->is_realtime)
3271 /*! \brief Load user from realtime storage
3272 * Loads user from "sipusers" category in realtime (extconfig.conf)
3273 * Users are matched on From: user name (the domain in skipped) */
3274 static struct sip_user *realtime_user(const char *username)
3276 struct ast_variable *var;
3277 struct ast_variable *tmp;
3278 struct sip_user *user = NULL;
3280 var = ast_load_realtime("sipusers", "name", username, NULL);
3285 for (tmp = var; tmp; tmp = tmp->next) {
3286 if (!strcasecmp(tmp->name, "type") &&
3287 !strcasecmp(tmp->value, "peer")) {
3288 ast_variables_destroy(var);
3293 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
3295 if (!user) { /* No user found */
3296 ast_variables_destroy(var);
3300 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
3301 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
3303 ASTOBJ_CONTAINER_LINK(&userl,user);
3305 /* Move counter from s to r... */
3308 user->is_realtime = 1;
3310 ast_variables_destroy(var);
3314 /*! \brief Locate user by name
3315 * Locates user by name (From: sip uri user name part) first
3316 * from in-memory list (static configuration) then from
3317 * realtime storage (defined in extconfig.conf) */
3318 static struct sip_user *find_user(const char *name, int realtime)
3320 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
3322 u = realtime_user(name);
3326 /*! \brief Set nat mode on the various data sockets */
3327 static void do_setnat(struct sip_pvt *p, int natflags)
3329 const char *mode = natflags ? "On" : "Off";
3332 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
3333 ast_rtp_setnat(p->rtp, natflags);
3336 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
3337 ast_rtp_setnat(p->vrtp, natflags);
3340 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
3341 ast_udptl_setnat(p->udptl, natflags);
3344 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
3345 ast_rtp_setnat(p->trtp, natflags);
3349 /*! \brief Create address structure from peer reference.
3350 * This function copies data from peer to the dialog, so we don't have to look up the peer
3351 * again from memory or database during the life time of the dialog.
3353 * \return -1 on error, 0 on success.
3355 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
3357 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
3358 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
3359 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
3360 dialog->recv = dialog->sa;
3364 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
3365 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
3366 dialog->capability = peer->capability;
3367 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
3368 ast_rtp_destroy(dialog->vrtp);
3369 dialog->vrtp = NULL;
3371 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
3372 ast_rtp_destroy(dialog->trtp);
3373 dialog->trtp = NULL;
3375 dialog->prefs = peer->prefs;
3376 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
3377 dialog->t38.capability = global_t38_capability;
3378 if (dialog->udptl) {
3379 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
3380 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
3381 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
3382 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
3383 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
3384 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
3385 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
3386 ast_debug(2,"Our T38 capability (%d)\n", dialog->t38.capability);
3388 dialog->t38.jointcapability = dialog->t38.capability;
3389 } else if (dialog->udptl) {
3390 ast_udptl_destroy(dialog->udptl);
3391 dialog->udptl = NULL;
3393 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
3395 if (dialog->rtp) { /* Audio */
3396 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
3397 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
3398 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
3399 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
3400 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
3401 /* Set Frame packetization */
3402 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
3403 dialog->autoframing = peer->autoframing;
3405 if (dialog->vrtp) { /* Video */
3406 ast_rtp_setdtmf(dialog->vrtp, 0);
3407 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
3408 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
3409 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
3410 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
3412 if (dialog->trtp) { /* Realtime text */
3413 ast_rtp_setdtmf(dialog->trtp, 0);
3414 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
3415 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
3416 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
3417 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
3420 ast_string_field_set(dialog, peername, peer->name);
3421 ast_string_field_set(dialog, authname, peer->username);
3422 ast_string_field_set(dialog, username, peer->username);
3423 ast_string_field_set(dialog, peersecret, peer->secret);
3424 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
3425 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
3426 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
3427 ast_string_field_set(dialog, tohost, peer->tohost);
3428 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
3429 ast_string_field_set(dialog, context, peer->context);
3430 dialog->outboundproxy = obproxy_get(dialog, peer);
3431 dialog->callgroup = peer->callgroup;
3432 dialog->pickupgroup = peer->pickupgroup;
3433 dialog->allowtransfer = peer->allowtransfer;
3434 dialog->jointnoncodeccapability = dialog->noncodeccapability;
3435 dialog->rtptimeout = peer->rtptimeout;
3436 dialog->maxcallbitrate = peer->maxcallbitrate;
3437 if (ast_strlen_zero(dialog->tohost))
3438 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
3439 if (!ast_strlen_zero(peer->fromdomain)) {
3440 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
3441 if (!dialog->initreq.headers) {
3443 char *tmpcall = ast_strdupa(dialog->callid);
3445 c = strchr(tmpcall, '@');
3448 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
3452 if (!ast_strlen_zero(peer->fromuser))
3453 ast_string_field_set(dialog, fromuser, peer->fromuser);
3454 if (!ast_strlen_zero(peer->language))
3455 ast_string_field_set(dialog, language, peer->language);
3457 /* Set timer T1 to RTT for this peer (if known by qualify=) */
3458 /* Minimum is settable or default to 100 ms */
3459 /* If there is a maxms and lastms from a qualify use that over a manual T1
3460 value. Otherwise, use the peer's T1 value. */
3461 if (peer->maxms && peer->lastms)
3462 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
3464 dialog->timer_t1 = peer->timer_t1;
3466 /* Set timer B to control transaction timeouts, the peer setting is the default and overrides