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$")
94 #include <sys/socket.h>
95 #include <sys/ioctl.h>
102 #include <sys/signal.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <arpa/inet.h>
106 #include <netinet/ip.h>
109 #include "asterisk/lock.h"
110 #include "asterisk/channel.h"
111 #include "asterisk/config.h"
112 #include "asterisk/logger.h"
113 #include "asterisk/module.h"
114 #include "asterisk/pbx.h"
115 #include "asterisk/options.h"
116 #include "asterisk/sched.h"
117 #include "asterisk/io.h"
118 #include "asterisk/rtp.h"
119 #include "asterisk/udptl.h"
120 #include "asterisk/acl.h"
121 #include "asterisk/manager.h"
122 #include "asterisk/callerid.h"
123 #include "asterisk/cli.h"
124 #include "asterisk/app.h"
125 #include "asterisk/musiconhold.h"
126 #include "asterisk/dsp.h"
127 #include "asterisk/features.h"
128 #include "asterisk/srv.h"
129 #include "asterisk/astdb.h"
130 #include "asterisk/causes.h"
131 #include "asterisk/utils.h"
132 #include "asterisk/file.h"
133 #include "asterisk/astobj.h"
134 #include "asterisk/dnsmgr.h"
135 #include "asterisk/devicestate.h"
136 #include "asterisk/linkedlists.h"
137 #include "asterisk/stringfields.h"
138 #include "asterisk/monitor.h"
139 #include "asterisk/netsock.h"
140 #include "asterisk/localtime.h"
141 #include "asterisk/abstract_jb.h"
142 #include "asterisk/compiler.h"
143 #include "asterisk/threadstorage.h"
144 #include "asterisk/translate.h"
145 #include "asterisk/version.h"
146 #include "asterisk/event.h"
156 #define XMIT_ERROR -2
158 /* #define VOCAL_DATA_HACK */
160 #define DEFAULT_DEFAULT_EXPIRY 120
161 #define DEFAULT_MIN_EXPIRY 60
162 #define DEFAULT_MAX_EXPIRY 3600
163 #define DEFAULT_REGISTRATION_TIMEOUT 20
164 #define DEFAULT_MAX_FORWARDS "70"
166 /* guard limit must be larger than guard secs */
167 /* guard min must be < 1000, and should be >= 250 */
168 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
169 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
171 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
172 GUARD_PCT turns out to be lower than this, it
173 will use this time instead.
174 This is in milliseconds. */
175 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
176 below EXPIRY_GUARD_LIMIT */
177 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
179 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
180 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
181 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
182 static int expiry = DEFAULT_EXPIRY;
185 #define MAX(a,b) ((a) > (b) ? (a) : (b))
188 #define CALLERID_UNKNOWN "Unknown"
190 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
191 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
192 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
194 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
195 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
196 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
197 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
198 \todo Use known T1 for timeout (peerpoke)
200 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
201 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
203 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
204 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
205 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
207 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
209 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
210 static struct ast_jb_conf default_jbconf =
214 .resync_threshold = -1,
217 static struct ast_jb_conf global_jbconf;
219 static const char config[] = "sip.conf";
220 static const char notify_config[] = "sip_notify.conf";
225 /*! \brief Authorization scheme for call transfers
226 \note Not a bitfield flag, since there are plans for other modes,
227 like "only allow transfers for authenticated devices" */
229 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
230 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
239 /*! \brief States for the INVITE transaction, not the dialog
240 \note this is for the INVITE that sets up the dialog
243 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
244 INV_CALLING = 1, /*!< Invite sent, no answer */
245 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
246 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
247 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
248 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
249 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
250 The only way out of this is a BYE from one side */
251 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
254 /* Do _NOT_ make any changes to this enum, or the array following it;
255 if you think you are doing the right thing, you are probably
256 not doing the right thing. If you think there are changes
257 needed, get someone else to review them first _before_
258 submitting a patch. If these two lists do not match properly
259 bad things will happen.
263 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
264 If it fails, it's critical and will cause a teardown of the session */
265 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
266 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
269 enum parse_register_result {
270 PARSE_REGISTER_FAILED,
271 PARSE_REGISTER_UPDATE,
272 PARSE_REGISTER_QUERY,
275 enum subscriptiontype {
284 static const struct cfsubscription_types {
285 enum subscriptiontype type;
286 const char * const event;
287 const char * const mediatype;
288 const char * const text;
289 } subscription_types[] = {
290 { NONE, "-", "unknown", "unknown" },
291 /* RFC 4235: SIP Dialog event package */
292 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
293 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
294 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
295 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
296 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
299 /*! \brief SIP Request methods known by Asterisk */
301 SIP_UNKNOWN, /* Unknown response */
302 SIP_RESPONSE, /* Not request, response to outbound request */
308 SIP_PRACK, /* Not supported at all */
313 SIP_UPDATE, /* We can send UPDATE; but not accept it */
316 SIP_PUBLISH, /* Not supported at all */
317 SIP_PING, /* Not supported at all, no standard but still implemented out there */
320 /*! \brief Authentication types - proxy or www authentication
321 \note Endpoints, like Asterisk, should always use WWW authentication to
322 allow multiple authentications in the same call - to the proxy and
330 /*! \brief Authentication result from check_auth* functions */
331 enum check_auth_result {
332 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
333 /* XXX maybe this is the same as AUTH_NOT_FOUND */
336 AUTH_CHALLENGE_SENT = 1,
337 AUTH_SECRET_FAILED = -1,
338 AUTH_USERNAME_MISMATCH = -2,
339 AUTH_NOT_FOUND = -3, /* returned by register_verify */
341 AUTH_UNKNOWN_DOMAIN = -5,
342 AUTH_PEER_NOT_DYNAMIC = -6,
343 AUTH_ACL_FAILED = -7,
346 /*! \brief States for outbound registrations (with register= lines in sip.conf */
347 enum sipregistrystate {
348 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
349 /* Initial state. We should have a timeout scheduled for the initial
350 * (or next) registration transmission, calling sip_reregister
353 REG_STATE_REGSENT, /*!< Registration request sent */
354 /* sent initial request, waiting for an ack or a timeout to
355 * retransmit the initial request.
358 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
359 /* entered after transmit_register with auth info,
360 * waiting for an ack.
363 REG_STATE_REGISTERED, /*!< Registered and done */
364 REG_STATE_REJECTED, /*!< Registration rejected */
365 /* only used when the remote party has an expire larger than
366 * our max-expire. This is a final state from which we do not
367 * recover (not sure how correctly).
370 REG_STATE_TIMEOUT, /*!< Registration timed out */
373 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
374 /* fatal - no chance to proceed */
376 REG_STATE_FAILED, /*!< Registration failed after several tries */
377 /* fatal - no chance to proceed */
380 /*! \brief definition of a sip proxy server
382 * For outbound proxies, this is allocated in the SIP peer dynamically or
383 * statically as the global_outboundproxy. The pointer in a SIP message is just
384 * a pointer and should *not* be de-allocated.
387 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
388 struct sockaddr_in ip; /*!< Currently used IP address and port */
389 time_t last_dnsupdate; /*!< When this was resolved */
390 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
391 /* Room for a SRV record chain based on the name */
394 enum can_create_dialog {
395 CAN_NOT_CREATE_DIALOG,
397 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
400 /*! XXX 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
439 #define SIP_OPT_REPLACES (1 << 0)
440 #define SIP_OPT_100REL (1 << 1)
441 #define SIP_OPT_TIMER (1 << 2)
442 #define SIP_OPT_EARLY_SESSION (1 << 3)
443 #define SIP_OPT_JOIN (1 << 4)
444 #define SIP_OPT_PATH (1 << 5)
445 #define SIP_OPT_PREF (1 << 6)
446 #define SIP_OPT_PRECONDITION (1 << 7)
447 #define SIP_OPT_PRIVACY (1 << 8)
448 #define SIP_OPT_SDP_ANAT (1 << 9)
449 #define SIP_OPT_SEC_AGREE (1 << 10)
450 #define SIP_OPT_EVENTLIST (1 << 11)
451 #define SIP_OPT_GRUU (1 << 12)
452 #define SIP_OPT_TARGET_DIALOG (1 << 13)
453 #define SIP_OPT_NOREFERSUB (1 << 14)
454 #define SIP_OPT_HISTINFO (1 << 15)
455 #define SIP_OPT_RESPRIORITY (1 << 16)
457 /*! \brief List of well-known SIP options. If we get this in a require,
458 we should check the list and answer accordingly. */
459 static const struct cfsip_options {
460 int id; /*!< Bitmap ID */
461 int supported; /*!< Supported by Asterisk ? */
462 char * const text; /*!< Text id, as in standard */
463 } sip_options[] = { /* XXX used in 3 places */
464 /* RFC3891: Replaces: header for transfer */
465 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
466 /* One version of Polycom firmware has the wrong label */
467 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
468 /* RFC3262: PRACK 100% reliability */
469 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
470 /* RFC4028: SIP Session Timers */
471 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
472 /* RFC3959: SIP Early session support */
473 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
474 /* RFC3911: SIP Join header support */
475 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
476 /* RFC3327: Path support */
477 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
478 /* RFC3840: Callee preferences */
479 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
480 /* RFC3312: Precondition support */
481 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
482 /* RFC3323: Privacy with proxies*/
483 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
484 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
485 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
486 /* RFC3329: Security agreement mechanism */
487 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
488 /* SIMPLE events: RFC4662 */
489 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
490 /* GRUU: Globally Routable User Agent URI's */
491 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
492 /* RFC4538: Target-dialog */
493 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
494 /* Disable the REFER subscription, RFC 4488 */
495 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
496 /* ietf-sip-history-info-06.txt */
497 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
498 /* ietf-sip-resource-priority-10.txt */
499 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
503 /*! \brief SIP Methods we support */
504 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
506 /*! \brief SIP Extensions we support */
507 #define SUPPORTED_EXTENSIONS "replaces"
509 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
510 #define STANDARD_SIP_PORT 5060
511 /* Note: in many SIP headers, absence of a port number implies port 5060,
512 * and this is why we cannot change the above constant.
513 * There is a limited number of places in asterisk where we could,
514 * in principle, use a different "default" port number, but
515 * we do not support this feature at the moment.
518 /* Default values, set and reset in reload_config before reading configuration */
519 /* These are default values in the source. There are other recommended values in the
520 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
521 yet encouraging new behaviour on new installations
523 #define DEFAULT_CONTEXT "default"
524 #define DEFAULT_MOHINTERPRET "default"
525 #define DEFAULT_MOHSUGGEST ""
526 #define DEFAULT_VMEXTEN "asterisk"
527 #define DEFAULT_CALLERID "asterisk"
528 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
529 #define DEFAULT_ALLOWGUEST TRUE
530 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
531 #define DEFAULT_COMPACTHEADERS FALSE
532 #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. */
533 #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. */
534 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
535 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
536 #define DEFAULT_COS_SIP 4
537 #define DEFAULT_COS_AUDIO 5
538 #define DEFAULT_COS_VIDEO 6
539 #define DEFAULT_COS_TEXT 0
540 #define DEFAULT_ALLOW_EXT_DOM TRUE
541 #define DEFAULT_REALM "asterisk"
542 #define DEFAULT_NOTIFYRINGING TRUE
543 #define DEFAULT_PEDANTIC FALSE
544 #define DEFAULT_AUTOCREATEPEER FALSE
545 #define DEFAULT_QUALIFY FALSE
546 #define DEFAULT_REGEXTENONQUALIFY FALSE
547 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
548 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
549 #ifndef DEFAULT_USERAGENT
550 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
551 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
552 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
555 /* Default setttings are used as a channel setting and as a default when
556 configuring devices */
557 static char default_context[AST_MAX_CONTEXT];
558 static char default_subscribecontext[AST_MAX_CONTEXT];
559 static char default_language[MAX_LANGUAGE];
560 static char default_callerid[AST_MAX_EXTENSION];
561 static char default_fromdomain[AST_MAX_EXTENSION];
562 static char default_notifymime[AST_MAX_EXTENSION];
563 static int default_qualify; /*!< Default Qualify= setting */
564 static char default_vmexten[AST_MAX_EXTENSION];
565 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
566 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
567 * a bridged channel on hold */
568 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
569 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
571 /*! \brief a place to store all global settings for the sip channel driver */
572 struct sip_settings {
573 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
574 int rtsave_sysname; /*!< G: Save system name at registration? */
575 int ignore_regexpire; /*!< G: Ignore expiration of peer */
578 static struct sip_settings sip_cfg;
580 /* Global settings only apply to the channel */
581 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
582 static int global_limitonpeers; /*!< Match call limit on peers only */
583 static int global_rtautoclear;
584 static int global_notifyringing; /*!< Send notifications on ringing */
585 static int global_notifyhold; /*!< Send notifications on hold */
586 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
587 static int global_srvlookup; /*!< SRV Lookup on or off. Default is on */
588 static int pedanticsipchecking; /*!< Extra checking ? Default off */
589 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
590 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
591 static int global_relaxdtmf; /*!< Relax DTMF */
592 static int global_rtptimeout; /*!< Time out call if no RTP */
593 static int global_rtpholdtimeout;
594 static int global_rtpkeepalive; /*!< Send RTP keepalives */
595 static int global_reg_timeout;
596 static int global_regattempts_max; /*!< Registration attempts before giving up */
597 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
598 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
599 the global setting is in globals_flags[1] */
600 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
601 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
602 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
603 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
604 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
605 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
606 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
607 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
608 static int compactheaders; /*!< send compact sip headers */
609 static int recordhistory; /*!< Record SIP history. Off by default */
610 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
611 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
612 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
613 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
614 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
615 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
616 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
617 static int global_callevents; /*!< Whether we send manager events or not */
618 static int global_t1min; /*!< T1 roundtrip time minimum */
619 static int global_regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
620 static int global_autoframing; /*!< Turn autoframing on or off. */
621 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
622 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
624 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
626 /*! \brief Codecs that we support by default: */
627 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
629 /* Object counters */
630 static int suserobjs = 0; /*!< Static users */
631 static int ruserobjs = 0; /*!< Realtime users */
632 static int speerobjs = 0; /*!< Statis peers */
633 static int rpeerobjs = 0; /*!< Realtime peers */
634 static int apeerobjs = 0; /*!< Autocreated peer objects */
635 static int regobjs = 0; /*!< Registry objects */
637 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
639 AST_MUTEX_DEFINE_STATIC(netlock);
641 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
642 when it's doing something critical. */
644 AST_MUTEX_DEFINE_STATIC(monlock);
646 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
648 /*! \brief This is the thread for the monitor which checks for input on the channels
649 which are not currently in use. */
650 static pthread_t monitor_thread = AST_PTHREADT_NULL;
652 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
653 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
655 static struct sched_context *sched; /*!< The scheduling context */
656 static struct io_context *io; /*!< The IO context */
657 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
659 #define DEC_CALL_LIMIT 0
660 #define INC_CALL_LIMIT 1
661 #define DEC_CALL_RINGING 2
662 #define INC_CALL_RINGING 3
664 /*! \brief The data grabbed from the UDP socket
666 * Incoming messages: we first store the data from the socket in data[],
667 * adding a trailing \0 to make string parsing routines happy.
668 * Then call parse_request() and req.method = find_sip_method();
669 * to initialize the other fields. The \r\n at the end of each line is
670 * replaced by \0, so that data[] is not a conforming SIP message anymore.
671 * After this processing, rlPart1 is set to non-NULL to remember
672 * that we can run get_header() on this kind of packet.
674 * parse_request() splits the first line as follows:
675 * Requests have in the first line method uri SIP/2.0
676 * rlPart1 = method; rlPart2 = uri;
677 * Responses have in the first line SIP/2.0 NNN description
678 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
680 * For outgoing packets, we initialize the fields with init_req() or init_resp()
681 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
682 * and then fill the rest with add_header() and add_line().
683 * The \r\n at the end of the line are still there, so the get_header()
684 * and similar functions don't work on these packets.
688 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
689 char *rlPart2; /*!< The Request URI or Response Status */
690 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
691 int headers; /*!< # of SIP Headers */
692 int method; /*!< Method of this request */
693 int lines; /*!< Body Content */
694 unsigned int sdp_start; /*!< the line number where the SDP begins */
695 unsigned int sdp_end; /*!< the line number where the SDP ends */
696 char debug; /*!< print extra debugging if non zero */
697 char has_to_tag; /*!< non-zero if packet has To: tag */
698 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
699 char *header[SIP_MAX_HEADERS];
700 char *line[SIP_MAX_LINES];
701 char data[SIP_MAX_PACKET];
704 /*! \brief structure used in transfers */
706 struct ast_channel *chan1; /*!< First channel involved */
707 struct ast_channel *chan2; /*!< Second channel involved */
708 struct sip_request req; /*!< Request that caused the transfer (REFER) */
709 int seqno; /*!< Sequence number */
714 /*! \brief Parameters to the transmit_invite function */
715 struct sip_invite_param {
716 int addsipheaders; /*!< Add extra SIP headers */
717 const char *uri_options; /*!< URI options to add to the URI */
718 const char *vxml_url; /*!< VXML url for Cisco phones */
719 char *auth; /*!< Authentication */
720 char *authheader; /*!< Auth header */
721 enum sip_auth_type auth_type; /*!< Authentication type */
722 const char *replaces; /*!< Replaces header for call transfers */
723 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
726 /*! \brief Structure to save routing information for a SIP session */
728 struct sip_route *next;
732 /*! \brief Modes for SIP domain handling in the PBX */
734 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
735 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
738 /*! \brief Domain data structure.
739 \note In the future, we will connect this to a configuration tree specific
743 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
744 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
745 enum domain_mode mode; /*!< How did we find this domain? */
746 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
749 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
752 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
754 AST_LIST_ENTRY(sip_history) list;
755 char event[0]; /* actually more, depending on needs */
758 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
760 /*! \brief sip_auth: Credentials for authentication to other SIP services */
762 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
763 char username[256]; /*!< Username */
764 char secret[256]; /*!< Secret */
765 char md5secret[256]; /*!< MD5Secret */
766 struct sip_auth *next; /*!< Next auth structure in list */
769 /*--- Various flags for the flags field in the pvt structure
770 Trying to sort these up (one or more of the following):
774 When flags are used by multiple structures, it is important that
775 they have a common layout so it is easy to copy them.
777 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
778 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
779 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
780 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
781 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
782 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
783 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
784 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
785 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
786 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 11) /*!< D: Do not hangup at first ast_hangup */
788 #define SIP_PROMISCREDIR (1 << 12) /*!< DP: Promiscuous redirection */
789 #define SIP_TRUSTRPID (1 << 13) /*!< DP: Trust RPID headers? */
790 #define SIP_USEREQPHONE (1 << 14) /*!< DP: Add user=phone to numeric URI. Default off */
791 #define SIP_USECLIENTCODE (1 << 15) /*!< DP: Trust X-ClientCode info message */
793 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
794 #define SIP_DTMF (3 << 16) /*!< DP: DTMF Support: four settings, uses two bits */
795 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
796 #define SIP_DTMF_INBAND (1 << 16) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
797 #define SIP_DTMF_INFO (2 << 16) /*!< DP: DTMF Support: SIP Info messages - "info" */
798 #define SIP_DTMF_AUTO (3 << 16) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
799 #define SIP_DTMF_SHORTINFO (4 << 16) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
801 /* NAT settings - see nat2str() */
802 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
803 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
804 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
805 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
806 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
808 /* re-INVITE related settings */
809 #define SIP_REINVITE (7 << 20) /*!< DP: three bits used */
810 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
811 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
812 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
814 /* "insecure" settings - see insecure2str() */
815 #define SIP_INSECURE (3 << 23) /*!< DP: two bits used */
816 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
817 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
819 /* Sending PROGRESS in-band settings */
820 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
821 #define SIP_PROG_INBAND_NEVER (0 << 25)
822 #define SIP_PROG_INBAND_NO (1 << 25)
823 #define SIP_PROG_INBAND_YES (2 << 25)
825 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
826 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
828 /*! \brief Flags to copy from peer/user to dialog */
829 #define SIP_FLAGS_TO_COPY \
830 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
831 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
832 SIP_USEREQPHONE | SIP_INSECURE)
834 /*--- a new page of flags (for flags[1] */
836 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
837 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
838 /* Space for addition of other realtime flags in the future */
840 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15) /*!< DP: Video supported if offered? */
841 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
842 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
843 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
845 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
846 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
847 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
848 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
850 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
851 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
852 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
853 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
855 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
856 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
857 #define SIP_PAGE2_TEXTSUPPORT (1 << 28) /*!< GDP: Global text enable */
858 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
860 #define SIP_PAGE2_FLAGS_TO_COPY \
861 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
862 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
863 SIP_PAGE2_TEXTSUPPORT )
866 /* T.38 set of flags */
867 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
868 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
869 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
870 /* Rate management */
871 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
872 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
873 /* UDP Error correction */
874 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
875 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
876 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
877 /* T38 Spec version */
878 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
879 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
880 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
881 /* Maximum Fax Rate */
882 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
883 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
884 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
885 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
886 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
887 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
889 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
890 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
892 /*! \brief debugging state
893 * We store separately the debugging requests from the config file
894 * and requests from the CLI. Debugging is enabled if either is set
895 * (which means that if sipdebug is set in the config file, we can
896 * only turn it off by reloading the config).
900 sip_debug_config = 1,
901 sip_debug_console = 2,
904 static enum sip_debug_e sipdebug;
906 /*! \brief extra debugging for 'text' related events.
907 * At thie moment this is set together with sip_debug_console.
908 * It should either go away or be implemented properly.
910 static int sipdebug_text;
912 /*! \brief T38 States for a call */
914 T38_DISABLED = 0, /*!< Not enabled */
915 T38_LOCAL_DIRECT, /*!< Offered from local */
916 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
917 T38_PEER_DIRECT, /*!< Offered from peer */
918 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
919 T38_ENABLED /*!< Negotiated (enabled) */
922 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
923 struct t38properties {
924 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
925 int capability; /*!< Our T38 capability */
926 int peercapability; /*!< Peers T38 capability */
927 int jointcapability; /*!< Supported T38 capability at both ends */
928 enum t38state state; /*!< T.38 state */
931 /*! \brief Parameters to know status of transfer */
933 REFER_IDLE, /*!< No REFER is in progress */
934 REFER_SENT, /*!< Sent REFER to transferee */
935 REFER_RECEIVED, /*!< Received REFER from transferrer */
936 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
937 REFER_ACCEPTED, /*!< Accepted by transferee */
938 REFER_RINGING, /*!< Target Ringing */
939 REFER_200OK, /*!< Answered by transfer target */
940 REFER_FAILED, /*!< REFER declined - go on */
941 REFER_NOAUTH /*!< We had no auth for REFER */
944 /*! \brief generic struct to map between strings and integers.
945 * Fill it with x-s pairs, terminate with an entry with s = NULL;
946 * Then you can call map_x_s(...) to map an integer to a string,
947 * and map_s_x() for the string -> integer mapping.
954 static const struct _map_x_s referstatusstrings[] = {
955 { REFER_IDLE, "<none>" },
956 { REFER_SENT, "Request sent" },
957 { REFER_RECEIVED, "Request received" },
958 { REFER_CONFIRMED, "Confirmed" },
959 { REFER_ACCEPTED, "Accepted" },
960 { REFER_RINGING, "Target ringing" },
961 { REFER_200OK, "Done" },
962 { REFER_FAILED, "Failed" },
963 { REFER_NOAUTH, "Failed - auth failure" },
964 { -1, NULL} /* terminator */
967 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
968 \note OEJ: Should be moved to string fields */
970 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
971 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
972 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
973 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
974 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
975 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
976 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
977 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
978 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
979 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
980 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
981 * dialog owned by someone else, so we should not destroy
982 * it when the sip_refer object goes.
984 int attendedtransfer; /*!< Attended or blind transfer? */
985 int localtransfer; /*!< Transfer to local domain? */
986 enum referstatus status; /*!< REFER status */
989 /*! \brief sip_pvt: structures used for each SIP dialog, ie. a call, a registration, a subscribe.
990 * Created and initialized by sip_alloc(), the descriptor goes into the list of
991 * descriptors (dialoglist).
994 struct sip_pvt *next; /*!< Next dialog in chain */
995 ast_mutex_t pvt_lock; /*!< Dialog private lock */
996 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
997 int method; /*!< SIP method that opened this dialog */
998 AST_DECLARE_STRING_FIELDS(
999 AST_STRING_FIELD(callid); /*!< Global CallID */
1000 AST_STRING_FIELD(randdata); /*!< Random data */
1001 AST_STRING_FIELD(accountcode); /*!< Account code */
1002 AST_STRING_FIELD(realm); /*!< Authorization realm */
1003 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1004 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1005 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1006 AST_STRING_FIELD(domain); /*!< Authorization domain */
1007 AST_STRING_FIELD(from); /*!< The From: header */
1008 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1009 AST_STRING_FIELD(exten); /*!< Extension where to start */
1010 AST_STRING_FIELD(context); /*!< Context for this call */
1011 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1012 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1013 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1014 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1015 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1016 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1017 AST_STRING_FIELD(language); /*!< Default language for this call */
1018 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1019 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1020 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1021 AST_STRING_FIELD(redircause); /*!< Referring cause */
1022 AST_STRING_FIELD(theirtag); /*!< Their tag */
1023 AST_STRING_FIELD(username); /*!< [user] name */
1024 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1025 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1026 AST_STRING_FIELD(uri); /*!< Original requested URI */
1027 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1028 AST_STRING_FIELD(peersecret); /*!< Password */
1029 AST_STRING_FIELD(peermd5secret);
1030 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1031 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1032 AST_STRING_FIELD(via); /*!< Via: header */
1033 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1034 /* we only store the part in <brackets> in this field. */
1035 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1036 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1037 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1038 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1040 unsigned int ocseq; /*!< Current outgoing seqno */
1041 unsigned int icseq; /*!< Current incoming seqno */
1042 ast_group_t callgroup; /*!< Call group */
1043 ast_group_t pickupgroup; /*!< Pickup group */
1044 int lastinvite; /*!< Last Cseq of invite */
1045 int lastnoninvite; /*!< Last Cseq of non-invite */
1046 struct ast_flags flags[2]; /*!< SIP_ flags */
1048 /* boolean or small integers that don't belong in flags */
1049 char do_history; /*!< Set if we want to record history */
1050 char alreadygone; /*!< already destroyed by our peer */
1051 char needdestroy; /*!< need to be destroyed by the monitor thread */
1052 char outgoing_call; /*!< this is an outgoing call */
1053 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1054 char novideo; /*!< Didn't get video in invite, don't offer */
1055 char notext; /*!< Text not supported (?) */
1057 int timer_t1; /*!< SIP timer T1, ms rtt */
1058 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1059 struct ast_codec_pref prefs; /*!< codec prefs */
1060 int capability; /*!< Special capability (codec) */
1061 int jointcapability; /*!< Supported capability at both ends (codecs) */
1062 int peercapability; /*!< Supported peer capability */
1063 int prefcodec; /*!< Preferred codec (outbound only) */
1064 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1065 int jointnoncodeccapability; /*!< Joint Non codec capability */
1066 int redircodecs; /*!< Redirect codecs */
1067 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1068 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
1069 struct t38properties t38; /*!< T38 settings */
1070 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1071 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1072 int callingpres; /*!< Calling presentation */
1073 int authtries; /*!< Times we've tried to authenticate */
1074 int expiry; /*!< How long we take to expire */
1075 long branch; /*!< The branch identifier of this session */
1076 char tag[11]; /*!< Our tag for this session */
1077 int sessionid; /*!< SDP Session ID */
1078 int sessionversion; /*!< SDP Session Version */
1079 struct sockaddr_in sa; /*!< Our peer */
1080 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1081 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1082 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1083 time_t lastrtprx; /*!< Last RTP received */
1084 time_t lastrtptx; /*!< Last RTP sent */
1085 int rtptimeout; /*!< RTP timeout time */
1086 struct sockaddr_in recv; /*!< Received as */
1087 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1088 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1089 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1090 int route_persistant; /*!< Is this the "real" route? */
1091 struct sip_auth *peerauth; /*!< Realm authentication */
1092 int noncecount; /*!< Nonce-count */
1093 char lastmsg[256]; /*!< Last Message sent/received */
1094 int amaflags; /*!< AMA Flags */
1095 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
1096 struct sip_request initreq; /*!< Latest request that opened a new transaction
1098 NOT the request that opened the dialog
1101 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1102 int autokillid; /*!< Auto-kill ID (scheduler) */
1103 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1104 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1105 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1106 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1107 int laststate; /*!< SUBSCRIBE: Last known extension state */
1108 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1110 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1112 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1113 Used in peerpoke, mwi subscriptions */
1114 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1115 struct ast_rtp *rtp; /*!< RTP Session */
1116 struct ast_rtp *vrtp; /*!< Video RTP session */
1117 struct ast_rtp *trtp; /*!< Text RTP session */
1118 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1119 struct sip_history_head *history; /*!< History of this SIP dialog */
1120 size_t history_entries; /*!< Number of entires in the history */
1121 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1122 struct sip_invite_param *options; /*!< Options for INVITE */
1123 int autoframing; /*!< The number of Asters we group in a Pyroflax
1124 before strolling to the Grokyzpå
1125 (A bit unsure of this, please correct if
1129 /*! Max entires in the history list for a sip_pvt */
1130 #define MAX_HISTORY_ENTRIES 50
1133 * Here we implement the container for dialogs (sip_pvt), defining
1134 * generic wrapper functions to ease the transition from the current
1135 * implementation (a single linked list) to a different container.
1136 * In addition to a reference to the container, we need functions to lock/unlock
1137 * the container and individual items, and functions to add/remove
1138 * references to the individual items.
1140 static struct sip_pvt *dialoglist = NULL;
1142 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1143 AST_MUTEX_DEFINE_STATIC(dialoglock);
1145 #ifndef DETECT_DEADLOCKS
1146 /*! \brief hide the way the list is locked/unlocked */
1147 static void dialoglist_lock(void)
1149 ast_mutex_lock(&dialoglock);
1152 static void dialoglist_unlock(void)
1154 ast_mutex_unlock(&dialoglock);
1157 /* we don't want to HIDE the information about where the lock was requested if trying to debug
1158 * deadlocks! So, just make these macros! */
1159 #define dialoglist_lock(x) ast_mutex_lock(&dialoglock)
1160 #define dialoglist_unlock(x) ast_mutex_unlock(&dialoglock)
1164 * when we create or delete references, make sure to use these
1165 * functions so we keep track of the refcounts.
1166 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1168 static struct sip_pvt *dialog_ref(struct sip_pvt *p)
1173 static struct sip_pvt *dialog_unref(struct sip_pvt *p)
1178 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1179 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1180 * Each packet holds a reference to the parent struct sip_pvt.
1181 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1182 * require retransmissions.
1185 struct sip_pkt *next; /*!< Next packet in linked list */
1186 int retrans; /*!< Retransmission number */
1187 int method; /*!< SIP method for this packet */
1188 int seqno; /*!< Sequence number */
1189 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1190 char is_fatal; /*!< non-zero if there is a fatal error */
1191 struct sip_pvt *owner; /*!< Owner AST call */
1192 int retransid; /*!< Retransmission ID */
1193 int timer_a; /*!< SIP timer A, retransmission timer */
1194 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1195 int packetlen; /*!< Length of packet */
1199 /*! \brief Structure for SIP user data. User's place calls to us */
1201 /* Users who can access various contexts */
1202 ASTOBJ_COMPONENTS(struct sip_user);
1203 char secret[80]; /*!< Password */
1204 char md5secret[80]; /*!< Password in md5 */
1205 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1206 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1207 char cid_num[80]; /*!< Caller ID num */
1208 char cid_name[80]; /*!< Caller ID name */
1209 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1210 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1211 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1212 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1213 char useragent[256]; /*!< User agent in SIP request */
1214 struct ast_codec_pref prefs; /*!< codec prefs */
1215 ast_group_t callgroup; /*!< Call group */
1216 ast_group_t pickupgroup; /*!< Pickup Group */
1217 unsigned int sipoptions; /*!< Supported SIP options */
1218 struct ast_flags flags[2]; /*!< SIP_ flags */
1220 /* things that don't belong in flags */
1221 char is_realtime; /*!< this is a 'realtime' user */
1223 int amaflags; /*!< AMA flags for billing */
1224 int callingpres; /*!< Calling id presentation */
1225 int capability; /*!< Codec capability */
1226 int inUse; /*!< Number of calls in use */
1227 int call_limit; /*!< Limit of concurrent calls */
1228 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1229 struct ast_ha *ha; /*!< ACL setting */
1230 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1231 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1236 * \brief A peer's mailbox
1238 * We could use STRINGFIELDS here, but for only two strings, it seems like
1239 * too much effort ...
1241 struct sip_mailbox {
1244 /*! Associated MWI subscription */
1245 struct ast_event_sub *event_sub;
1246 AST_LIST_ENTRY(sip_mailbox) entry;
1249 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1250 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1252 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1253 /*!< peer->name is the unique name of this object */
1254 char secret[80]; /*!< Password */
1255 char md5secret[80]; /*!< Password in MD5 */
1256 struct sip_auth *auth; /*!< Realm authentication list */
1257 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1258 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1259 char username[80]; /*!< Temporary username until registration */
1260 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1261 int amaflags; /*!< AMA Flags (for billing) */
1262 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1263 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1264 char fromuser[80]; /*!< From: user when calling this peer */
1265 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1266 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1267 char cid_num[80]; /*!< Caller ID num */
1268 char cid_name[80]; /*!< Caller ID name */
1269 int callingpres; /*!< Calling id presentation */
1270 int inUse; /*!< Number of calls in use */
1271 int inRinging; /*!< Number of calls ringing */
1272 int onHold; /*!< Peer has someone on hold */
1273 int call_limit; /*!< Limit of concurrent calls */
1274 int busy_level; /*!< Level of active channels where we signal busy */
1275 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1276 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1277 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1278 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1279 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1280 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1281 struct ast_codec_pref prefs; /*!< codec prefs */
1283 unsigned int sipoptions; /*!< Supported SIP options */
1284 struct ast_flags flags[2]; /*!< SIP_ flags */
1286 /*! Mailboxes that this peer cares about */
1287 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1289 /* things that don't belong in flags */
1290 char is_realtime; /*!< this is a 'realtime' peer */
1291 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1292 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1293 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1295 int expire; /*!< When to expire this peer registration */
1296 int capability; /*!< Codec capability */
1297 int rtptimeout; /*!< RTP timeout */
1298 int rtpholdtimeout; /*!< RTP Hold Timeout */
1299 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1300 ast_group_t callgroup; /*!< Call group */
1301 ast_group_t pickupgroup; /*!< Pickup group */
1302 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1303 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1304 struct sockaddr_in addr; /*!< IP address of peer */
1305 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1308 struct sip_pvt *call; /*!< Call pointer */
1309 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1310 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1311 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1312 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1313 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1314 struct ast_ha *ha; /*!< Access control list */
1315 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1316 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1321 /*! \brief Registrations with other SIP proxies
1322 * Created by sip_register(), the entry is linked in the 'regl' list,
1323 * and never deleted (other than at 'sip reload' or module unload times).
1324 * The entry always has a pending timeout, either waiting for an ACK to
1325 * the REGISTER message (in which case we have to retransmit the request),
1326 * or waiting for the next REGISTER message to be sent (either the initial one,
1327 * or once the previously completed registration one expires).
1328 * The registration can be in one of many states, though at the moment
1329 * the handling is a bit mixed.
1330 * Note that the entire evolution of sip_registry (transmissions,
1331 * incoming packets and timeouts) is driven by one single thread,
1332 * do_monitor(), so there is almost no synchronization issue.
1333 * The only exception is the sip_pvt creation/lookup,
1334 * as the dialoglist is also manipulated by other threads.
1336 struct sip_registry {
1337 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1338 AST_DECLARE_STRING_FIELDS(
1339 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1340 AST_STRING_FIELD(realm); /*!< Authorization realm */
1341 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1342 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1343 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1344 AST_STRING_FIELD(domain); /*!< Authorization domain */
1345 AST_STRING_FIELD(username); /*!< Who we are registering as */
1346 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1347 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1348 AST_STRING_FIELD(secret); /*!< Password in clear text */
1349 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1350 AST_STRING_FIELD(callback); /*!< Contact extension */
1351 AST_STRING_FIELD(random);
1353 int portno; /*!< Optional port override */
1354 int expire; /*!< Sched ID of expiration */
1355 int expiry; /*!< Value to use for the Expires header */
1356 int regattempts; /*!< Number of attempts (since the last success) */
1357 int timeout; /*!< sched id of sip_reg_timeout */
1358 int refresh; /*!< How often to refresh */
1359 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1360 enum sipregistrystate regstate; /*!< Registration state (see above) */
1361 struct timeval regtime; /*!< Last successful registration time */
1362 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1363 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1364 struct sockaddr_in us; /*!< Who the server thinks we are */
1365 int noncecount; /*!< Nonce-count */
1366 char lastmsg[256]; /*!< Last Message sent/received */
1369 /* --- Linked lists of various objects --------*/
1371 /*! \brief The user list: Users and friends */
1372 static struct ast_user_list {
1373 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1376 /*! \brief The peer list: Peers and Friends */
1377 static struct ast_peer_list {
1378 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1381 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1382 static struct ast_register_list {
1383 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1387 static int temp_pvt_init(void *);
1388 static void temp_pvt_cleanup(void *);
1390 /*! \brief A per-thread temporary pvt structure */
1391 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1393 /*! \brief Authentication list for realm authentication
1394 * \todo Move the sip_auth list to AST_LIST */
1395 static struct sip_auth *authl = NULL;
1398 /* --- Sockets and networking --------------*/
1400 /*! \brief Main socket for SIP communication.
1401 * sipsock is shared between the manager thread (which handles reload
1402 * requests), the io handler (sipsock_read()) and the user routines that
1403 * issue writes (using __sip_xmit()).
1404 * The socket is -1 only when opening fails (this is a permanent condition),
1405 * or when we are handling a reload() that changes its address (this is
1406 * a transient situation during which we might have a harmless race, see
1407 * below). Because the conditions for the race to be possible are extremely
1408 * rare, we don't want to pay the cost of locking on every I/O.
1409 * Rather, we remember that when the race may occur, communication is
1410 * bound to fail anyways, so we just live with this event and let
1411 * the protocol handle this above us.
1413 static int sipsock = -1;
1415 static struct sockaddr_in bindaddr; /*!< The address we bind to */
1417 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1418 * internip is initialized picking a suitable address from one of the
1419 * interfaces, and the same port number we bind to. It is used as the
1420 * default address/port in SIP messages, and as the default address
1421 * (but not port) in SDP messages.
1423 static struct sockaddr_in internip;
1425 /*! \brief our external IP address/port for SIP sessions.
1426 * externip.sin_addr is only set when we know we might be behind
1427 * a NAT, and this is done using a variety of (mutually exclusive)
1428 * ways from the config file:
1430 * + with "externip = host[:port]" we specify the address/port explicitly.
1431 * The address is looked up only once when (re)loading the config file;
1433 * + with "externhost = host[:port]" we do a similar thing, but the
1434 * hostname is stored in externhost, and the hostname->IP mapping
1435 * is refreshed every 'externrefresh' seconds;
1437 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1438 * to the specified server, and store the result in externip.
1440 * Other variables (externhost, externexpire, externrefresh) are used
1441 * to support the above functions.
1443 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1445 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1446 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1447 static int externrefresh = 10;
1448 static struct sockaddr_in stunaddr; /*!< stun server address */
1450 /*! \brief List of local networks
1451 * We store "localnet" addresses from the config file into an access list,
1452 * marked as 'DENY', so the call to ast_apply_ha() will return
1453 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1454 * (i.e. presumably public) addresses.
1456 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1458 static struct sockaddr_in debugaddr;
1460 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1462 /*---------------------------- Forward declarations of functions in chan_sip.c */
1463 /*! \note This is added to help splitting up chan_sip.c into several files
1464 in coming releases */
1466 /*--- PBX interface functions */
1467 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1468 static int sip_devicestate(void *data);
1469 static int sip_sendtext(struct ast_channel *ast, const char *text);
1470 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1471 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1472 static int sip_hangup(struct ast_channel *ast);
1473 static int sip_answer(struct ast_channel *ast);
1474 static struct ast_frame *sip_read(struct ast_channel *ast);
1475 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1476 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1477 static int sip_transfer(struct ast_channel *ast, const char *dest);
1478 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1479 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1480 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1482 /*--- Transmitting responses and requests */
1483 static int sipsock_read(int *id, int fd, short events, void *ignore);
1484 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1485 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1486 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1487 static int retrans_pkt(const void *data);
1488 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1489 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);
1490 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1491 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1492 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1493 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1494 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1495 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);
1496 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1497 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1498 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1499 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1500 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1501 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1502 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1503 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1504 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1505 static int transmit_refer(struct sip_pvt *p, const char *dest);
1506 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1507 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1508 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1509 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1510 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1511 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1512 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1513 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1514 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1516 /*--- Dialog management */
1517 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1518 int useglobal_nat, const int intended_method);
1519 static int __sip_autodestruct(const void *data);
1520 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1521 static void sip_cancel_destroy(struct sip_pvt *p);
1522 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1523 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1524 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1525 static void __sip_pretend_ack(struct sip_pvt *p);
1526 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1527 static int auto_congest(const void *arg);
1528 static int update_call_counter(struct sip_pvt *fup, int event);
1529 static int hangup_sip2cause(int cause);
1530 static const char *hangup_cause2sip(int cause);
1531 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1532 static void free_old_route(struct sip_route *route);
1533 static void list_route(struct sip_route *route);
1534 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1535 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1536 struct sip_request *req, char *uri);
1537 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1538 static void check_pendings(struct sip_pvt *p);
1539 static void *sip_park_thread(void *stuff);
1540 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1541 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1543 /*--- Codec handling / SDP */
1544 static void try_suggested_sip_codec(struct sip_pvt *p);
1545 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1546 static const char *get_sdp(struct sip_request *req, const char *name);
1547 static int find_sdp(struct sip_request *req);
1548 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1549 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1550 struct ast_str **m_buf, struct ast_str **a_buf,
1551 int debug, int *min_packet_size);
1552 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1553 struct ast_str **m_buf, struct ast_str **a_buf,
1555 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1556 static void do_setnat(struct sip_pvt *p, int natflags);
1557 static void stop_media_flows(struct sip_pvt *p);
1559 /*--- Authentication stuff */
1560 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1561 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1562 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1563 const char *secret, const char *md5secret, int sipmethod,
1564 char *uri, enum xmittype reliable, int ignore);
1565 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1566 int sipmethod, char *uri, enum xmittype reliable,
1567 struct sockaddr_in *sin, struct sip_peer **authpeer);
1568 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1570 /*--- Domain handling */
1571 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1572 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1573 static void clear_sip_domains(void);
1575 /*--- SIP realm authentication */
1576 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1577 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1578 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1580 /*--- Misc functions */
1581 static int sip_do_reload(enum channelreloadreason reason);
1582 static int reload_config(enum channelreloadreason reason);
1583 static int expire_register(const void *data);
1584 static void *do_monitor(void *data);
1585 static int restart_monitor(void);
1586 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1587 static int sip_refer_allocate(struct sip_pvt *p);
1588 static void ast_quiet_chan(struct ast_channel *chan);
1589 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1591 /*--- Device monitoring and Device/extension state/event handling */
1592 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1593 static int sip_devicestate(void *data);
1594 static int sip_poke_noanswer(const void *data);
1595 static int sip_poke_peer(struct sip_peer *peer);
1596 static void sip_poke_all_peers(void);
1597 static void sip_peer_hold(struct sip_pvt *p, int hold);
1598 static void mwi_event_cb(const struct ast_event *, void *);
1600 /*--- Applications, functions, CLI and manager command helpers */
1601 static const char *sip_nat_mode(const struct sip_pvt *p);
1602 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1603 static char *transfermode2str(enum transfermodes mode) attribute_const;
1604 static const char *nat2str(int nat) attribute_const;
1605 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1606 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1607 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1608 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1609 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1610 static void print_group(int fd, ast_group_t group, int crlf);
1611 static const char *dtmfmode2str(int mode) attribute_const;
1612 static int str2dtmfmode(const char *str) attribute_unused;
1613 static const char *insecure2str(int mode) attribute_const;
1614 static void cleanup_stale_contexts(char *new, char *old);
1615 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1616 static const char *domain_mode_to_text(const enum domain_mode mode);
1617 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1618 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1619 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1620 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1621 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1622 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1623 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1624 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1625 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1626 static char *complete_sip_peer(const char *word, int state, int flags2);
1627 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1628 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1629 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1630 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1631 static char *complete_sip_user(const char *word, int state, int flags2);
1632 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1633 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1634 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1635 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1636 static char *sip_do_debug_ip(int fd, char *arg);
1637 static char *sip_do_debug_peer(int fd, char *arg);
1638 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1639 static char *sip_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1640 static char *sip_do_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1641 static char *sip_no_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1642 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1643 static int sip_addheader(struct ast_channel *chan, void *data);
1644 static int sip_do_reload(enum channelreloadreason reason);
1645 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1646 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1649 Functions for enabling debug per IP or fully, or enabling history logging for
1652 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1653 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1654 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1655 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1656 static void sip_dump_history(struct sip_pvt *dialog);
1658 /*--- Device object handling */
1659 static struct sip_peer *temp_peer(const char *name);
1660 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1661 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1662 static int update_call_counter(struct sip_pvt *fup, int event);
1663 static void sip_destroy_peer(struct sip_peer *peer);
1664 static void sip_destroy_user(struct sip_user *user);
1665 static int sip_poke_peer(struct sip_peer *peer);
1666 static void set_peer_defaults(struct sip_peer *peer);
1667 static struct sip_peer *temp_peer(const char *name);
1668 static void register_peer_exten(struct sip_peer *peer, int onoff);
1669 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1670 static struct sip_user *find_user(const char *name, int realtime);
1671 static int sip_poke_peer_s(const void *data);
1672 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1673 static void reg_source_db(struct sip_peer *peer);
1674 static void destroy_association(struct sip_peer *peer);
1675 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1676 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1678 /* Realtime device support */
1679 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1680 static struct sip_user *realtime_user(const char *username);
1681 static void update_peer(struct sip_peer *p, int expiry);
1682 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1683 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1684 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1685 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1687 /*--- Internal UA client handling (outbound registrations) */
1688 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
1689 static void sip_registry_destroy(struct sip_registry *reg);
1690 static int sip_register(const char *value, int lineno);
1691 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1692 static int sip_reregister(const void *data);
1693 static int __sip_do_register(struct sip_registry *r);
1694 static int sip_reg_timeout(const void *data);
1695 static void sip_send_all_registers(void);
1697 /*--- Parsing SIP requests and responses */
1698 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1699 static int determine_firstline_parts(struct sip_request *req);
1700 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1701 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1702 static int find_sip_method(const char *msg);
1703 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1704 static void parse_request(struct sip_request *req);
1705 static const char *get_header(const struct sip_request *req, const char *name);
1706 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1707 static int method_match(enum sipmethod id, const char *name);
1708 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1709 static char *get_in_brackets(char *tmp);
1710 static const char *find_alias(const char *name, const char *_default);
1711 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1712 static int lws2sws(char *msgbuf, int len);
1713 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1714 static char *remove_uri_parameters(char *uri);
1715 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1716 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1717 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1718 static int set_address_from_contact(struct sip_pvt *pvt);
1719 static void check_via(struct sip_pvt *p, struct sip_request *req);
1720 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1721 static int get_rpid_num(const char *input, char *output, int maxlen);
1722 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1723 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1724 static int get_msg_text(char *buf, int len, struct sip_request *req);
1725 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1727 /*--- Constructing requests and responses */
1728 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1729 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1730 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1731 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1732 static int init_resp(struct sip_request *resp, const char *msg);
1733 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1734 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1735 static void build_via(struct sip_pvt *p);
1736 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1737 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1738 static char *generate_random_string(char *buf, size_t size);
1739 static void build_callid_pvt(struct sip_pvt *pvt);
1740 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1741 static void make_our_tag(char *tagbuf, size_t len);
1742 static int add_header(struct sip_request *req, const char *var, const char *value);
1743 static int add_header_contentLength(struct sip_request *req, int len);
1744 static int add_line(struct sip_request *req, const char *line);
1745 static int add_text(struct sip_request *req, const char *text);
1746 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1747 static int add_vidupdate(struct sip_request *req);
1748 static void add_route(struct sip_request *req, struct sip_route *route);
1749 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1750 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1751 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1752 static void set_destination(struct sip_pvt *p, char *uri);
1753 static void append_date(struct sip_request *req);
1754 static void build_contact(struct sip_pvt *p);
1755 static void build_rpid(struct sip_pvt *p);
1757 /*------Request handling functions */
1758 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1759 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);
1760 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1761 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1762 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1763 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1764 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1765 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1766 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1767 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1768 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
1769 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1770 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1772 /*------Response handling functions */
1773 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1774 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1775 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1776 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1778 /*----- RTP interface functions */
1779 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);
1780 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1781 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1782 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1783 static int sip_get_codec(struct ast_channel *chan);
1784 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1786 /*------ T38 Support --------- */
1787 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
1788 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1789 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1790 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1792 /*! \brief Definition of this channel for PBX channel registration */
1793 static const struct ast_channel_tech sip_tech = {
1795 .description = "Session Initiation Protocol (SIP)",
1796 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
1797 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1798 .requester = sip_request_call, /* called with chan unlocked */
1799 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1800 .call = sip_call, /* called with chan locked */
1801 .send_html = sip_sendhtml,
1802 .hangup = sip_hangup, /* called with chan locked */
1803 .answer = sip_answer, /* called with chan locked */
1804 .read = sip_read, /* called with chan locked */
1805 .write = sip_write, /* called with chan locked */
1806 .write_video = sip_write, /* called with chan locked */
1807 .write_text = sip_write,
1808 .indicate = sip_indicate, /* called with chan locked */
1809 .transfer = sip_transfer, /* called with chan locked */
1810 .fixup = sip_fixup, /* called with chan locked */
1811 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1812 .send_digit_end = sip_senddigit_end,
1813 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
1814 .early_bridge = ast_rtp_early_bridge,
1815 .send_text = sip_sendtext, /* called with chan locked */
1816 .func_channel_read = acf_channel_read,
1819 /*! \brief This version of the sip channel tech has no send_digit_begin
1820 * callback so that the core knows that the channel does not want
1821 * DTMF BEGIN frames.
1822 * The struct is initialized just before registering the channel driver,
1823 * and is for use with channels using SIP INFO DTMF.
1825 static struct ast_channel_tech sip_tech_info;
1827 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
1828 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
1830 /*! \brief map from an integer value to a string.
1831 * If no match is found, return errorstring
1833 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
1835 const struct _map_x_s *cur;
1837 for (cur = table; cur->s; cur++)
1843 /*! \brief map from a string to an integer value, case insensitive.
1844 * If no match is found, return errorvalue.
1846 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
1848 const struct _map_x_s *cur;
1850 for (cur = table; cur->s; cur++)
1851 if (!strcasecmp(cur->s, s))
1856 /**--- some list management macros. **/
1858 #define UNLINK(element, head, prev) do { \
1860 (prev)->next = (element)->next; \
1862 (head) = (element)->next; \
1865 /*! \brief Interface structure with callbacks used to connect to RTP module */
1866 static struct ast_rtp_protocol sip_rtp = {
1868 .get_rtp_info = sip_get_rtp_peer,
1869 .get_vrtp_info = sip_get_vrtp_peer,
1870 .get_trtp_info = sip_get_trtp_peer,
1871 .set_rtp_peer = sip_set_rtp_peer,
1872 .get_codec = sip_get_codec,
1875 #define sip_pvt_lock(x) ast_mutex_lock(&x->pvt_lock)
1876 #define sip_pvt_unlock(x) ast_mutex_unlock(&x->pvt_lock)
1879 * helper functions to unreference various types of objects.
1880 * By handling them this way, we don't have to declare the
1881 * destructor on each call, which removes the chance of errors.
1883 static void unref_peer(struct sip_peer *peer)
1885 ASTOBJ_UNREF(peer, sip_destroy_peer);
1888 static void unref_user(struct sip_user *user)
1890 ASTOBJ_UNREF(user, sip_destroy_user);
1893 static void *registry_unref(struct sip_registry *reg)
1895 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
1896 ASTOBJ_UNREF(reg, sip_registry_destroy);
1900 /*! \brief Add object reference to SIP registry */
1901 static struct sip_registry *registry_addref(struct sip_registry *reg)
1903 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
1904 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
1907 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1908 static struct ast_udptl_protocol sip_udptl = {
1910 get_udptl_info: sip_get_udptl_peer,
1911 set_udptl_peer: sip_set_udptl_peer,
1914 /*! \brief Append to SIP dialog history
1915 \return Always returns 0 */
1916 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1918 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1919 __attribute__ ((format (printf, 2, 3)));
1922 /*! \brief Convert transfer status to string */
1923 static const char *referstatus2str(enum referstatus rstatus)
1925 return map_x_s(referstatusstrings, rstatus, "");
1928 /*! \brief Initialize the initital request packet in the pvt structure.
1929 This packet is used for creating replies and future requests in
1931 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1933 if (p->initreq.headers)
1934 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1936 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1937 /* Use this as the basis */
1938 copy_request(&p->initreq, req);
1939 parse_request(&p->initreq);
1941 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1944 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1945 static void sip_alreadygone(struct sip_pvt *dialog)
1947 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1948 dialog->alreadygone = 1;
1951 /*! Resolve DNS srv name or host name in a sip_proxy structure */
1952 static int proxy_update(struct sip_proxy *proxy)
1954 /* if it's actually an IP address and not a name,
1955 there's no need for a managed lookup */
1956 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
1957 /* Ok, not an IP address, then let's check if it's a domain or host */
1958 /* XXX Todo - if we have proxy port, don't do SRV */
1959 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
1960 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
1964 proxy->last_dnsupdate = time(NULL);
1968 /*! \brief Allocate and initialize sip proxy */
1969 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
1971 struct sip_proxy *proxy;
1972 proxy = ast_calloc(1, sizeof(*proxy));
1975 proxy->force = force;
1976 ast_copy_string(proxy->name, name, sizeof(proxy->name));
1977 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
1978 proxy_update(proxy);
1982 /*! \brief Get default outbound proxy or global proxy */
1983 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
1985 if (peer && peer->outboundproxy) {
1987 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
1988 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
1989 return peer->outboundproxy;
1991 if (global_outboundproxy.name[0]) {
1993 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
1994 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
1995 return &global_outboundproxy;
1998 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2002 /*! \brief returns true if 'name' (with optional trailing whitespace)
2003 * matches the sip method 'id'.
2004 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2005 * a case-insensitive comparison to be more tolerant.
2006 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2008 static int method_match(enum sipmethod id, const char *name)
2010 int len = strlen(sip_methods[id].text);
2011 int l_name = name ? strlen(name) : 0;
2012 /* true if the string is long enough, and ends with whitespace, and matches */
2013 return (l_name >= len && name[len] < 33 &&
2014 !strncasecmp(sip_methods[id].text, name, len));
2017 /*! \brief find_sip_method: Find SIP method from header */
2018 static int find_sip_method(const char *msg)
2022 if (ast_strlen_zero(msg))
2024 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
2025 if (method_match(i, msg))
2026 res = sip_methods[i].id;
2031 /*! \brief Parse supported header in incoming packet */
2032 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2036 unsigned int profile = 0;
2039 if (ast_strlen_zero(supported) )
2041 temp = ast_strdupa(supported);
2044 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2046 for (next = temp; next; next = sep) {
2048 if ( (sep = strchr(next, ',')) != NULL)
2050 next = ast_skip_blanks(next);
2052 ast_debug(3, "Found SIP option: -%s-\n", next);
2053 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
2054 if (!strcasecmp(next, sip_options[i].text)) {
2055 profile |= sip_options[i].id;
2058 ast_debug(3, "Matched SIP option: %s\n", next);
2062 if (!found && sipdebug) {
2063 if (!strncasecmp(next, "x-", 2))
2064 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2066 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2071 pvt->sipoptions = profile;
2075 /*! \brief See if we pass debug IP filter */
2076 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2080 if (debugaddr.sin_addr.s_addr) {
2081 if (((ntohs(debugaddr.sin_port) != 0)
2082 && (debugaddr.sin_port != addr->sin_port))
2083 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2089 /*! \brief The real destination address for a write */
2090 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2092 if (p->outboundproxy)
2093 return &p->outboundproxy->ip;
2095 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2098 /*! \brief Display SIP nat mode */
2099 static const char *sip_nat_mode(const struct sip_pvt *p)
2101 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2104 /*! \brief Test PVT for debugging output */
2105 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2109 return sip_debug_test_addr(sip_real_dst(p));
2112 /*! \brief Transmit SIP message */
2113 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
2116 const struct sockaddr_in *dst = sip_real_dst(p);
2117 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2121 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2122 case EHOSTUNREACH: /* Host can't be reached */
2123 case ENETDOWN: /* Interface down */
2124 case ENETUNREACH: /* Network failure */
2125 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2129 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));
2134 /*! \brief Build a Via header for a request */
2135 static void build_via(struct sip_pvt *p)
2137 /* Work around buggy UNIDEN UIP200 firmware */
2138 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2140 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2141 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
2142 ast_inet_ntoa(p->ourip.sin_addr),
2143 ntohs(p->ourip.sin_port), p->branch, rport);
2146 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2148 * Using the localaddr structure built up with localnet statements in sip.conf
2149 * apply it to their address to see if we need to substitute our
2150 * externip or can get away with our internal bindaddr
2151 * 'us' is always overwritten.
2153 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2155 struct sockaddr_in theirs;
2156 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2157 * reachable IP address and port. This is done if:
2158 * 1. we have a localaddr list (containing 'internal' addresses marked
2159 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2160 * and AST_SENSE_ALLOW on 'external' ones);
2161 * 2. either stunaddr or externip is set, so we know what to use as the
2162 * externally visible address;
2163 * 3. the remote address, 'them', is external;
2164 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2165 * when passed to ast_apply_ha() so it does need to be remapped.
2166 * This fourth condition is checked later.
2168 int want_remap = localaddr &&
2169 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2170 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2172 *us = internip; /* starting guess for the internal address */
2173 /* now ask the system what would it use to talk to 'them' */
2174 ast_ouraddrfor(them, &us->sin_addr);
2175 theirs.sin_addr = *them;
2178 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2179 /* if we used externhost or stun, see if it is time to refresh the info */
2180 if (externexpire && time(NULL) >= externexpire) {
2181 if (stunaddr.sin_addr.s_addr) {
2182 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2184 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2185 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2187 externexpire = time(NULL) + externrefresh;
2189 if (externip.sin_addr.s_addr)
2192 ast_log(LOG_WARNING, "stun failed\n");
2193 ast_debug(1, "Target address %s is not local, substituting externip\n",
2194 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2195 } else if (bindaddr.sin_addr.s_addr) {
2196 /* no remapping, but we bind to a specific address, so use it. */
2201 /*! \brief Append to SIP dialog history with arg list */
2202 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2204 char buf[80], *c = buf; /* max history length */
2205 struct sip_history *hist;
2208 vsnprintf(buf, sizeof(buf), fmt, ap);
2209 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2210 l = strlen(buf) + 1;
2211 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2213 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2217 memcpy(hist->event, buf, l);
2218 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2219 struct sip_history *oldest;
2220 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2221 p->history_entries--;
2224 AST_LIST_INSERT_TAIL(p->history, hist, list);
2225 p->history_entries++;
2228 /*! \brief Append to SIP dialog history with arg list */
2229 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2236 if (!p->do_history && !recordhistory && !dumphistory)
2240 append_history_va(p, fmt, ap);
2246 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2247 static int retrans_pkt(const void *data)
2249 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2250 int reschedule = DEFAULT_RETRANS;
2253 /* Lock channel PVT */
2254 sip_pvt_lock(pkt->owner);
2256 if (pkt->retrans < MAX_RETRANS) {
2258 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2260 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);
2265 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2269 pkt->timer_a = 2 * pkt->timer_a;
2271 /* For non-invites, a maximum of 4 secs */
2272 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2273 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2276 /* Reschedule re-transmit */
2277 reschedule = siptimer_a;
2278 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);
2281 if (sip_debug_test_pvt(pkt->owner)) {
2282 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2283 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2284 pkt->retrans, sip_nat_mode(pkt->owner),
2285 ast_inet_ntoa(dst->sin_addr),
2286 ntohs(dst->sin_port), pkt->data);
2289 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
2290 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2291 sip_pvt_unlock(pkt->owner);
2292 if (xmitres == XMIT_ERROR)
2293 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2297 /* Too many retries */
2298 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2299 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2300 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n",
2301 pkt->owner->callid, pkt->seqno,
2302 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2303 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2304 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2307 if (xmitres == XMIT_ERROR) {
2308 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2309 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2311 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2313 pkt->retransid = -1;
2315 if (pkt->is_fatal) {
2316 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2317 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2319 sip_pvt_lock(pkt->owner);
2322 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
2323 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2325 if (pkt->owner->owner) {
2326 sip_alreadygone(pkt->owner);
2327 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2328 ast_queue_hangup(pkt->owner->owner);
2329 ast_channel_unlock(pkt->owner->owner);
2331 /* If no channel owner, destroy now */
2333 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2334 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2335 pkt->owner->needdestroy = 1;
2336 sip_alreadygone(pkt->owner);
2337 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2342 if (pkt->method == SIP_BYE) {
2343 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
2344 if (pkt->owner->owner)
2345 ast_channel_unlock(pkt->owner->owner);
2346 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2347 pkt->owner->needdestroy = 1;
2350 /* Remove the packet */
2351 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2353 UNLINK(cur, pkt->owner->packets, prev);
2354 sip_pvt_unlock(pkt->owner);
2360 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2361 sip_pvt_unlock(pkt->owner);
2365 /*! \brief Transmit packet with retransmits
2366 \return 0 on success, -1 on failure to allocate packet
2368 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2370 struct sip_pkt *pkt;
2371 int siptimer_a = DEFAULT_RETRANS;
2374 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2376 /* copy data, add a terminator and save length */
2377 memcpy(pkt->data, data, len);
2378 pkt->data[len] = '\0';
2379 pkt->packetlen = len;
2380 /* copy other parameters from the caller */
2381 pkt->method = sipmethod;
2383 pkt->is_resp = resp;
2384 pkt->is_fatal = fatal;
2385 pkt->owner = dialog_ref(p);
2386 pkt->next = p->packets;
2388 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2390 siptimer_a = pkt->timer_t1 * 2;
2392 /* Schedule retransmission */
2393 pkt->retransid = ast_sched_replace_variable(pkt->retransid, sched,
2394 siptimer_a, retrans_pkt, pkt, 1);
2396 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
2397 if (sipmethod == SIP_INVITE) {
2398 /* Note this is a pending invite */
2399 p->pendinginvite = seqno;
2402 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2404 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
2405 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2406 ast_sched_del(sched, pkt->retransid); /* No more retransmission */
2407 pkt->retransid = -1;
2413 /*! \brief Kill a SIP dialog (called only by the scheduler)
2414 * The scheduler has a reference to this dialog when p->autokillid != -1,
2415 * and we are called using that reference. So if the event is not
2416 * rescheduled, we need to call dialog_unref().
2418 static int __sip_autodestruct(const void *data)
2420 struct sip_pvt *p = (struct sip_pvt *)data;
2422 /* If this is a subscription, tell the phone that we got a timeout */
2423 if (p->subscribed) {
2424 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2425 p->subscribed = NONE;
2426 append_history(p, "Subscribestatus", "timeout");
2427 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
2428 return 10000; /* Reschedule this destruction so that we know that it's gone */
2431 /* If there are packets still waiting for delivery, delay the destruction */
2433 if (option_debug > 2)
2434 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2435 append_history(p, "ReliableXmit", "timeout");
2439 if (p->subscribed == MWI_NOTIFICATION)
2441 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2443 /* Reset schedule ID */
2447 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2448 ast_queue_hangup(p->owner);
2450 } else if (p->refer) {
2451 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
2452 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2453 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2454 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2457 append_history(p, "AutoDestroy", "%s", p->callid);
2458 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
2459 sip_destroy(p); /* Go ahead and destroy dialog. All attempts to recover is done */
2460 /* sip_destroy also absorbs the reference */
2465 /*! \brief Schedule destruction of SIP dialog */
2466 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2469 if (p->timer_t1 == 0)
2470 p->timer_t1 = SIP_TIMER_T1; /* Set timer T1 if not set (RFC 3261) */
2471 ms = p->timer_t1 * 64;
2473 if (sip_debug_test_pvt(p))
2474 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2475 sip_cancel_destroy(p);
2477 append_history(p, "SchedDestroy", "%d ms", ms);
2478 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p));
2481 /*! \brief Cancel destruction of SIP dialog.
2482 * Be careful as this also absorbs the reference - if you call it
2483 * from within the scheduler, this might be the last reference.
2485 static void sip_cancel_destroy(struct sip_pvt *p)
2487 if (p->autokillid > -1) {
2488 ast_sched_del(sched, p->autokillid);
2489 append_history(p, "CancelDestroy", "");
2495 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2496 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2498 struct sip_pkt *cur, *prev = NULL;
2499 const char *msg = "Not Found"; /* used only for debugging */
2503 /* If we have an outbound proxy for this dialog, then delete it now since
2504 the rest of the requests in this dialog needs to follow the routing.
2505 If obforcing is set, we will keep the outbound proxy during the whole
2506 dialog, regardless of what the SIP rfc says
2508 if (p->outboundproxy && !p->outboundproxy->force)
2509 p->outboundproxy = NULL;
2511 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2512 if (cur->seqno != seqno || cur->is_resp != resp)
2514 if (cur->is_resp || cur->method == sipmethod) {
2516 if (!resp && (seqno == p->pendinginvite)) {
2517 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
2518 p->pendinginvite = 0;
2520 if (cur->retransid > -1) {
2522 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2523 ast_sched_del(sched, cur->retransid);
2524 cur->retransid = -1;
2526 UNLINK(cur, p->packets, prev);
2527 dialog_unref(cur->owner);
2533 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2534 p->callid, resp ? "Response" : "Request", seqno, msg);
2537 /*! \brief Pretend to ack all packets
2538 * maybe the lock on p is not strictly necessary but there might be a race */
2539 static void __sip_pretend_ack(struct sip_pvt *p)
2541 struct sip_pkt *cur = NULL;
2543 while (p->packets) {
2545 if (cur == p->packets) {
2546 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2550 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2551 __sip_ack(p, cur->seqno, cur->is_resp, method);
2555 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2556 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2558 struct sip_pkt *cur;
2561 for (cur = p->packets; cur; cur = cur->next) {
2562 if (cur->seqno == seqno && cur->is_resp == resp &&
2563 (cur->is_resp || method_match(sipmethod, cur->data))) {
2564 /* this is our baby */
2565 if (cur->retransid > -1) {
2567 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2568 ast_sched_del(sched, cur->retransid);
2569 cur->retransid = -1;
2575 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");
2580 /*! \brief Copy SIP request, parse it */
2581 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2583 memset(dst, 0, sizeof(*dst));
2584 memcpy(dst->data, src->data, sizeof(dst->data));
2585 dst->len = src->len;
2589 /*! \brief add a blank line if no body */
2590 static void add_blank(struct sip_request *req)
2593 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2594 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
2595 req->len += strlen(req->data + req->len);
2599 /*! \brief Transmit response on SIP request*/
2600 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2605 if (sip_debug_test_pvt(p)) {
2606 const struct sockaddr_in *dst = sip_real_dst(p);
2608 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2609 reliable ? "Reliably " : "", sip_nat_mode(p),
2610 ast_inet_ntoa(dst->sin_addr),
2611 ntohs(dst->sin_port), req->data);
2613 if (p->do_history) {
2614 struct sip_request tmp;
2615 parse_copy(&tmp, req);
2616 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2617 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2620 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2621 __sip_xmit(p, req->data, req->len);
2627 /*! \brief Send SIP Request to the other part of the dialogue */
2628 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2632 /* If we have an outbound proxy, reset peer address
2635 if (p->outboundproxy) {
2636 p->sa = p->outboundproxy->ip;
2640 if (sip_debug_test_pvt(p)) {
2641 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2642 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);
2644 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);
2646 if (p->do_history) {
2647 struct sip_request tmp;
2648 parse_copy(&tmp, req);
2649 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2652 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2653 __sip_xmit(p, req->data, req->len);
2657 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2658 * optionally with a limit on the search.
2659 * start must be past the first quote.
2661 static const char *find_closing_quote(const char *start, const char *lim)
2663 char last_char = '\0';
2665 for (s = start; *s && s != lim; last_char = *s++) {
2666 if (*s == '"' && last_char != '\\')
2672 /*! \brief Pick out text in brackets from character string
2673 \return pointer to terminated stripped string
2674 \param tmp input string that will be modified
2677 "foo" <bar> valid input, returns bar
2678 foo returns the whole string
2679 < "foo ... > returns the string between brackets
2680 < "foo... bogus (missing closing bracket), returns the whole string
2681 XXX maybe should still skip the opening bracket
2684 static char *get_in_brackets(char *tmp)
2686 const char *parse = tmp;
2687 char *first_bracket;
2690 * Skip any quoted text until we find the part in brackets.
2691 * On any error give up and return the full string.
2693 while ( (first_bracket = strchr(parse, '<')) ) {
2694 char *first_quote = strchr(parse, '"');
2696 if (!first_quote || first_quote > first_bracket)
2697 break; /* no need to look at quoted part */
2698 /* the bracket is within quotes, so ignore it */
2699 parse = find_closing_quote(first_quote + 1, NULL);
2700 if (!*parse) { /* not found, return full string ? */
2701 /* XXX or be robust and return in-bracket part ? */
2702 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2707 if (first_bracket) {
2708 char *second_bracket = strchr(first_bracket + 1, '>');
2709 if (second_bracket) {
2710 *second_bracket = '\0';
2711 tmp = first_bracket + 1;
2713 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2719 /*! \brief * parses a URI in its components.
2722 *- If scheme is specified, drop it from the top.
2723 * - If a component is not requested, do not split around it.
2724 * This means that if we don't have domain, we cannot split
2725 * name:pass and domain:port.
2726 * It is safe to call with ret_name, pass, domain, port
2727 * pointing all to the same place.
2728 * Init pointers to empty string so we never get NULL dereferencing.
2729 * Overwrites the string.
2730 * return 0 on success, other values on error.
2732 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
2735 static int parse_uri(char *uri, char *scheme,
2736 char **ret_name, char **pass, char **domain, char **port, char **options)
2741 /* init field as required */
2747 int l = strlen(scheme);
2748 if (!strncasecmp(uri, scheme, l))
2751 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, uri);
2756 /* if we don't want to split around domain, keep everything as a name,
2757 * so we need to do nothing here, except remember why.
2760 /* store the result in a temp. variable to avoid it being
2761 * overwritten if arguments point to the same place.
2765 if ((c = strchr(uri, '@')) == NULL) {
2766 /* domain-only URI, according to the SIP RFC. */
2775 /* Remove options in domain and name */
2776 dom = strsep(&dom, ";");
2777 name = strsep(&name, ";");
2779 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2783 if (pass && (c = strchr(name, ':'))) { /* user:password */
2789 if (ret_name) /* same as for domain, store the result only at the end */
2792 *options = uri ? uri : "";
2797 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
2798 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2800 struct sip_pvt *p = chan->tech_pvt;
2802 if (subclass != AST_HTML_URL)
2805 ast_string_field_build(p, url, "<%s>;mode=active", data);
2807 if (sip_debug_test_pvt(p))
2808 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
2810 switch (chan->_state) {
2811 case AST_STATE_RING:
2812 transmit_response(p, "100 Trying", &p->initreq);
2814 case AST_STATE_RINGING:
2815 transmit_response(p, "180 Ringing", &p->initreq);
2818 if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
2819 transmit_reinvite_with_sdp(p, FALSE);
2820 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
2821 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
2825 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
2831 /*! \brief Send SIP MESSAGE text within a call
2832 Called from PBX core sendtext() application */
2833 static int sip_sendtext(struct ast_channel *ast, const char *text)
2835 struct sip_pvt *p = ast->tech_pvt;
2836 int debug = sip_debug_test_pvt(p);
2839 ast_verbose("Sending text %s on %s\n", text, ast->name);
2842 if (ast_strlen_zero(text))
2845 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2846 transmit_message_with_text(p, text);
2850 /*! \brief Update peer object in realtime storage
2851 If the Asterisk system name is set in asterisk.conf, we will use
2852 that name and store that in the "regserver" field in the sippeers
2853 table to facilitate multi-server setups.
2855 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2858 char ipaddr[INET_ADDRSTRLEN];
2859 char regseconds[20];
2860 char *tablename = NULL;
2862 char *sysname = ast_config_AST_SYSTEM_NAME;
2863 char *syslabel = NULL;
2865 time_t nowtime = time(NULL) + expirey;
2866 const char *fc = fullcontact ? "fullcontact" : NULL;
2868 int realtimeregs = ast_check_realtime("sipregs");
2870 tablename = realtimeregs ? "sipregs" : "sippeers";
2872 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2873 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2874 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2876 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2878 else if (sip_cfg.rtsave_sysname)
2879 syslabel = "regserver";
2882 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2883 "port", port, "regseconds", regseconds,
2884 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2886 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2887 "port", port, "regseconds", regseconds,
2888 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2891 /*! \brief Automatically add peer extension to dial plan */
2892 static void register_peer_exten(struct sip_peer *peer, int onoff)
2895 char *stringp, *ext, *context;
2897 /* XXX note that global_regcontext is both a global 'enable' flag and
2898 * the name of the global regexten context, if not specified
2901 if (ast_strlen_zero(global_regcontext))
2904 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2906 while ((ext = strsep(&stringp, "&"))) {
2907 if ((context = strchr(ext, '@'))) {
2908 *context++ = '\0'; /* split ext@context */
2909 if (!ast_context_find(context)) {
2910 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2914 context = global_regcontext;
2917 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2918 ast_strdup(peer->name), ast_free_ptr, "SIP");
2920 ast_context_remove_extension(context, ext, 1, NULL);
2924 static void destroy_mailbox(struct sip_mailbox *mailbox)
2926 if (mailbox->mailbox)
2927 ast_free(mailbox->mailbox);
2928 if (mailbox->context)
2929 ast_free(mailbox->context);
2930 if (mailbox->event_sub)
2931 ast_event_unsubscribe(mailbox->event_sub);
2935 static void clear_peer_mailboxes(struct sip_peer *peer)
2937 struct sip_mailbox *mailbox;
2939 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
2940 destroy_mailbox(mailbox);
2943 /*! \brief Destroy peer object from memory */
2944 static void sip_destroy_peer(struct sip_peer *peer)
2946 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
2948 if (peer->outboundproxy)
2949 ast_free(peer->outboundproxy);
2950 peer->outboundproxy = NULL;
2952 /* Delete it, it needs to disappear */
2954 peer->call = sip_destroy(peer->call);
2956 if (peer->mwipvt) /* We have an active subscription, delete it */
2957 peer->mwipvt = sip_destroy(peer->mwipvt);
2959 if (peer->chanvars) {
2960 ast_variables_destroy(peer->chanvars);
2961 peer->chanvars = NULL;
2963 if (peer->expire > -1)
2964 ast_sched_del(sched, peer->expire);
2966 if (peer->pokeexpire > -1)
2967 ast_sched_del(sched, peer->pokeexpire);
2968 register_peer_exten(peer, FALSE);
2969 ast_free_ha(peer->ha);
2970 if (peer->selfdestruct)
2972 else if (peer->is_realtime) {
2974 ast_debug(3,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
2977 clear_realm_authentication(peer->auth);
2980 ast_dnsmgr_release(peer->dnsmgr);
2981 clear_peer_mailboxes(peer);
2985 /*! \brief Update peer data in database (if used) */
2986 static void update_peer(struct sip_peer *p, int expiry)
2988 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2989 if (sip_cfg.peer_rtupdate &&
2990 (p->is_realtime || rtcachefriends)) {
2991 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2995 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config)
2997 struct ast_variable *var = NULL;
2998 struct ast_flags flags = {0};
3000 const char *insecure;
3001 while ((cat = ast_category_browse(config, cat))) {
3002 insecure = ast_variable_retrieve(config, cat, "insecure");
3003 set_insecure_flags(&flags, insecure, -1);
3004 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
3005 var = ast_category_root(config, cat);
3012 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
3014 struct ast_variable *tmp;
3015 for (tmp = var; tmp; tmp = tmp->next) {
3016 if (!newpeername && !strcasecmp(tmp->name, "name"))
3017 newpeername = tmp->value;
3022 /*! \brief realtime_peer: Get peer from realtime storage
3023 * Checks the "sippeers" realtime family from extconfig.conf
3024 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
3026 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
3028 struct sip_peer *peer;
3029 struct ast_variable *var = NULL;
3030 struct ast_variable *varregs = NULL;
3031 struct ast_variable *tmp;
3032 struct ast_config *peerlist = NULL;
3033 char ipaddr[INET_ADDRSTRLEN];
3034 char portstring[6]; /*up to 5 digits plus null terminator*/
3036 unsigned short portnum;
3037 int realtimeregs = ast_check_realtime("sipregs");
3039 /* First check on peer name */
3041 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3043 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3044 } else if (sin) { /* Then check on IP address for dynamic peers */
3045 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3046 portnum = ntohs(sin->sin_port);
3047 sprintf(portstring, "%u", portnum);
3048 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, NULL); /* First check for fixed IP hosts */
3051 newpeername = get_name_from_variable(var, newpeername);
3052 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3056 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
3058 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
3060 newpeername = get_name_from_variable(varregs, newpeername);
3061 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3064 if(!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
3065 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, NULL);
3067 var = get_insecure_variable_from_config(peerlist);
3070 newpeername = get_name_from_variable(var, newpeername);
3071 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3073 } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
3076 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
3078 var = get_insecure_variable_from_config(peerlist);
3081 newpeername = get_name_from_variable(var, newpeername);
3082 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3089 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, NULL);
3091 varregs = get_insecure_variable_from_config(peerlist);
3093 newpeername = get_name_from_variable(varregs, newpeername);
3094 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3098 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
3100 var = get_insecure_variable_from_config(peerlist);
3102 newpeername = get_name_from_variable(var, newpeername);
3103 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3113 ast_config_destroy(peerlist);
3117 for (tmp = var; tmp; tmp = tmp->next) {
3118 /* If this is type=user, then skip this object. */
3119 if (!strcasecmp(tmp->name, "type") &&
3120 !strcasecmp(tmp->value, "user")) {
3122 ast_config_destroy(peerlist);
3124 ast_variables_destroy(var);
3125 ast_variables_destroy(varregs);
3128 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
3129 newpeername = tmp->value;
3133 if (!newpeername) { /* Did not find peer in realtime */
3134 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
3136 ast_config_destroy(peerlist);
3138 ast_variables_destroy(var);
3143 /* Peer found in realtime, now build it in memory */
3144 peer = build_peer(newpeername, var, varregs, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
3147 ast_config_destroy(peerlist);
3149 ast_variables_destroy(var);
3150 ast_variables_destroy(varregs);
3155 ast_debug(3,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
3157 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
3159 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
3160 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
3161 peer->expire = ast_sched_replace(peer->expire, sched,
3162 global_rtautoclear * 1000, expire_register, (void *) peer);
3164 ASTOBJ_CONTAINER_LINK(&peerl,peer);
3166 peer->is_realtime = 1;
3169 ast_config_destroy(peerlist);
3171 ast_variables_destroy(var);
3172 ast_variables_destroy(varregs);
3178 /*! \brief Support routine for find_peer */
3179 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
3181 /* We know name is the first field, so we can cast */
3182 struct sip_peer *p = (struct sip_peer *) name;
3183 return !(!inaddrcmp(&p->addr, sin) ||
3184 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
3185 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
3188 /*! \brief Locate peer by name or ip address
3189 * This is used on incoming SIP message to find matching peer on ip
3190 or outgoing message to find matching peer on name */
3191 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
3193 struct sip_peer *p = NULL;
3196 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
3198 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
3201 p = realtime_peer(peer, sin);
3206 /*! \brief Remove user object from in-memory storage */
3207 static void sip_destroy_user(struct sip_user *user)
3209 ast_debug(3, "Destroying user object from memory: %s\n", user->name);
3210 ast_free_ha(user->ha);
3211 if (user->chanvars) {
3212 ast_variables_destroy(user->chanvars);
3213 user->chanvars = NULL;
3215 if (user->is_realtime)
3222 /*! \brief Load user from realtime storage
3223 * Loads user from "sipusers" category in realtime (extconfig.conf)
3224 * Users are matched on From: user name (the domain in skipped) */
3225 static struct sip_user *realtime_user(const char *username)
3227 struct ast_variable *var;
3228 struct ast_variable *tmp;
3229 struct sip_user *user = NULL;
3231 var = ast_load_realtime("sipusers", "name", username, NULL);
3236 for (tmp = var; tmp; tmp = tmp->next) {
3237 if (!strcasecmp(tmp->name, "type") &&
3238 !strcasecmp(tmp->value, "peer")) {
3239 ast_variables_destroy(var);
3244 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
3246 if (!user) { /* No user found */
3247 ast_variables_destroy(var);
3251 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
3252 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
3254 ASTOBJ_CONTAINER_LINK(&userl,user);
3256 /* Move counter from s to r... */
3259 user->is_realtime = 1;
3261 ast_variables_destroy(var);
3265 /*! \brief Locate user by name
3266 * Locates user by name (From: sip uri user name part) first
3267 * from in-memory list (static configuration) then from
3268 * realtime storage (defined in extconfig.conf) */
3269 static struct sip_user *find_user(const char *name, int realtime)
3271 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
3273 u = realtime_user(name);
3277 /*! \brief Set nat mode on the various data sockets */
3278 static void do_setnat(struct sip_pvt *p, int natflags)
3280 const char *mode = natflags ? "On" : "Off";
3283 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
3284 ast_rtp_setnat(p->rtp, natflags);
3287 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
3288 ast_rtp_setnat(p->vrtp, natflags);
3291 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
3292 ast_udptl_setnat(p->udptl, natflags);
3295 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
3296 ast_rtp_setnat(p->trtp, natflags);
3300 /*! \brief Create address structure from peer reference.
3301 * return -1 on error, 0 on success.
3303 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
3305 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
3306 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
3307 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
3308 dialog->recv = dialog->sa;
3312 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
3313 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
3314 dialog->capability = peer->capability;
3315 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
3316 ast_rtp_destroy(dialog->vrtp);
3317 dialog->vrtp = NULL;
3319 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
3320 ast_rtp_destroy(dialog->trtp);
3321 dialog->trtp = NULL;
3323 dialog->prefs = peer->prefs;
3324 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
3325 dialog->t38.capability = global_t38_capability;
3326 if (dialog->udptl) {
3327 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
3328 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
3329 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
3330 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
3331 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
3332 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
3333 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
3334 ast_debug(2,"Our T38 capability (%d)\n", dialog->t38.capability);
3336 dialog->t38.jointcapability = dialog->t38.capability;
3337 } else if (dialog->udptl) {
3338 ast_udptl_destroy(dialog->udptl);
3339 dialog->udptl = NULL;
3341 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
3344 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
3345 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
3346 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
3347 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
3348 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
3349 /* Set Frame packetization */
3350 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
3351 dialog->autoframing = peer->autoframing;
3354 ast_rtp_setdtmf(dialog->vrtp, 0);
3355 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
3356 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
3357 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
3358 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
3361 ast_rtp_setdtmf(dialog->trtp, 0);
3362 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
3363 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
3364 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
3365 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
3368 ast_string_field_set(dialog, peername, peer->name);
3369 ast_string_field_set(dialog, authname, peer->username);
3370 ast_string_field_set(dialog, username, peer->username);
3371 ast_string_field_set(dialog, peersecret, peer->secret);
3372 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
3373 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
3374 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
3375 ast_string_field_set(dialog, tohost, peer->tohost);
3376 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
3377 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
3380 tmpcall = ast_strdupa(dialog->callid);
3381 c = strchr(tmpcall, '@');
3384 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
3387 dialog->outboundproxy = obproxy_get(dialog, peer);
3388 if (ast_strlen_zero(dialog->tohost))
3389 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
3390 if (!ast_strlen_zero(peer->fromdomain))
3391 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
3392 if (!ast_strlen_zero(peer->fromuser))
3393 ast_string_field_set(dialog, fromuser, peer->fromuser);
3394 if (!ast_strlen_zero(peer->language))
3395 ast_string_field_set(dialog, language, peer->language);
3396 dialog->callgroup = peer->callgroup;
3397 dialog->pickupgroup = peer->pickupgroup;
3398 dialog->allowtransfer = peer->allowtransfer;
3399 /* Set timer T1 to RTT for this peer (if known by qualify=) */
3400 /* Minimum is settable or default to 100 ms */
3401 if (peer->maxms && peer->lastms)
3402 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
3403 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
3404 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
3405 dialog->noncodeccapability |= AST_RTP_DTMF;
3407 dialog->noncodeccapability &= ~AST_RTP_DTMF;
3408 dialog->jointnoncodeccapability = dialog->noncodeccapability;
3409 ast_string_field_set(dialog, context, peer->context);
3410 dialog->rtptimeout = peer->rtptimeout;
3411 if (peer->call_limit)
3412 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
3413 dialog->maxcallbitrate = peer->maxcallbitrate;
3418 /*! \brief create address structure from peer name
3419 * Or, if peer not found, find it in the global DNS
3420 * returns TRUE (-1) on failure, FALSE on success */
3421 static int create_addr(struct sip_pvt *dialog, const char *opeer)
3424 struct ast_hostent ahp;
3425 struct sip_peer *peer;
3428 char host[MAXHOSTNAMELEN], *hostn;
3431 ast_copy_string(peername, opeer, sizeof(peername));
3432 port = strchr(peername, ':');
3435 dialog->sa.sin_family = AF_INET;
3436 dialog->timer_t1 = SIP_TIMER_T1; /* Default SIP retransmission timer T1 (RFC 3261) */
3437 peer = find_peer(peername, NULL, 1);
3440 int res = create_addr_from_peer(dialog, peer);
3445 ast_string_field_set(dialog, tohost, peername);
3447 /* Get the outbound proxy information */
3448 dialog->outboundproxy = obproxy_get(dialog, NULL);
3450 /* If we have an outbound proxy, don't bother with DNS resolution at all */
3451 if (dialog->outboundproxy)
3454 /* Let's see if we can find the host in DNS. First try DNS SRV records,
3455 then hostname lookup */
3458 portno = port ? atoi(port) : STANDARD_SIP_PORT;
3459 if (global_srvlookup) {
3460 char service[MAXHOSTNAMELEN];
3464 snprintf(service, sizeof(service), "_sip._udp.%s", peername);
3465 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
3471 hp = ast_gethostbyname(hostn, &ahp);
3473 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3476 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
3477 dialog->sa.sin_port = htons(portno);
3478 dialog->recv = dialog->sa;
3482 /*! \brief Scheduled congestion on a call.
3483 * Only called by the s