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_request(), that parses a bit more.
61 * if it's a response to an outbound request, it's sent to handle_response().
62 * If it is a request, handle_request 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/localtime.h"
140 #include "asterisk/abstract_jb.h"
141 #include "asterisk/compiler.h"
142 #include "asterisk/threadstorage.h"
143 #include "asterisk/translate.h"
144 #include "asterisk/version.h"
154 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
155 #ifndef IPTOS_MINCOST
156 #define IPTOS_MINCOST 0x02
159 /* #define VOCAL_DATA_HACK */
161 #define DEFAULT_DEFAULT_EXPIRY 120
162 #define DEFAULT_MIN_EXPIRY 60
163 #define DEFAULT_MAX_EXPIRY 3600
164 #define DEFAULT_REGISTRATION_TIMEOUT 20
165 #define DEFAULT_MAX_FORWARDS "70"
167 /* guard limit must be larger than guard secs */
168 /* guard min must be < 1000, and should be >= 250 */
169 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
170 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
172 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
173 GUARD_PCT turns out to be lower than this, it
174 will use this time instead.
175 This is in milliseconds. */
176 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
177 below EXPIRY_GUARD_LIMIT */
178 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
180 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
181 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
182 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
183 static int expiry = DEFAULT_EXPIRY;
186 #define MAX(a,b) ((a) > (b) ? (a) : (b))
189 #define CALLERID_UNKNOWN "Unknown"
191 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
192 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
193 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
195 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
196 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
197 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
198 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
199 \todo Use known T1 for timeout (peerpoke)
201 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
202 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
204 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
205 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
206 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
208 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
210 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
211 static struct ast_jb_conf default_jbconf =
215 .resync_threshold = -1,
218 static struct ast_jb_conf global_jbconf;
220 static const char config[] = "sip.conf";
221 static const char notify_config[] = "sip_notify.conf";
226 /*! \brief Authorization scheme for call transfers
227 \note Not a bitfield flag, since there are plans for other modes,
228 like "only allow transfers for authenticated devices" */
230 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
231 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
240 /*! \brief States for the INVITE transaction, not the dialog
241 \note this is for the INVITE that sets up the dialog
244 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
245 INV_CALLING = 1, /*!< Invite sent, no answer */
246 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
247 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
248 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
249 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
250 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
251 The only way out of this is a BYE from one side */
252 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
255 /* Do _NOT_ make any changes to this enum, or the array following it;
256 if you think you are doing the right thing, you are probably
257 not doing the right thing. If you think there are changes
258 needed, get someone else to review them first _before_
259 submitting a patch. If these two lists do not match properly
260 bad things will happen.
264 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
265 If it fails, it's critical and will cause a teardown of the session */
266 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
267 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
270 enum parse_register_result {
271 PARSE_REGISTER_FAILED,
272 PARSE_REGISTER_UPDATE,
273 PARSE_REGISTER_QUERY,
276 enum subscriptiontype {
285 static const struct cfsubscription_types {
286 enum subscriptiontype type;
287 const char * const event;
288 const char * const mediatype;
289 const char * const text;
290 } subscription_types[] = {
291 { NONE, "-", "unknown", "unknown" },
292 /* RFC 4235: SIP Dialog event package */
293 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
294 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
295 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
296 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
297 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
300 /*! \brief SIP Request methods known by Asterisk */
302 SIP_UNKNOWN, /* Unknown response */
303 SIP_RESPONSE, /* Not request, response to outbound request */
309 SIP_PRACK, /* Not supported at all */
314 SIP_UPDATE, /* We can send UPDATE; but not accept it */
317 SIP_PUBLISH, /* Not supported at all */
318 SIP_PING, /* Not supported at all, no standard but still implemented out there */
321 /*! \brief Authentication types - proxy or www authentication
322 \note Endpoints, like Asterisk, should always use WWW authentication to
323 allow multiple authentications in the same call - to the proxy and
331 /*! \brief Authentication result from check_auth* functions */
332 enum check_auth_result {
333 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
334 /* XXX maybe this is the same as AUTH_NOT_FOUND */
337 AUTH_CHALLENGE_SENT = 1,
338 AUTH_SECRET_FAILED = -1,
339 AUTH_USERNAME_MISMATCH = -2,
340 AUTH_NOT_FOUND = -3, /* returned by register_verify */
342 AUTH_UNKNOWN_DOMAIN = -5,
345 /*! \brief States for outbound registrations (with register= lines in sip.conf */
346 enum sipregistrystate {
347 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
348 REG_STATE_REGSENT, /*!< Registration request sent */
349 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
350 REG_STATE_REGISTERED, /*!< Registered and done */
351 REG_STATE_REJECTED, /*!< Registration rejected */
352 REG_STATE_TIMEOUT, /*!< Registration timed out */
353 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
354 REG_STATE_FAILED, /*!< Registration failed after several tries */
357 /*! \brief definition of a sip proxy server
359 * For outbound proxies, this is allocated in the SIP peer dynamically or
360 * statically as the global_outboundproxy. The pointer in a SIP message is just
361 * a pointer and should *not* be de-allocated.
364 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
365 struct sockaddr_in ip; /*!< Currently used IP address and port */
366 time_t last_dnsupdate; /*!< When this was resolved */
367 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
368 /* Room for a SRV record chain based on the name */
371 enum can_create_dialog {
372 CAN_NOT_CREATE_DIALOG,
374 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
377 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
378 static const struct cfsip_methods {
380 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
382 enum can_create_dialog can_create;
384 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
385 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
386 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
387 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
388 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
389 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
390 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
391 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
392 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
393 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
394 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
395 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
396 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
397 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
398 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
399 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
400 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
403 /*! Define SIP option tags, used in Require: and Supported: headers
404 We need to be aware of these properties in the phones to use
405 the replace: header. We should not do that without knowing
406 that the other end supports it...
407 This is nothing we can configure, we learn by the dialog
408 Supported: header on the REGISTER (peer) or the INVITE
410 We are not using many of these today, but will in the future.
411 This is documented in RFC 3261
414 #define NOT_SUPPORTED 0
416 #define SIP_OPT_REPLACES (1 << 0)
417 #define SIP_OPT_100REL (1 << 1)
418 #define SIP_OPT_TIMER (1 << 2)
419 #define SIP_OPT_EARLY_SESSION (1 << 3)
420 #define SIP_OPT_JOIN (1 << 4)
421 #define SIP_OPT_PATH (1 << 5)
422 #define SIP_OPT_PREF (1 << 6)
423 #define SIP_OPT_PRECONDITION (1 << 7)
424 #define SIP_OPT_PRIVACY (1 << 8)
425 #define SIP_OPT_SDP_ANAT (1 << 9)
426 #define SIP_OPT_SEC_AGREE (1 << 10)
427 #define SIP_OPT_EVENTLIST (1 << 11)
428 #define SIP_OPT_GRUU (1 << 12)
429 #define SIP_OPT_TARGET_DIALOG (1 << 13)
430 #define SIP_OPT_NOREFERSUB (1 << 14)
431 #define SIP_OPT_HISTINFO (1 << 15)
432 #define SIP_OPT_RESPRIORITY (1 << 16)
434 /*! \brief List of well-known SIP options. If we get this in a require,
435 we should check the list and answer accordingly. */
436 static const struct cfsip_options {
437 int id; /*!< Bitmap ID */
438 int supported; /*!< Supported by Asterisk ? */
439 char * const text; /*!< Text id, as in standard */
440 } sip_options[] = { /* XXX used in 3 places */
441 /* RFC3891: Replaces: header for transfer */
442 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
443 /* One version of Polycom firmware has the wrong label */
444 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
445 /* RFC3262: PRACK 100% reliability */
446 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
447 /* RFC4028: SIP Session Timers */
448 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
449 /* RFC3959: SIP Early session support */
450 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
451 /* RFC3911: SIP Join header support */
452 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
453 /* RFC3327: Path support */
454 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
455 /* RFC3840: Callee preferences */
456 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
457 /* RFC3312: Precondition support */
458 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
459 /* RFC3323: Privacy with proxies*/
460 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
461 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
462 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
463 /* RFC3329: Security agreement mechanism */
464 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
465 /* SIMPLE events: RFC4662 */
466 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
467 /* GRUU: Globally Routable User Agent URI's */
468 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
469 /* RFC4538: Target-dialog */
470 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
471 /* Disable the REFER subscription, RFC 4488 */
472 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
473 /* ietf-sip-history-info-06.txt */
474 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
475 /* ietf-sip-resource-priority-10.txt */
476 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
480 /*! \brief SIP Methods we support */
481 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
483 /*! \brief SIP Extensions we support */
484 #define SUPPORTED_EXTENSIONS "replaces"
486 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
487 #define STANDARD_SIP_PORT 5060
488 /* Note: in many SIP headers, absence of a port number implies port 5060,
489 * and this is why we cannot change the above constant.
490 * There is a limited number of places in asterisk where we could,
491 * in principle, use a different "default" port number, but
492 * we do not support this feature at the moment.
495 /* Default values, set and reset in reload_config before reading configuration */
496 /* These are default values in the source. There are other recommended values in the
497 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
498 yet encouraging new behaviour on new installations
500 #define DEFAULT_CONTEXT "default"
501 #define DEFAULT_MOHINTERPRET "default"
502 #define DEFAULT_MOHSUGGEST ""
503 #define DEFAULT_VMEXTEN "asterisk"
504 #define DEFAULT_CALLERID "asterisk"
505 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
506 #define DEFAULT_MWITIME 10
507 #define DEFAULT_ALLOWGUEST TRUE
508 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
509 #define DEFAULT_COMPACTHEADERS FALSE
510 #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. */
511 #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. */
512 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
513 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
514 #define DEFAULT_ALLOW_EXT_DOM TRUE
515 #define DEFAULT_REALM "asterisk"
516 #define DEFAULT_NOTIFYRINGING TRUE
517 #define DEFAULT_PEDANTIC FALSE
518 #define DEFAULT_AUTOCREATEPEER FALSE
519 #define DEFAULT_QUALIFY FALSE
520 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
521 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
522 #ifndef DEFAULT_USERAGENT
523 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
527 /* Default setttings are used as a channel setting and as a default when
528 configuring devices */
529 static char default_context[AST_MAX_CONTEXT];
530 static char default_subscribecontext[AST_MAX_CONTEXT];
531 static char default_language[MAX_LANGUAGE];
532 static char default_callerid[AST_MAX_EXTENSION];
533 static char default_fromdomain[AST_MAX_EXTENSION];
534 static char default_notifymime[AST_MAX_EXTENSION];
535 static int default_qualify; /*!< Default Qualify= setting */
536 static char default_vmexten[AST_MAX_EXTENSION];
537 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
538 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
539 * a bridged channel on hold */
540 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
541 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
543 /* Global settings only apply to the channel */
544 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
545 static int global_limitonpeers; /*!< Match call limit on peers only */
546 static int global_rtautoclear;
547 static int global_notifyringing; /*!< Send notifications on ringing */
548 static int global_notifyhold; /*!< Send notifications on hold */
549 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
550 static int global_srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
551 static int pedanticsipchecking; /*!< Extra checking ? Default off */
552 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
553 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
554 static int global_relaxdtmf; /*!< Relax DTMF */
555 static int global_rtptimeout; /*!< Time out call if no RTP */
556 static int global_rtpholdtimeout;
557 static int global_rtpkeepalive; /*!< Send RTP keepalives */
558 static int global_reg_timeout;
559 static int global_regattempts_max; /*!< Registration attempts before giving up */
560 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
561 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
562 the global setting is in globals_flags[1] */
563 static int global_mwitime; /*!< Time between MWI checks for peers */
564 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
565 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
566 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
567 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
568 static int compactheaders; /*!< send compact sip headers */
569 static int recordhistory; /*!< Record SIP history. Off by default */
570 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
571 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
572 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
573 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
574 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
575 static int global_callevents; /*!< Whether we send manager events or not */
576 static int global_t1min; /*!< T1 roundtrip time minimum */
577 static int global_autoframing; /*!< Turn autoframing on or off. */
578 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
579 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
581 /*! \brief Codecs that we support by default: */
582 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
584 /* Object counters */
585 static int suserobjs = 0; /*!< Static users */
586 static int ruserobjs = 0; /*!< Realtime users */
587 static int speerobjs = 0; /*!< Statis peers */
588 static int rpeerobjs = 0; /*!< Realtime peers */
589 static int apeerobjs = 0; /*!< Autocreated peer objects */
590 static int regobjs = 0; /*!< Registry objects */
592 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
594 AST_MUTEX_DEFINE_STATIC(netlock);
596 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
597 when it's doing something critical. */
599 AST_MUTEX_DEFINE_STATIC(monlock);
601 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
603 /*! \brief This is the thread for the monitor which checks for input on the channels
604 which are not currently in use. */
605 static pthread_t monitor_thread = AST_PTHREADT_NULL;
607 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
608 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
610 static struct sched_context *sched; /*!< The scheduling context */
611 static struct io_context *io; /*!< The IO context */
612 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
614 #define DEC_CALL_LIMIT 0
615 #define INC_CALL_LIMIT 1
616 #define DEC_CALL_RINGING 2
617 #define INC_CALL_RINGING 3
619 /*! \brief sip_request: The data grabbed from the UDP socket */
621 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
622 char *rlPart2; /*!< The Request URI or Response Status */
623 int len; /*!< Length */
624 int headers; /*!< # of SIP Headers */
625 int method; /*!< Method of this request */
626 int lines; /*!< Body Content */
627 unsigned int flags; /*!< SIP_PKT Flags for this packet */
628 char *header[SIP_MAX_HEADERS];
629 char *line[SIP_MAX_LINES];
630 char data[SIP_MAX_PACKET];
631 unsigned int sdp_start; /*!< the line number where the SDP begins */
632 unsigned int sdp_end; /*!< the line number where the SDP ends */
636 * A sip packet is stored into the data[] buffer, with the header followed
637 * by an empty line and the body of the message.
638 * On outgoing packets, data is accumulated in data[] with len reflecting
639 * the next available byte, headers and lines count the number of lines
640 * in both parts. There are no '\0' in data[0..len-1].
642 * On received packet, the input read from the socket is copied into data[],
643 * len is set and the string is NUL-terminated. Then a parser fills up
644 * the other fields -header[] and line[] to point to the lines of the
645 * message, rlPart1 and rlPart2 parse the first lnie as below:
647 * Requests have in the first line METHOD URI SIP/2.0
648 * rlPart1 = method; rlPart2 = uri;
649 * Responses have in the first line SIP/2.0 code description
650 * rlPart1 = SIP/2.0; rlPart2 = code + description;
654 /*! \brief structure used in transfers */
656 struct ast_channel *chan1; /*!< First channel involved */
657 struct ast_channel *chan2; /*!< Second channel involved */
658 struct sip_request req; /*!< Request that caused the transfer (REFER) */
659 int seqno; /*!< Sequence number */
664 /*! \brief Parameters to the transmit_invite function */
665 struct sip_invite_param {
666 int addsipheaders; /*!< Add extra SIP headers */
667 const char *uri_options; /*!< URI options to add to the URI */
668 const char *vxml_url; /*!< VXML url for Cisco phones */
669 char *auth; /*!< Authentication */
670 char *authheader; /*!< Auth header */
671 enum sip_auth_type auth_type; /*!< Authentication type */
672 const char *replaces; /*!< Replaces header for call transfers */
673 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
676 /*! \brief Structure to save routing information for a SIP session */
678 struct sip_route *next;
682 /*! \brief Modes for SIP domain handling in the PBX */
684 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
685 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
688 /*! \brief Domain data structure.
689 \note In the future, we will connect this to a configuration tree specific
693 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
694 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
695 enum domain_mode mode; /*!< How did we find this domain? */
696 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
699 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
702 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
704 AST_LIST_ENTRY(sip_history) list;
705 char event[0]; /* actually more, depending on needs */
708 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
710 /*! \brief sip_auth: Credentials for authentication to other SIP services */
712 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
713 char username[256]; /*!< Username */
714 char secret[256]; /*!< Secret */
715 char md5secret[256]; /*!< MD5Secret */
716 struct sip_auth *next; /*!< Next auth structure in list */
719 /*--- Various flags for the flags field in the pvt structure */
720 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
721 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
722 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
723 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
724 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
725 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
726 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
727 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
728 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
729 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
730 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
731 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
732 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
733 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
734 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
735 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
736 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
737 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
738 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
739 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
740 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
742 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
743 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
744 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
745 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
746 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
747 /* re-INVITE related settings */
748 #define SIP_REINVITE (7 << 20) /*!< three bits used */
749 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
750 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
751 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
752 /* "insecure" settings */
753 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
754 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
755 /* Sending PROGRESS in-band settings */
756 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
757 #define SIP_PROG_INBAND_NEVER (0 << 25)
758 #define SIP_PROG_INBAND_NO (1 << 25)
759 #define SIP_PROG_INBAND_YES (2 << 25)
760 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
761 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
762 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
763 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
764 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
766 #define SIP_FLAGS_TO_COPY \
767 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
768 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
769 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
771 /*--- a new page of flags (for flags[1] */
773 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
774 #define SIP_PAGE2_RTUPDATE (1 << 1)
775 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
776 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
777 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
778 /* Space for addition of other realtime flags in the future */
779 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
780 #define SIP_PAGE2_DEBUG (3 << 11)
781 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
782 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
783 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
784 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
785 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
786 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
787 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
788 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
789 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
790 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
791 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
792 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
793 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
794 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
795 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
796 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (1 << 24) /*!< 24: Inactive */
797 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */
798 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */
799 #define SIP_PAGE2_NOTEXT (1 << 27) /*!< 26: Text not supported */
800 #define SIP_PAGE2_TEXTSUPPORT (1 << 28) /*!< 27: Global text enable */
801 #define SIP_PAGE2_DEBUG_TEXT (1 << 29) /*!< 28: Global text debug */
803 #define SIP_PAGE2_FLAGS_TO_COPY \
804 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
805 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
806 SIP_PAGE2_TEXTSUPPORT )
808 /* SIP packet flags */
809 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
810 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
811 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
813 /* T.38 set of flags */
814 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
815 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
816 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
817 /* Rate management */
818 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
819 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
820 /* UDP Error correction */
821 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
822 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
823 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
824 /* T38 Spec version */
825 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
826 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
827 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
828 /* Maximum Fax Rate */
829 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
830 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
831 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
832 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
833 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
834 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
836 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
837 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
839 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
840 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
841 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
842 #define sipdebug_text ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_TEXT)
844 /*! \brief T38 States for a call */
846 T38_DISABLED = 0, /*!< Not enabled */
847 T38_LOCAL_DIRECT, /*!< Offered from local */
848 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
849 T38_PEER_DIRECT, /*!< Offered from peer */
850 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
851 T38_ENABLED /*!< Negotiated (enabled) */
854 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
855 struct t38properties {
856 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
857 int capability; /*!< Our T38 capability */
858 int peercapability; /*!< Peers T38 capability */
859 int jointcapability; /*!< Supported T38 capability at both ends */
860 enum t38state state; /*!< T.38 state */
863 /*! \brief Parameters to know status of transfer */
865 REFER_IDLE, /*!< No REFER is in progress */
866 REFER_SENT, /*!< Sent REFER to transferee */
867 REFER_RECEIVED, /*!< Received REFER from transferrer */
868 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
869 REFER_ACCEPTED, /*!< Accepted by transferee */
870 REFER_RINGING, /*!< Target Ringing */
871 REFER_200OK, /*!< Answered by transfer target */
872 REFER_FAILED, /*!< REFER declined - go on */
873 REFER_NOAUTH /*!< We had no auth for REFER */
876 static const struct c_referstatusstring {
877 enum referstatus status;
879 } referstatusstrings[] = {
880 { REFER_IDLE, "<none>" },
881 { REFER_SENT, "Request sent" },
882 { REFER_RECEIVED, "Request received" },
883 { REFER_ACCEPTED, "Accepted" },
884 { REFER_RINGING, "Target ringing" },
885 { REFER_200OK, "Done" },
886 { REFER_FAILED, "Failed" },
887 { REFER_NOAUTH, "Failed - auth failure" }
890 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
891 /* OEJ: Should be moved to string fields */
893 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
894 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
895 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
896 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
897 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
898 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
899 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
900 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
901 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
902 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
903 struct sip_pvt *refer_call; /*!< Call we are referring */
904 int attendedtransfer; /*!< Attended or blind transfer? */
905 int localtransfer; /*!< Transfer to local domain? */
906 enum referstatus status; /*!< REFER status */
909 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
911 ast_mutex_t pvt_lock; /*!< Dialog private lock */
912 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
913 int method; /*!< SIP method that opened this dialog */
914 AST_DECLARE_STRING_FIELDS(
915 AST_STRING_FIELD(callid); /*!< Global CallID */
916 AST_STRING_FIELD(randdata); /*!< Random data */
917 AST_STRING_FIELD(accountcode); /*!< Account code */
918 AST_STRING_FIELD(realm); /*!< Authorization realm */
919 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
920 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
921 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
922 AST_STRING_FIELD(domain); /*!< Authorization domain */
923 AST_STRING_FIELD(from); /*!< The From: header */
924 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
925 AST_STRING_FIELD(exten); /*!< Extension where to start */
926 AST_STRING_FIELD(context); /*!< Context for this call */
927 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
928 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
929 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
930 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
931 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
932 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
933 AST_STRING_FIELD(language); /*!< Default language for this call */
934 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
935 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
936 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
937 AST_STRING_FIELD(redircause); /*!< Referring cause */
938 AST_STRING_FIELD(theirtag); /*!< Their tag */
939 AST_STRING_FIELD(username); /*!< [user] name */
940 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
941 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
942 AST_STRING_FIELD(uri); /*!< Original requested URI */
943 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
944 AST_STRING_FIELD(peersecret); /*!< Password */
945 AST_STRING_FIELD(peermd5secret);
946 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
947 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
948 AST_STRING_FIELD(via); /*!< Via: header */
949 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
950 /* we only store the part in <brackets> in this field. */
951 AST_STRING_FIELD(our_contact); /*!< Our contact header */
952 AST_STRING_FIELD(rpid); /*!< Our RPID header */
953 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
955 unsigned int ocseq; /*!< Current outgoing seqno */
956 unsigned int icseq; /*!< Current incoming seqno */
957 ast_group_t callgroup; /*!< Call group */
958 ast_group_t pickupgroup; /*!< Pickup group */
959 int lastinvite; /*!< Last Cseq of invite */
960 struct ast_flags flags[2]; /*!< SIP_ flags */
961 int timer_t1; /*!< SIP timer T1, ms rtt */
962 unsigned int sipoptions; /*!< Supported SIP options on the other end */
963 struct ast_codec_pref prefs; /*!< codec prefs */
964 int capability; /*!< Special capability (codec) */
965 int jointcapability; /*!< Supported capability at both ends (codecs) */
966 int peercapability; /*!< Supported peer capability */
967 int prefcodec; /*!< Preferred codec (outbound only) */
968 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
969 int jointnoncodeccapability; /*!< Joint Non codec capability */
970 int redircodecs; /*!< Redirect codecs */
971 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
972 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
973 struct t38properties t38; /*!< T38 settings */
974 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
975 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
976 int callingpres; /*!< Calling presentation */
977 int authtries; /*!< Times we've tried to authenticate */
978 int expiry; /*!< How long we take to expire */
979 long branch; /*!< The branch identifier of this session */
980 char tag[11]; /*!< Our tag for this session */
981 int sessionid; /*!< SDP Session ID */
982 int sessionversion; /*!< SDP Session Version */
983 struct sockaddr_in sa; /*!< Our peer */
984 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
985 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
986 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
987 time_t lastrtprx; /*!< Last RTP received */
988 time_t lastrtptx; /*!< Last RTP sent */
989 int rtptimeout; /*!< RTP timeout time */
990 struct sockaddr_in recv; /*!< Received as */
991 struct in_addr ourip; /*!< Our IP */
992 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
993 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
994 int route_persistant; /*!< Is this the "real" route? */
995 struct sip_auth *peerauth; /*!< Realm authentication */
996 int noncecount; /*!< Nonce-count */
997 char lastmsg[256]; /*!< Last Message sent/received */
998 int amaflags; /*!< AMA Flags */
999 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
1000 struct sip_request initreq; /*!< Latest request that opened a new transaction
1002 NOT the request that opened the dialog
1005 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1006 int autokillid; /*!< Auto-kill ID (scheduler) */
1007 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1008 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1009 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1010 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1011 int laststate; /*!< SUBSCRIBE: Last known extension state */
1012 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1014 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1016 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1017 Used in peerpoke, mwi subscriptions */
1018 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1019 struct ast_rtp *rtp; /*!< RTP Session */
1020 struct ast_rtp *vrtp; /*!< Video RTP session */
1021 struct ast_rtp *trtp; /*!< Text RTP session */
1022 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1023 struct sip_history_head *history; /*!< History of this SIP dialog */
1024 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1025 struct sip_pvt *next; /*!< Next dialog in chain */
1026 struct sip_invite_param *options; /*!< Options for INVITE */
1027 int autoframing; /*!< The number of Asters we group in a Pyroflax
1028 before strolling to the Grokyzpå
1029 (A bit unsure of this, please correct if
1033 static struct sip_pvt *dialoglist = NULL;
1035 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1036 AST_MUTEX_DEFINE_STATIC(dialoglock);
1038 /*! \brief hide the way the list is locked/unlocked */
1039 static void dialoglist_lock(void)
1041 ast_mutex_lock(&dialoglock);
1044 static void dialoglist_unlock(void)
1046 ast_mutex_unlock(&dialoglock);
1049 #define FLAG_RESPONSE (1 << 0)
1050 #define FLAG_FATAL (1 << 1)
1052 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1054 struct sip_pkt *next; /*!< Next packet in linked list */
1055 int retrans; /*!< Retransmission number */
1056 int method; /*!< SIP method for this packet */
1057 int seqno; /*!< Sequence number */
1058 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1059 struct sip_pvt *owner; /*!< Owner AST call */
1060 int retransid; /*!< Retransmission ID */
1061 int timer_a; /*!< SIP timer A, retransmission timer */
1062 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1063 int packetlen; /*!< Length of packet */
1067 /*! \brief Structure for SIP user data. User's place calls to us */
1069 /* Users who can access various contexts */
1070 ASTOBJ_COMPONENTS(struct sip_user);
1071 char secret[80]; /*!< Password */
1072 char md5secret[80]; /*!< Password in md5 */
1073 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1074 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1075 char cid_num[80]; /*!< Caller ID num */
1076 char cid_name[80]; /*!< Caller ID name */
1077 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1078 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1079 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1080 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1081 char useragent[256]; /*!< User agent in SIP request */
1082 struct ast_codec_pref prefs; /*!< codec prefs */
1083 ast_group_t callgroup; /*!< Call group */
1084 ast_group_t pickupgroup; /*!< Pickup Group */
1085 unsigned int sipoptions; /*!< Supported SIP options */
1086 struct ast_flags flags[2]; /*!< SIP_ flags */
1087 int amaflags; /*!< AMA flags for billing */
1088 int callingpres; /*!< Calling id presentation */
1089 int capability; /*!< Codec capability */
1090 int inUse; /*!< Number of calls in use */
1091 int call_limit; /*!< Limit of concurrent calls */
1092 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1093 struct ast_ha *ha; /*!< ACL setting */
1094 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1095 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1099 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1100 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1102 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1103 /*!< peer->name is the unique name of this object */
1104 char secret[80]; /*!< Password */
1105 char md5secret[80]; /*!< Password in MD5 */
1106 struct sip_auth *auth; /*!< Realm authentication list */
1107 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1108 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1109 char username[80]; /*!< Temporary username until registration */
1110 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1111 int amaflags; /*!< AMA Flags (for billing) */
1112 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1113 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1114 char fromuser[80]; /*!< From: user when calling this peer */
1115 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1116 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1117 char cid_num[80]; /*!< Caller ID num */
1118 char cid_name[80]; /*!< Caller ID name */
1119 int callingpres; /*!< Calling id presentation */
1120 int inUse; /*!< Number of calls in use */
1121 int inRinging; /*!< Number of calls ringing */
1122 int onHold; /*!< Peer has someone on hold */
1123 int call_limit; /*!< Limit of concurrent calls */
1124 int busy_level; /*!< Level of active channels where we signal busy */
1125 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1126 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1127 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1128 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1129 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1130 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1131 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1132 struct ast_codec_pref prefs; /*!< codec prefs */
1134 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1135 unsigned int sipoptions; /*!< Supported SIP options */
1136 struct ast_flags flags[2]; /*!< SIP_ flags */
1137 int expire; /*!< When to expire this peer registration */
1138 int capability; /*!< Codec capability */
1139 int rtptimeout; /*!< RTP timeout */
1140 int rtpholdtimeout; /*!< RTP Hold Timeout */
1141 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1142 ast_group_t callgroup; /*!< Call group */
1143 ast_group_t pickupgroup; /*!< Pickup group */
1144 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1145 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1146 struct sockaddr_in addr; /*!< IP address of peer */
1147 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1150 struct sip_pvt *call; /*!< Call pointer */
1151 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1152 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1153 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1154 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1155 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1156 struct ast_ha *ha; /*!< Access control list */
1157 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1158 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1164 /*! \brief Registrations with other SIP proxies */
1165 struct sip_registry {
1166 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1167 AST_DECLARE_STRING_FIELDS(
1168 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1169 AST_STRING_FIELD(realm); /*!< Authorization realm */
1170 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1171 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1172 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1173 AST_STRING_FIELD(domain); /*!< Authorization domain */
1174 AST_STRING_FIELD(username); /*!< Who we are registering as */
1175 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1176 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1177 AST_STRING_FIELD(secret); /*!< Password in clear text */
1178 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1179 AST_STRING_FIELD(callback); /*!< Contact extension */
1180 AST_STRING_FIELD(random);
1182 int portno; /*!< Optional port override */
1183 int expire; /*!< Sched ID of expiration */
1184 int expiry; /*!< Value to use for the Expires header */
1185 int regattempts; /*!< Number of attempts (since the last success) */
1186 int timeout; /*!< sched id of sip_reg_timeout */
1187 int refresh; /*!< How often to refresh */
1188 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1189 enum sipregistrystate regstate; /*!< Registration state (see above) */
1190 time_t regtime; /*!< Last successful registration time */
1191 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1192 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1193 struct sockaddr_in us; /*!< Who the server thinks we are */
1194 int noncecount; /*!< Nonce-count */
1195 char lastmsg[256]; /*!< Last Message sent/received */
1198 /* --- Linked lists of various objects --------*/
1200 /*! \brief The user list: Users and friends */
1201 static struct ast_user_list {
1202 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1205 /*! \brief The peer list: Peers and Friends */
1206 static struct ast_peer_list {
1207 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1210 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1211 static struct ast_register_list {
1212 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1216 static int temp_pvt_init(void *);
1217 static void temp_pvt_cleanup(void *);
1219 /*! \brief A per-thread temporary pvt structure */
1220 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1222 /*! \todo Move the sip_auth list to AST_LIST */
1223 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1226 /* --- Sockets and networking --------------*/
1227 static int sipsock = -1; /*!< Main socket for SIP network communication */
1228 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1229 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1230 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1231 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1232 static int externrefresh = 10;
1233 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1234 static struct in_addr __ourip;
1236 static struct sockaddr_in debugaddr;
1238 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1240 /*---------------------------- Forward declarations of functions in chan_sip.c */
1241 /*! \note This is added to help splitting up chan_sip.c into several files
1242 in coming releases */
1244 /*--- PBX interface functions */
1245 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1246 static int sip_devicestate(void *data);
1247 static int sip_sendtext(struct ast_channel *ast, const char *text);
1248 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1249 static int sip_hangup(struct ast_channel *ast);
1250 static int sip_answer(struct ast_channel *ast);
1251 static struct ast_frame *sip_read(struct ast_channel *ast);
1252 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1253 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1254 static int sip_transfer(struct ast_channel *ast, const char *dest);
1255 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1256 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1257 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1259 /*--- Transmitting responses and requests */
1260 static int sipsock_read(int *id, int fd, short events, void *ignore);
1261 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1262 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1263 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1264 static int retrans_pkt(void *data);
1265 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1266 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);
1267 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1268 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1269 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1270 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1271 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1272 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);
1273 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1274 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1275 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1276 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1277 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1278 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1279 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1280 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1281 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1282 static int transmit_refer(struct sip_pvt *p, const char *dest);
1283 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1284 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1285 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1286 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1287 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1288 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1289 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1290 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1291 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1292 static int does_peer_need_mwi(struct sip_peer *peer);
1294 /*--- Dialog management */
1295 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1296 int useglobal_nat, const int intended_method);
1297 static int __sip_autodestruct(void *data);
1298 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1299 static void sip_cancel_destroy(struct sip_pvt *p);
1300 static void sip_destroy(struct sip_pvt *p);
1301 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1302 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1303 static void __sip_pretend_ack(struct sip_pvt *p);
1304 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1305 static int auto_congest(void *nothing);
1306 static int update_call_counter(struct sip_pvt *fup, int event);
1307 static int hangup_sip2cause(int cause);
1308 static const char *hangup_cause2sip(int cause);
1309 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1310 static void free_old_route(struct sip_route *route);
1311 static void list_route(struct sip_route *route);
1312 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1313 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1314 struct sip_request *req, char *uri);
1315 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1316 static void check_pendings(struct sip_pvt *p);
1317 static void *sip_park_thread(void *stuff);
1318 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1319 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1321 /*--- Codec handling / SDP */
1322 static void try_suggested_sip_codec(struct sip_pvt *p);
1323 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1324 static const char *get_sdp(struct sip_request *req, const char *name);
1325 static int find_sdp(struct sip_request *req);
1326 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1327 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1328 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1329 int debug, int *min_packet_size);
1330 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1331 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1333 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1334 static void do_setnat(struct sip_pvt *p, int natflags);
1336 /*--- Authentication stuff */
1337 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1338 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1339 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1340 const char *secret, const char *md5secret, int sipmethod,
1341 char *uri, enum xmittype reliable, int ignore);
1342 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1343 int sipmethod, char *uri, enum xmittype reliable,
1344 struct sockaddr_in *sin, struct sip_peer **authpeer);
1345 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1347 /*--- Domain handling */
1348 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1349 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1350 static void clear_sip_domains(void);
1352 /*--- SIP realm authentication */
1353 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1354 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1355 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1357 /*--- Misc functions */
1358 static int sip_do_reload(enum channelreloadreason reason);
1359 static int reload_config(enum channelreloadreason reason);
1360 static int expire_register(void *data);
1361 static void *do_monitor(void *data);
1362 static int restart_monitor(void);
1363 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1364 static void sip_destroy(struct sip_pvt *p);
1365 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1366 static int sip_refer_allocate(struct sip_pvt *p);
1367 static void ast_quiet_chan(struct ast_channel *chan);
1368 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1370 /*--- Device monitoring and Device/extension state handling */
1371 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1372 static int sip_devicestate(void *data);
1373 static int sip_poke_noanswer(void *data);
1374 static int sip_poke_peer(struct sip_peer *peer);
1375 static void sip_poke_all_peers(void);
1376 static void sip_peer_hold(struct sip_pvt *p, int hold);
1378 /*--- Applications, functions, CLI and manager command helpers */
1379 static const char *sip_nat_mode(const struct sip_pvt *p);
1380 static int sip_show_inuse(int fd, int argc, char *argv[]);
1381 static char *transfermode2str(enum transfermodes mode) attribute_const;
1382 static char *nat2str(int nat) attribute_const;
1383 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1384 static int sip_show_users(int fd, int argc, char *argv[]);
1385 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1386 static int sip_show_peers(int fd, int argc, char *argv[]);
1387 static int sip_show_objects(int fd, int argc, char *argv[]);
1388 static void print_group(int fd, ast_group_t group, int crlf);
1389 static const char *dtmfmode2str(int mode) attribute_const;
1390 static const char *insecure2str(int port, int invite) attribute_const;
1391 static void cleanup_stale_contexts(char *new, char *old);
1392 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1393 static const char *domain_mode_to_text(const enum domain_mode mode);
1394 static int sip_show_domains(int fd, int argc, char *argv[]);
1395 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1396 static int sip_show_peer(int fd, int argc, char *argv[]);
1397 static int sip_show_user(int fd, int argc, char *argv[]);
1398 static int sip_show_registry(int fd, int argc, char *argv[]);
1399 static int sip_show_settings(int fd, int argc, char *argv[]);
1400 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1401 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1402 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1403 static int sip_show_channels(int fd, int argc, char *argv[]);
1404 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1405 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1406 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1407 static char *complete_sip_peer(const char *word, int state, int flags2);
1408 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1409 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1410 static char *complete_sip_user(const char *word, int state, int flags2);
1411 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1412 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1413 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1414 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1415 static int sip_show_channel(int fd, int argc, char *argv[]);
1416 static int sip_show_history(int fd, int argc, char *argv[]);
1417 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1418 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1419 static int sip_do_debug(int fd, int argc, char *argv[]);
1420 static int sip_no_debug(int fd, int argc, char *argv[]);
1421 static int sip_notify(int fd, int argc, char *argv[]);
1422 static int sip_do_history(int fd, int argc, char *argv[]);
1423 static int sip_no_history(int fd, int argc, char *argv[]);
1424 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1425 static int sip_addheader(struct ast_channel *chan, void *data);
1426 static int sip_do_reload(enum channelreloadreason reason);
1427 static int sip_reload(int fd, int argc, char *argv[]);
1430 Functions for enabling debug per IP or fully, or enabling history logging for
1433 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1434 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1435 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1436 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1437 static void sip_dump_history(struct sip_pvt *dialog);
1439 /*--- Device object handling */
1440 static struct sip_peer *temp_peer(const char *name);
1441 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1442 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1443 static int update_call_counter(struct sip_pvt *fup, int event);
1444 static void sip_destroy_peer(struct sip_peer *peer);
1445 static void sip_destroy_user(struct sip_user *user);
1446 static int sip_poke_peer(struct sip_peer *peer);
1447 static void set_peer_defaults(struct sip_peer *peer);
1448 static struct sip_peer *temp_peer(const char *name);
1449 static void register_peer_exten(struct sip_peer *peer, int onoff);
1450 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1451 static struct sip_user *find_user(const char *name, int realtime);
1452 static int sip_poke_peer_s(void *data);
1453 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1454 static void reg_source_db(struct sip_peer *peer);
1455 static void destroy_association(struct sip_peer *peer);
1456 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1458 /* Realtime device support */
1459 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1460 static struct sip_user *realtime_user(const char *username);
1461 static void update_peer(struct sip_peer *p, int expiry);
1462 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1463 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1465 /*--- Internal UA client handling (outbound registrations) */
1466 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1467 static void sip_registry_destroy(struct sip_registry *reg);
1468 static int sip_register(char *value, int lineno);
1469 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1470 static int sip_reregister(void *data);
1471 static int __sip_do_register(struct sip_registry *r);
1472 static int sip_reg_timeout(void *data);
1473 static void sip_send_all_registers(void);
1475 /*--- Parsing SIP requests and responses */
1476 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1477 static int determine_firstline_parts(struct sip_request *req);
1478 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1479 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1480 static int find_sip_method(const char *msg);
1481 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1482 static void parse_request(struct sip_request *req);
1483 static const char *get_header(const struct sip_request *req, const char *name);
1484 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1485 static int method_match(enum sipmethod id, const char *name);
1486 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1487 static char *get_in_brackets(char *tmp);
1488 static const char *find_alias(const char *name, const char *_default);
1489 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1490 static int lws2sws(char *msgbuf, int len);
1491 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1492 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1493 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1494 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1495 static int set_address_from_contact(struct sip_pvt *pvt);
1496 static void check_via(struct sip_pvt *p, struct sip_request *req);
1497 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1498 static int get_rpid_num(const char *input, char *output, int maxlen);
1499 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1500 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1501 static int get_msg_text(char *buf, int len, struct sip_request *req);
1502 static void free_old_route(struct sip_route *route);
1503 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1505 /*--- Constructing requests and responses */
1506 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1507 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1508 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1509 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1510 static int init_resp(struct sip_request *resp, const char *msg);
1511 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1512 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1513 static void build_via(struct sip_pvt *p);
1514 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1515 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1516 static char *generate_random_string(char *buf, size_t size);
1517 static void build_callid_pvt(struct sip_pvt *pvt);
1518 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1519 static void make_our_tag(char *tagbuf, size_t len);
1520 static int add_header(struct sip_request *req, const char *var, const char *value);
1521 static int add_header_contentLength(struct sip_request *req, int len);
1522 static int add_line(struct sip_request *req, const char *line);
1523 static int add_text(struct sip_request *req, const char *text);
1524 static int add_digit(struct sip_request *req, char digit, unsigned int duration);
1525 static int add_vidupdate(struct sip_request *req);
1526 static void add_route(struct sip_request *req, struct sip_route *route);
1527 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1528 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1529 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1530 static void set_destination(struct sip_pvt *p, char *uri);
1531 static void append_date(struct sip_request *req);
1532 static void build_contact(struct sip_pvt *p);
1533 static void build_rpid(struct sip_pvt *p);
1535 /*------Request handling functions */
1536 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1537 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);
1538 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1539 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1540 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1541 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1542 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1543 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1544 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1545 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1546 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1547 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1548 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1550 /*------Response handling functions */
1551 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1552 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1553 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1554 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1556 /*----- RTP interface functions */
1557 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);
1558 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1559 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1560 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1561 static int sip_get_codec(struct ast_channel *chan);
1562 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1564 /*------ T38 Support --------- */
1565 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1566 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1567 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1568 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1570 /*! \brief Definition of this channel for PBX channel registration */
1571 static const struct ast_channel_tech sip_tech = {
1573 .description = "Session Initiation Protocol (SIP)",
1574 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1575 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1576 .requester = sip_request_call,
1577 .devicestate = sip_devicestate,
1579 .hangup = sip_hangup,
1580 .answer = sip_answer,
1583 .write_video = sip_write,
1584 .write_text = sip_write,
1585 .indicate = sip_indicate,
1586 .transfer = sip_transfer,
1588 .send_digit_begin = sip_senddigit_begin,
1589 .send_digit_end = sip_senddigit_end,
1590 .bridge = ast_rtp_bridge,
1591 .early_bridge = ast_rtp_early_bridge,
1592 .send_text = sip_sendtext,
1595 /*! \brief This version of the sip channel tech has no send_digit_begin
1596 * callback. This is for use with channels using SIP INFO DTMF so that
1597 * the core knows that the channel doesn't want DTMF BEGIN frames. */
1598 static const struct ast_channel_tech sip_tech_info = {
1600 .description = "Session Initiation Protocol (SIP)",
1601 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1602 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1603 .requester = sip_request_call,
1604 .devicestate = sip_devicestate,
1606 .hangup = sip_hangup,
1607 .answer = sip_answer,
1610 .write_video = sip_write,
1611 .indicate = sip_indicate,
1612 .transfer = sip_transfer,
1614 .send_digit_end = sip_senddigit_end,
1615 .bridge = ast_rtp_bridge,
1616 .send_text = sip_sendtext,
1619 /**--- some list management macros. **/
1621 #define UNLINK(element, head, prev) do { \
1623 (prev)->next = (element)->next; \
1625 (head) = (element)->next; \
1628 /*! \brief Interface structure with callbacks used to connect to RTP module */
1629 static struct ast_rtp_protocol sip_rtp = {
1631 get_rtp_info: sip_get_rtp_peer,
1632 get_vrtp_info: sip_get_vrtp_peer,
1633 get_trtp_info: sip_get_trtp_peer,
1634 set_rtp_peer: sip_set_rtp_peer,
1635 get_codec: sip_get_codec,
1638 /*! \brief Helper function to lock, hiding the underlying locking mechanism. */
1639 static void sip_pvt_lock(struct sip_pvt *pvt)
1641 ast_mutex_lock(&pvt->pvt_lock);
1644 /*! \brief Helper function to unlock pvt, hiding the underlying locking mechanism. */
1645 static void sip_pvt_unlock(struct sip_pvt *pvt)
1647 ast_mutex_unlock(&pvt->pvt_lock);
1651 * helper functions to unreference various types of objects.
1652 * By handling them this way, we don't have to declare the
1653 * destructor on each call, which removes the chance of errors.
1655 static void unref_peer(struct sip_peer *peer)
1657 ASTOBJ_UNREF(peer, sip_destroy_peer);
1660 static void unref_user(struct sip_user *user)
1662 ASTOBJ_UNREF(user, sip_destroy_user);
1665 static void registry_unref(struct sip_registry *reg)
1667 if (option_debug > 2)
1668 ast_log(LOG_DEBUG, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
1669 ASTOBJ_UNREF(reg, sip_registry_destroy);
1672 /*! \brief Add object reference to SIP registry */
1673 static struct sip_registry *registry_addref(struct sip_registry *reg)
1675 if (option_debug > 2)
1676 ast_log(LOG_DEBUG, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
1677 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
1680 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1681 static struct ast_udptl_protocol sip_udptl = {
1683 get_udptl_info: sip_get_udptl_peer,
1684 set_udptl_peer: sip_set_udptl_peer,
1687 /*! \brief Append to SIP dialog history
1688 \return Always returns 0 */
1689 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1691 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1692 __attribute__ ((format (printf, 2, 3)));
1695 /*! \brief Convert transfer status to string */
1696 static const char *referstatus2str(enum referstatus rstatus)
1698 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1701 for (x = 0; x < i; x++) {
1702 if (referstatusstrings[x].status == rstatus)
1703 return referstatusstrings[x].text;
1708 /*! \brief Initialize the initital request packet in the pvt structure.
1709 This packet is used for creating replies and future requests in
1711 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1714 if (p->initreq.headers)
1715 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1717 ast_log(LOG_DEBUG, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1719 /* Use this as the basis */
1720 copy_request(&p->initreq, req);
1721 parse_request(&p->initreq);
1722 if (ast_test_flag(req, SIP_PKT_DEBUG))
1723 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1726 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1727 static void sip_alreadygone(struct sip_pvt *dialog)
1729 if (option_debug > 2)
1730 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1731 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1734 /*! Resolve DNS srv name or host name in a sip_proxy structure */
1735 static int proxy_update(struct sip_proxy *proxy)
1737 /* if it's actually an IP address and not a name,
1738 there's no need for a managed lookup */
1739 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
1740 /* Ok, not an IP address, then let's check if it's a domain or host */
1741 /* XXX Todo - if we have proxy port, don't do SRV */
1742 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
1743 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
1747 proxy->last_dnsupdate = time(NULL);
1751 /*! \brief Allocate and initialize sip proxy */
1752 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
1754 struct sip_proxy *proxy;
1755 proxy = ast_calloc(1, sizeof(struct sip_proxy));
1758 proxy->force = force;
1759 ast_copy_string(proxy->name, name, sizeof(proxy->name));
1760 if (!ast_strlen_zero(port))
1761 proxy->ip.sin_port = htons(atoi(port));
1762 proxy_update(proxy);
1766 /*! \brief Get default outbound proxy or global proxy */
1767 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
1769 if (peer && peer->outboundproxy) {
1770 if (option_debug && sipdebug)
1771 ast_log(LOG_DEBUG, "OBPROXY: Applying peer OBproxy to this call\n");
1772 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
1773 return peer->outboundproxy;
1775 if (global_outboundproxy.name[0]) {
1776 if (option_debug && sipdebug)
1777 ast_log(LOG_DEBUG, "OBPROXY: Applying global OBproxy to this call\n");
1778 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
1779 return &global_outboundproxy;
1781 if (option_debug && sipdebug)
1782 ast_log(LOG_DEBUG, "OBPROXY: Not applying OBproxy to this call\n");
1786 /*! \brief returns true if 'name' (with optional trailing whitespace)
1787 * matches the sip method 'id'.
1788 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1789 * a case-insensitive comparison to be more tolerant.
1790 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1792 static int method_match(enum sipmethod id, const char *name)
1794 int len = strlen(sip_methods[id].text);
1795 int l_name = name ? strlen(name) : 0;
1796 /* true if the string is long enough, and ends with whitespace, and matches */
1797 return (l_name >= len && name[len] < 33 &&
1798 !strncasecmp(sip_methods[id].text, name, len));
1801 /*! \brief find_sip_method: Find SIP method from header */
1802 static int find_sip_method(const char *msg)
1806 if (ast_strlen_zero(msg))
1808 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1809 if (method_match(i, msg))
1810 res = sip_methods[i].id;
1815 /*! \brief Parse supported header in incoming packet */
1816 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1820 unsigned int profile = 0;
1823 if (ast_strlen_zero(supported) )
1825 temp = ast_strdupa(supported);
1827 if (option_debug > 2 && sipdebug)
1828 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1830 for (next = temp; next; next = sep) {
1832 if ( (sep = strchr(next, ',')) != NULL)
1834 next = ast_skip_blanks(next);
1835 if (option_debug > 2 && sipdebug)
1836 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1837 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1838 if (!strcasecmp(next, sip_options[i].text)) {
1839 profile |= sip_options[i].id;
1841 if (option_debug > 2 && sipdebug)
1842 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1846 if (!found && option_debug > 2 && sipdebug) {
1847 if (!strncasecmp(next, "x-", 2))
1848 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1850 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1855 pvt->sipoptions = profile;
1859 /*! \brief See if we pass debug IP filter */
1860 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1864 if (debugaddr.sin_addr.s_addr) {
1865 if (((ntohs(debugaddr.sin_port) != 0)
1866 && (debugaddr.sin_port != addr->sin_port))
1867 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1873 /*! \brief The real destination address for a write */
1874 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1876 if (p->outboundproxy)
1877 return &p->outboundproxy->ip;
1879 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1882 /*! \brief Display SIP nat mode */
1883 static const char *sip_nat_mode(const struct sip_pvt *p)
1885 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1888 /*! \brief Test PVT for debugging output */
1889 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1893 return sip_debug_test_addr(sip_real_dst(p));
1896 /*! \brief Transmit SIP message */
1897 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1900 const struct sockaddr_in *dst = sip_real_dst(p);
1901 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1904 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));
1909 /*! \brief Build a Via header for a request */
1910 static void build_via(struct sip_pvt *p)
1912 /* Work around buggy UNIDEN UIP200 firmware */
1913 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1915 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1916 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1917 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1920 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1922 * Using the localaddr structure built up with localnet statements in sip.conf
1923 * apply it to their address to see if we need to substitute our
1924 * externip or can get away with our internal bindaddr
1926 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1928 struct sockaddr_in theirs, ours;
1930 /* Get our local information */
1931 ast_ouraddrfor(them, us);
1932 theirs.sin_addr = *them;
1933 ours.sin_addr = *us;
1935 if (localaddr && externip.sin_addr.s_addr &&
1936 ast_apply_ha(localaddr, &theirs) &&
1937 !ast_apply_ha(localaddr, &ours)) {
1938 if (externexpire && time(NULL) >= externexpire) {
1939 struct ast_hostent ahp;
1942 externexpire = time(NULL) + externrefresh;
1943 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1944 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1946 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1948 *us = externip.sin_addr;
1950 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1951 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1953 } else if (bindaddr.sin_addr.s_addr)
1954 *us = bindaddr.sin_addr;
1958 /*! \brief Append to SIP dialog history with arg list */
1959 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1961 char buf[80], *c = buf; /* max history length */
1962 struct sip_history *hist;
1965 vsnprintf(buf, sizeof(buf), fmt, ap);
1966 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1967 l = strlen(buf) + 1;
1968 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1970 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1974 memcpy(hist->event, buf, l);
1975 AST_LIST_INSERT_TAIL(p->history, hist, list);
1978 /*! \brief Append to SIP dialog history with arg list */
1979 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1986 append_history_va(p, fmt, ap);
1992 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1993 static int retrans_pkt(void *data)
1995 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1996 int reschedule = DEFAULT_RETRANS;
1998 /* Lock channel PVT */
1999 sip_pvt_lock(pkt->owner);
2001 if (pkt->retrans < MAX_RETRANS) {
2003 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2004 if (sipdebug && option_debug > 3)
2005 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
2009 if (sipdebug && option_debug > 3)
2010 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2014 pkt->timer_a = 2 * pkt->timer_a;
2016 /* For non-invites, a maximum of 4 secs */
2017 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2018 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2021 /* Reschedule re-transmit */
2022 reschedule = siptimer_a;
2023 if (option_debug > 3)
2024 ast_log(LOG_DEBUG, "** 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);
2027 if (sip_debug_test_pvt(pkt->owner)) {
2028 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2029 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2030 pkt->retrans, sip_nat_mode(pkt->owner),
2031 ast_inet_ntoa(dst->sin_addr),
2032 ntohs(dst->sin_port), pkt->data);
2035 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
2036 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2037 sip_pvt_unlock(pkt->owner);
2040 /* Too many retries */
2041 if (pkt->owner && pkt->method != SIP_OPTIONS) {
2042 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
2043 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
2045 if ((pkt->method == SIP_OPTIONS) && sipdebug)
2046 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2048 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
2050 pkt->retransid = -1;
2052 if (ast_test_flag(pkt, FLAG_FATAL)) {
2053 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2054 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2056 sip_pvt_lock(pkt->owner);
2058 if (pkt->owner->owner) {
2059 sip_alreadygone(pkt->owner);
2060 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2061 ast_queue_hangup(pkt->owner->owner);
2062 ast_channel_unlock(pkt->owner->owner);
2064 /* If no channel owner, destroy now */
2066 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2067 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER)
2068 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
2071 /* Remove the packet */
2072 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2074 UNLINK(cur, pkt->owner->packets, prev);
2075 sip_pvt_unlock(pkt->owner);
2081 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2082 sip_pvt_unlock(pkt->owner);
2086 /*! \brief Transmit packet with retransmits
2087 \return 0 on success, -1 on failure to allocate packet
2089 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
2091 struct sip_pkt *pkt;
2092 int siptimer_a = DEFAULT_RETRANS;
2094 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2096 memcpy(pkt->data, data, len);
2097 pkt->method = sipmethod;
2098 pkt->packetlen = len;
2099 pkt->next = p->packets;
2103 ast_set_flag(pkt, FLAG_RESPONSE);
2104 pkt->data[len] = '\0';
2105 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
2107 ast_set_flag(pkt, FLAG_FATAL);
2109 siptimer_a = pkt->timer_t1 * 2;
2111 /* Schedule retransmission */
2112 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2113 if (option_debug > 3 && sipdebug)
2114 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
2115 pkt->next = p->packets;
2118 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2119 if (sipmethod == SIP_INVITE) {
2120 /* Note this is a pending invite */
2121 p->pendinginvite = seqno;
2126 /*! \brief Kill a SIP dialog (called by scheduler) */
2127 static int __sip_autodestruct(void *data)
2129 struct sip_pvt *p = data;
2131 /* If this is a subscription, tell the phone that we got a timeout */
2132 if (p->subscribed) {
2133 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2134 p->subscribed = NONE;
2135 append_history(p, "Subscribestatus", "timeout");
2136 if (option_debug > 2)
2137 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2138 return 10000; /* Reschedule this destruction so that we know that it's gone */
2141 if (p->subscribed == MWI_NOTIFICATION)
2143 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2145 /* Reset schedule ID */
2149 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2150 ast_queue_hangup(p->owner);
2151 } else if (p->refer) {
2152 if (option_debug > 2)
2153 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2154 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2155 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2156 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2158 append_history(p, "AutoDestroy", "%s", p->callid);
2160 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2161 sip_destroy(p); /* Go ahead and destroy dialog. All attempts to recover is done */
2166 /*! \brief Schedule destruction of SIP dialog */
2167 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2170 if (p->timer_t1 == 0)
2171 p->timer_t1 = SIP_TIMER_T1; /* Set timer T1 if not set (RFC 3261) */
2172 ms = p->timer_t1 * 64;
2174 if (sip_debug_test_pvt(p))
2175 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2176 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2177 append_history(p, "SchedDestroy", "%d ms", ms);
2179 if (p->autokillid > -1)
2180 ast_sched_del(sched, p->autokillid);
2181 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2184 /*! \brief Cancel destruction of SIP dialog */
2185 static void sip_cancel_destroy(struct sip_pvt *p)
2187 if (p->autokillid > -1) {
2188 ast_sched_del(sched, p->autokillid);
2189 append_history(p, "CancelDestroy", "");
2194 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2195 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2197 struct sip_pkt *cur, *prev = NULL;
2198 const char *msg = "Not Found"; /* used only for debugging */
2202 /* If we have an outbound proxy for this dialog, then delete it now since
2203 the rest of the requests in this dialog needs to follow the routing.
2204 If obforcing is set, we will keep the outbound proxy during the whole
2205 dialog, regardless of what the SIP rfc says
2207 if (p->outboundproxy && !p->outboundproxy->force)
2208 p->outboundproxy = NULL;
2210 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2211 if (cur->seqno != seqno || ast_test_flag(cur, FLAG_RESPONSE) != resp)
2213 if (ast_test_flag(cur, FLAG_RESPONSE) || cur->method == sipmethod) {
2215 if (!resp && (seqno == p->pendinginvite)) {
2217 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2218 p->pendinginvite = 0;
2220 if (cur->retransid > -1) {
2221 if (sipdebug && option_debug > 3)
2222 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2223 ast_sched_del(sched, cur->retransid);
2224 cur->retransid = -1;
2226 UNLINK(cur, p->packets, prev);
2233 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2234 p->callid, resp ? "Response" : "Request", seqno, msg);
2237 /*! \brief Pretend to ack all packets
2238 * maybe the lock on p is not strictly necessary but there might be a race */
2239 static void __sip_pretend_ack(struct sip_pvt *p)
2241 struct sip_pkt *cur = NULL;
2243 while (p->packets) {
2245 if (cur == p->packets) {
2246 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2250 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2251 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2255 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2256 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2258 struct sip_pkt *cur;
2261 for (cur = p->packets; cur; cur = cur->next) {
2262 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2263 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2264 /* this is our baby */
2265 if (cur->retransid > -1) {
2266 if (option_debug > 3 && sipdebug)
2267 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2268 ast_sched_del(sched, cur->retransid);
2269 cur->retransid = -1;
2276 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2281 /*! \brief Copy SIP request, parse it */
2282 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2284 memset(dst, 0, sizeof(*dst));
2285 memcpy(dst->data, src->data, sizeof(dst->data));
2286 dst->len = src->len;
2290 /*! \brief add a blank line if no body */
2291 static void add_blank(struct sip_request *req)
2294 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2295 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2296 req->len += strlen(req->data + req->len);
2300 /*! \brief Transmit response on SIP request*/
2301 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2306 if (sip_debug_test_pvt(p)) {
2307 const struct sockaddr_in *dst = sip_real_dst(p);
2309 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2310 reliable ? "Reliably " : "", sip_nat_mode(p),
2311 ast_inet_ntoa(dst->sin_addr),
2312 ntohs(dst->sin_port), req->data);
2314 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2315 struct sip_request tmp;
2316 parse_copy(&tmp, req);
2317 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2318 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2321 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2322 __sip_xmit(p, req->data, req->len);
2328 /*! \brief Send SIP Request to the other part of the dialogue */
2329 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2333 /* If we have an outbound proxy, reset peer address
2336 if (p->outboundproxy) {
2337 p->sa = p->outboundproxy->ip;
2341 if (sip_debug_test_pvt(p)) {
2342 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2343 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);
2345 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);
2347 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2348 struct sip_request tmp;
2349 parse_copy(&tmp, req);
2350 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2353 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2354 __sip_xmit(p, req->data, req->len);
2358 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2359 * optionally with a limit on the search.
2360 * start must be past the first quote.
2362 static const char *find_closing_quote(const char *start, const char *lim)
2364 char last_char = '\0';
2366 for (s = start; *s && s != lim; last_char = *s++) {
2367 if (*s == '"' && last_char != '\\')
2373 /*! \brief Pick out text in brackets from character string
2374 \return pointer to terminated stripped string
2375 \param tmp input string that will be modified
2378 "foo" <bar> valid input, returns bar
2379 foo returns the whole string
2380 < "foo ... > returns the string between brackets
2381 < "foo... bogus (missing closing bracket), returns the whole string
2382 XXX maybe should still skip the opening bracket
2384 static char *get_in_brackets(char *tmp)
2386 const char *parse = tmp;
2387 char *first_bracket;
2390 * Skip any quoted text until we find the part in brackets.
2391 * On any error give up and return the full string.
2393 while ( (first_bracket = strchr(parse, '<')) ) {
2394 char *first_quote = strchr(parse, '"');
2396 if (!first_quote || first_quote > first_bracket)
2397 break; /* no need to look at quoted part */
2398 /* the bracket is within quotes, so ignore it */
2399 parse = find_closing_quote(first_quote + 1, NULL);
2400 if (!*parse) { /* not found, return full string ? */
2401 /* XXX or be robust and return in-bracket part ? */
2402 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2407 if (first_bracket) {
2408 char *second_bracket = strchr(first_bracket + 1, '>');
2409 if (second_bracket) {
2410 *second_bracket = '\0';
2411 tmp = first_bracket + 1;
2413 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2420 * parses a URI in its components.
2421 * If scheme is specified, drop it from the top.
2422 * If a component is not requested, do not split around it.
2423 * This means that if we don't have domain, we cannot split
2424 * name:pass and domain:port.
2425 * It is safe to call with ret_name, pass, domain, port
2426 * pointing all to the same place.
2427 * Init pointers to empty string so we never get NULL dereferencing.
2428 * Overwrites the string.
2429 * return 0 on success, other values on error.
2431 static int parse_uri(char *uri, char *scheme,
2432 char **ret_name, char **pass, char **domain, char **port, char **options)
2437 /* init field as required */
2442 name = strsep(&uri, ";"); /* remove options */
2444 int l = strlen(scheme);
2445 if (!strncmp(name, scheme, l))
2448 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, name);
2453 /* if we don't want to split around domain, keep everything as a name,
2454 * so we need to do nothing here, except remember why.
2457 /* store the result in a temp. variable to avoid it being
2458 * overwritten if arguments point to the same place.
2462 if ((c = strchr(name, '@')) == NULL) {
2463 /* domain-only URI, according to the SIP RFC. */
2470 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2474 if (pass && (c = strchr(name, ':'))) { /* user:password */
2480 if (ret_name) /* same as for domain, store the result only at the end */
2483 *options = uri ? uri : "";
2488 /*! \brief Send SIP MESSAGE text within a call
2489 Called from PBX core sendtext() application */
2490 static int sip_sendtext(struct ast_channel *ast, const char *text)
2492 struct sip_pvt *p = ast->tech_pvt;
2493 int debug = sip_debug_test_pvt(p);
2496 ast_verbose("Sending text %s on %s\n", text, ast->name);
2499 if (ast_strlen_zero(text))
2502 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2503 transmit_message_with_text(p, text);
2507 /*! \brief Update peer object in realtime storage
2508 If the Asterisk system name is set in asterisk.conf, we will use
2509 that name and store that in the "regserver" field in the sippeers
2510 table to facilitate multi-server setups.
2512 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2515 char ipaddr[INET_ADDRSTRLEN];
2516 char regseconds[20];
2517 char *tablename = NULL;
2519 char *sysname = ast_config_AST_SYSTEM_NAME;
2520 char *syslabel = NULL;
2522 time_t nowtime = time(NULL) + expirey;
2523 const char *fc = fullcontact ? "fullcontact" : NULL;
2525 int realtimeregs = ast_check_realtime("sipregs");
2527 tablename = realtimeregs ? "sipregs" : "sippeers";
2529 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2530 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2531 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2533 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2535 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2536 syslabel = "regserver";
2539 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2540 "port", port, "regseconds", regseconds,
2541 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2543 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
2544 "port", port, "regseconds", regseconds,
2545 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2548 /*! \brief Automatically add peer extension to dial plan */
2549 static void register_peer_exten(struct sip_peer *peer, int onoff)
2552 char *stringp, *ext, *context;
2554 /* XXX note that global_regcontext is both a global 'enable' flag and
2555 * the name of the global regexten context, if not specified
2558 if (ast_strlen_zero(global_regcontext))
2561 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2563 while ((ext = strsep(&stringp, "&"))) {
2564 if ((context = strchr(ext, '@'))) {
2565 *context++ = '\0'; /* split ext@context */
2566 if (!ast_context_find(context)) {
2567 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2571 context = global_regcontext;
2574 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2575 ast_strdup(peer->name), ast_free, "SIP");
2577 ast_context_remove_extension(context, ext, 1, NULL);
2581 /*! \brief Destroy peer object from memory */
2582 static void sip_destroy_peer(struct sip_peer *peer)
2584 if (option_debug > 2)
2585 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2587 if (peer->outboundproxy)
2588 free(peer->outboundproxy);
2590 /* Delete it, it needs to disappear */
2592 sip_destroy(peer->call);
2594 if (peer->mwipvt) /* We have an active subscription, delete it */
2595 sip_destroy(peer->mwipvt);
2597 if (peer->chanvars) {
2598 ast_variables_destroy(peer->chanvars);
2599 peer->chanvars = NULL;
2601 if (peer->expire > -1)
2602 ast_sched_del(sched, peer->expire);
2604 if (peer->pokeexpire > -1)
2605 ast_sched_del(sched, peer->pokeexpire);
2606 register_peer_exten(peer, FALSE);
2607 ast_free_ha(peer->ha);
2608 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2610 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
2612 if (option_debug > 2)
2613 ast_log(LOG_DEBUG,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
2616 clear_realm_authentication(peer->auth);
2619 ast_dnsmgr_release(peer->dnsmgr);
2623 /*! \brief Update peer data in database (if used) */
2624 static void update_peer(struct sip_peer *p, int expiry)
2626 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2627 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2628 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2629 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2634 /*! \brief realtime_peer: Get peer from realtime storage
2635 * Checks the "sippeers" realtime family from extconfig.conf
2636 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
2637 * \todo Consider adding check of port address when matching here to follow the same
2638 * algorithm as for static peers. Will we break anything by adding that?
2640 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2642 struct sip_peer *peer;
2643 struct ast_variable *var = NULL;
2644 struct ast_variable *varregs = NULL;
2645 struct ast_variable *tmp;
2646 char ipaddr[INET_ADDRSTRLEN];
2647 int realtimeregs = ast_check_realtime("sipregs");
2649 /* First check on peer name */
2651 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2653 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
2654 } else if (sin) { /* Then check on IP address for dynamic peers */
2655 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2656 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2657 if (var && realtimeregs) {
2660 if (!newpeername && !strcasecmp(tmp->name, "name"))
2661 newpeername = tmp->value;
2664 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
2667 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, NULL); /* Then check for registered hosts */
2669 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registered hosts */
2673 if (!newpeername && !strcasecmp(tmp->name, "name"))
2674 newpeername = tmp->value;
2677 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2685 for (tmp = var; tmp; tmp = tmp->next) {
2686 /* If this is type=user, then skip this object. */
2687 if (!strcasecmp(tmp->name, "type") &&
2688 !strcasecmp(tmp->value, "user")) {
2689 ast_variables_destroy(var);
2690 ast_variables_destroy(varregs);
2692 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2693 newpeername = tmp->value;
2697 if (!newpeername) { /* Did not find peer in realtime */
2698 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2699 ast_variables_destroy(var);
2704 /* Peer found in realtime, now build it in memory */
2705 peer = build_peer(newpeername, var, varregs, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2707 ast_variables_destroy(var);
2708 ast_variables_destroy(varregs);
2712 if (option_debug > 2)
2713 ast_log(LOG_DEBUG,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
2715 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2717 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2718 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2719 if (peer->expire > -1) {
2720 ast_sched_del(sched, peer->expire);
2722 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2724 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2726 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2728 ast_variables_destroy(var);
2729 ast_variables_destroy(varregs);
2734 /*! \brief Support routine for find_peer */
2735 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2737 /* We know name is the first field, so we can cast */
2738 struct sip_peer *p = (struct sip_peer *) name;
2739 return !(!inaddrcmp(&p->addr, sin) ||
2740 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2741 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2744 /*! \brief Locate peer by name or ip address
2745 * This is used on incoming SIP message to find matching peer on ip
2746 or outgoing message to find matching peer on name */
2747 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2749 struct sip_peer *p = NULL;
2752 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2754 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2757 p = realtime_peer(peer, sin);
2762 /*! \brief Remove user object from in-memory storage */
2763 static void sip_destroy_user(struct sip_user *user)
2765 if (option_debug > 2)
2766 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2767 ast_free_ha(user->ha);
2768 if (user->chanvars) {
2769 ast_variables_destroy(user->chanvars);
2770 user->chanvars = NULL;
2772 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2779 /*! \brief Load user from realtime storage
2780 * Loads user from "sipusers" category in realtime (extconfig.conf)
2781 * Users are matched on From: user name (the domain in skipped) */
2782 static struct sip_user *realtime_user(const char *username)
2784 struct ast_variable *var;
2785 struct ast_variable *tmp;
2786 struct sip_user *user = NULL;
2788 var = ast_load_realtime("sipusers", "name", username, NULL);
2793 for (tmp = var; tmp; tmp = tmp->next) {
2794 if (!strcasecmp(tmp->name, "type") &&
2795 !strcasecmp(tmp->value, "peer")) {
2796 ast_variables_destroy(var);
2801 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2803 if (!user) { /* No user found */
2804 ast_variables_destroy(var);
2808 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2809 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2811 ASTOBJ_CONTAINER_LINK(&userl,user);
2813 /* Move counter from s to r... */
2816 ast_set_flag(&user->flags[0], SIP_REALTIME);
2818 ast_variables_destroy(var);
2822 /*! \brief Locate user by name
2823 * Locates user by name (From: sip uri user name part) first
2824 * from in-memory list (static configuration) then from
2825 * realtime storage (defined in extconfig.conf) */
2826 static struct sip_user *find_user(const char *name, int realtime)
2828 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2830 u = realtime_user(name);
2834 /*! \brief Set nat mode on the various data sockets */
2835 static void do_setnat(struct sip_pvt *p, int natflags)
2837 const char *mode = natflags ? "On" : "Off";
2841 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2842 ast_rtp_setnat(p->rtp, natflags);
2846 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2847 ast_rtp_setnat(p->vrtp, natflags);
2851 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2852 ast_udptl_setnat(p->udptl, natflags);
2856 ast_log(LOG_DEBUG, "Setting NAT on TRTP to %s\n", mode);
2857 ast_rtp_setnat(p->trtp, natflags);
2861 /*! \brief Create address structure from peer reference.
2862 * return -1 on error, 0 on success.
2864 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2866 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2867 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2868 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2869 dialog->recv = dialog->sa;
2873 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2874 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2875 dialog->capability = peer->capability;
2876 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2877 ast_rtp_destroy(dialog->vrtp);
2878 dialog->vrtp = NULL;
2880 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
2881 ast_rtp_destroy(dialog->trtp);
2882 dialog->trtp = NULL;
2884 dialog->prefs = peer->prefs;
2885 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2886 dialog->t38.capability = global_t38_capability;
2887 if (dialog->udptl) {
2888 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2889 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2890 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2891 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2892 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2893 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2894 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2895 if (option_debug > 1)
2896 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2898 dialog->t38.jointcapability = dialog->t38.capability;
2899 } else if (dialog->udptl) {
2900 ast_udptl_destroy(dialog->udptl);
2901 dialog->udptl = NULL;
2903 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2906 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
2907 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2908 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2909 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2910 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2911 /* Set Frame packetization */
2912 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2913 dialog->autoframing = peer->autoframing;
2916 ast_rtp_setdtmf(dialog->vrtp, 0);
2917 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2918 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2919 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2920 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2923 ast_rtp_setdtmf(dialog->trtp, 0);
2924 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
2925 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
2926 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
2927 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
2930 ast_string_field_set(dialog, peername, peer->username);
2931 ast_string_field_set(dialog, authname, peer->username);
2932 ast_string_field_set(dialog, username, peer->username);
2933 ast_string_field_set(dialog, peersecret, peer->secret);
2934 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2935 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
2936 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
2937 ast_string_field_set(dialog, tohost, peer->tohost);
2938 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2939 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2942 tmpcall = ast_strdupa(dialog->callid);
2943 c = strchr(tmpcall, '@');
2946 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2949 dialog->outboundproxy = obproxy_get(dialog, peer);
2950 if (ast_strlen_zero(dialog->tohost))
2951 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2952 if (!ast_strlen_zero(peer->fromdomain))
2953 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2954 if (!ast_strlen_zero(peer->fromuser))
2955 ast_string_field_set(dialog, fromuser, peer->fromuser);
2956 dialog->callgroup = peer->callgroup;
2957 dialog->pickupgroup = peer->pickupgroup;
2958 dialog->allowtransfer = peer->allowtransfer;
2959 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2960 /* Minimum is settable or default to 100 ms */
2961 if (peer->maxms && peer->lastms)
2962 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2963 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2964 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2965 dialog->noncodeccapability |= AST_RTP_DTMF;
2967 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2968 ast_string_field_set(dialog, context, peer->context);
2969 dialog->rtptimeout = peer->rtptimeout;
2970 if (peer->call_limit)
2971 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2972 dialog->maxcallbitrate = peer->maxcallbitrate;
2977 /*! \brief create address structure from peer name
2978 * Or, if peer not found, find it in the global DNS
2979 * returns TRUE (-1) on failure, FALSE on success */
2980 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2983 struct ast_hostent ahp;
2984 struct sip_peer *peer;
2987 char host[MAXHOSTNAMELEN], *hostn;
2990 ast_copy_string(peername, opeer, sizeof(peername));
2991 port = strchr(peername, ':');
2994 dialog->sa.sin_family = AF_INET;
2995 dialog->timer_t1 = SIP_TIMER_T1; /* Default SIP retransmission timer T1 (RFC 3261) */
2996 peer = find_peer(peername, NULL, 1);
2999 int res = create_addr_from_peer(dialog, peer);
3004 ast_string_field_set(dialog, tohost, peername);
3006 /* Get the outbound proxy information */
3007 dialog->outboundproxy = obproxy_get(dialog, NULL);
3009 /* If we have an outbound proxy, don't bother with DNS resolution at all */
3010 if (dialog->outboundproxy)
3013 /* Let's see if we can find the host in DNS. First try DNS SRV records,
3014 then hostname lookup */
3017 portno = port ? atoi(port) : STANDARD_SIP_PORT;
3018 if (global_srvlookup) {
3019 char service[MAXHOSTNAMELEN];
3023 snprintf(service, sizeof(service), "_sip._udp.%s", peername);
3024 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
3030 hp = ast_gethostbyname(hostn, &ahp);
3032 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3035 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
3036 dialog->sa.sin_port = htons(portno);
3037 dialog->recv = dialog->sa;
3041 /*! \brief Scheduled congestion on a call */
3042 static int auto_congest(void *nothing)
3044 struct sip_pvt *p = nothing;
3049 /* XXX fails on possible deadlock */
3050 if (!ast_channel_trylock(p->owner)) {
3051 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
3052 append_history(p, "Cong", "Auto-congesting (timer)");
3053 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
3054 ast_channel_unlock(p->owner);
3062 /*! \brief Initiate SIP call from PBX
3063 * used from the dial() application */
3064 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
3068 struct varshead *headp;
3069 struct ast_var_t *current;
3070 const char *referer = NULL; /* SIP referrer */
3073 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
3074 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
3078 /* Check whether there is vxml_url, distinctive ring variables */
3079 headp=&ast->varshead;
3080 AST_LIST_TRAVERSE(headp,current,entries) {
3081 /* Check whether there is a VXML_URL variable */
3082 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
3083 p->options->vxml_url = ast_var_value(current);
3084 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
3085 p->options->uri_options = ast_var_value(current);
3086 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
3087 /* Check whether there is a variable with a name starting with SIPADDHEADER */
3088 p->options->addsipheaders = 1;
3089 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
3090 /* This is a transfered call */
3091 p->options->transfer = 1;
3092 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
3093 /* This is the referrer */
3094 referer = ast_var_value(current);
3095 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
3096 /* We're replacing a call. */
3097 p->options->replaces = ast_var_value(current);
3098 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
3099 p->t38.state = T38_LOCAL_DIRECT;
3101 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3107 ast_set_flag(&p->flags[0], SIP_OUTGOING);
3109 if (p->options->transfer) {
3113 if (sipdebug && option_debug > 2)
3114 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
3115 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
3117 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
3118 ast_string_field_set(p, cid_name, buf);
3121 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
3123 res = update_call_counter(p, INC_CALL_RINGING);
3128 p->callingpres = ast->cid.cid_pres;
3129 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
3130 p->jointnoncodeccapability = p->noncodeccapability;
3132 /* If there are no audio formats left to offer, punt */
3133 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
3134 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
3137 p->t38.jointcapability = p->t38.capability;
3138 if (option_debug > 1)
3139 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
3140 transmit_invite(p, SIP_INVITE, 1, 2);
3141 p->invitestate = INV_CALLING;
3143 /* Initialize auto-congest time */
3144 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
3150 /*! \brief Destroy registry object
3151 Objects created with the register= statement in static configuration */
3152 static void sip_registry_destroy(struct sip_registry *reg)
3155 if (option_debug > 2)
3156 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
3159 /* Clear registry before destroying to ensure
3160 we don't get reentered trying to grab the registry lock */
3161 reg->call->registry = NULL;
3162 if (option_debug > 2)
3163 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
3164 sip_destroy(reg->call);
3166 if (reg->expire > -1)
3167 ast_sched_del(sched, reg->expire);
3168 if (reg->timeout > -1)
3169 ast_sched_del(sched, reg->timeout);
3170 ast_string_field_free_pools(reg);
3176 /*! \brief Execute destruction of SIP dialog structure, release memory */
3177 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
3179 struct sip_pvt *cur, *prev = NULL;
3182 if (sip_debug_test_pvt(p) || option_debug > 2)
3183 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
3185 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT)) {
3186 update_call_counter(p, DEC_CALL_LIMIT);
3187 if (option_debug > 1)
3188 ast_log(LOG_DEBUG, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
3191 /* Remove link from peer to subscription of MWI */
3192 if (p->relatedpeer && p->relatedpeer->mwipvt)
3193 p->relatedpeer->mwipvt = NULL;
3196 sip_dump_history(p);
3201 if (p->stateid > -1)
3202 ast_extension_state_del(p->stateid, NULL);
3204 ast_sched_del(sched, p->initid);
3205 if (p->autokillid > -1)
3206 ast_sched_del(sched, p->autokillid);
3209 ast_rtp_destroy(p->rtp);
3211 ast_rtp_destroy(p->vrtp);
3213 ast_rtp_destroy(p->trtp);
3215 ast_udptl_destroy(p->udptl);
3219 free_old_route(p->route);
3223 if (p->registry->call == p)
3224 p->registry->call = NULL;
3225 registry_unref(p->registry);
3228 /* Unlink us from the owner if we have one */
3231 ast_channel_lock(p->owner);
3233 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3234 p->owner->tech_pvt = NULL;
3236 ast_channel_unlock(p->owner);
3240 struct sip_history *hist;
3241 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
3247 /* Lock dialog list before removing ourselves from the list */
3250 for (prev = NULL, cur = dialoglist; cur; prev = cur, cur = cur->next) {
3252 UNLINK(cur, dialoglist, prev);
3257 dialoglist_unlock();
3259 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3263 /* remove all current packets in this dialog */
3264 while((cp = p->packets)) {
3265 p->packets = p->packets->next;
3266 if (cp->retransid > -1)
3267 ast_sched_del(sched, cp->retransid);
3271 ast_variables_destroy(p->chanvars);
3274 ast_mutex_destroy(&p->pvt_lock);
3276 ast_string_field_free_pools(p);
3281 /*! \brief update_call_counter: Handle call_limit for SIP users
3282 * Setting a call-limit will cause calls above the limit not to be accepted.
3284 * Remember that for a type=friend, there's one limit for the user and
3285 * another for the peer, not a combined call limit.
3286 * This will cause unexpected behaviour in subscriptions, since a "friend"
3287 * is *two* devices in Asterisk, not one.
3289 * Thought: For realtime, we should probably update storage with inuse counter...
3291 * \return 0 if call is ok (no call limit, below threshold)
3292 * -1 on rejection of call
3295 static int update_call_counter(struct sip_pvt *fup, int event)
3298 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3299 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
3300 struct sip_user *u = NULL;
3301 struct sip_peer *p = NULL;
3303 if (option_debug > 2)
3304 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3306 /* Test if we need to check call limits, in order to avoid
3307 realtime lookups if we do not need it */
3308 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
3311 ast_copy_string(name, fup->username, sizeof(name));
3313 /* Check the list of users only for incoming calls */
3314 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3316 call_limit = &u->call_limit;
3318 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3320 call_limit = &p->call_limit;
3321 inringing = &p->inRinging;
3322 ast_copy_string(name, fup->peername, sizeof(name));
3325 if (option_debug > 1)
3326 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3331 /* incoming and outgoing affects the inUse counter */
3332 case DEC_CALL_LIMIT:
3333 /* Decrement inuse count if applicable */
3334 if (inuse && ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
3335 ast_atomic_fetchadd_int(inuse, -1);
3336 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
3339 /* Decrement ringing count if applicable */
3340 if (inringing && ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3341 ast_atomic_fetchadd_int(inringing, -1);
3342 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3344 /* Decrement onhold count if applicable */
3345 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold)
3346 sip_peer_hold(fup, FALSE);
3347 if (option_debug > 1 || sipdebug)
3348 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3351 case INC_CALL_RINGING:
3352 case INC_CALL_LIMIT:
3353 /* If call limit is active and we have reached the limit, reject the call */
3354 if (*call_limit > 0 ) {
3355 if (*inuse >= *call_limit) {
3356 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3364 if (inringing && (event == INC_CALL_RINGING)) {
3365 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3366 ast_atomic_fetchadd_int(inringing, +1);
3367 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3371 ast_atomic_fetchadd_int(inuse, +1);
3372 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3373 if (option_debug > 1 || sipdebug) {
3374 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3378 case DEC_CALL_RINGING:
3379 if (inringing && ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3380 ast_atomic_fetchadd_int(inringing, -1);
3381 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3386 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3389 ast_device_state_changed("SIP/%s", p->name);
3391 } else /* u must be set */
3396 /*! \brief Destroy SIP call structure */
3397 static void sip_destroy(struct sip_pvt *p)
3399 if (option_debug > 2)
3400 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3401 __sip_destroy(p, TRUE, TRUE);
3404 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3405 static int hangup_sip2cause(int cause)
3407 /* Possible values taken from causes.h */
3410 case 401: /* Unauthorized */
3411 return AST_CAUSE_CALL_REJECTED;
3412 case 403: /* Not found */
3413 return AST_CAUSE_CALL_REJECTED;
3414 case 404: /* Not found */
3415 return AST_CAUSE_UNALLOCATED;
3416 case 405: /* Method not allowed */
3417 return AST_CAUSE_INTERWORKING;
3418 case 407: /* Proxy authentication required */
3419 return AST_CAUSE_CALL_REJECTED;
3420 case 408: /* No reaction */
3421 return AST_CAUSE_NO_USER_RESPONSE;
3422 case 409: /* Conflict */
3423 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3424 case 410: /* Gone */
3425 return AST_CAUSE_UNALLOCATED;
3426 case 411: /* Length required */
3427 return AST_CAUSE_INTERWORKING;
3428 case 413: /* Request entity too large */
3429 return AST_CAUSE_INTERWORKING;
3430 case 414: /* Request URI too large */
3431 return AST_CAUSE_INTERWORKING;
3432 case 415: /* Unsupported media type */
3433 return AST_CAUSE_INTERWORKING;
3434 case 420: /* Bad extension */
3435 return AST_CAUSE_NO_ROUTE_DESTINATION;
3436 case 480: /* No answer */
3437 return AST_CAUSE_NO_ANSWER;
3438 case 481: /* No answer */
3439 return AST_CAUSE_INTERWORKING;
3440 case 482: /* Loop detected */
3441 return AST_CAUSE_INTERWORKING;
3442 case 483: /* Too many hops */
3443 return AST_CAUSE_NO_ANSWER;
3444 case 484: /* Address incomplete */
3445 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3446 case 485: /* Ambiguous */
3447 return AST_CAUSE_UNALLOCATED;
3448 case 486: /* Busy everywhere */
3449 return AST_CAUSE_BUSY;
3450 case 487: /* Request terminated */
3451 return AST_CAUSE_INTERWORKING;
3452 case 488: /* No codecs approved */
3453 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3454 case 491: /* Request pending */
3455 return AST_CAUSE_INTERWORKING;
3456 case 493: /* Undecipherable */
3457 return AST_CAUSE_INTERWORKING;
3458 case 500: /* Server internal failure */
3459 return AST_CAUSE_FAILURE;
3460 case 501: /* Call rejected */
3461 return AST_CAUSE_FACILITY_REJECTED;
3463 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3464 case 503: /* Service unavailable */
3465 return AST_CAUSE_CONGESTION;
3466 case 504: /* Gateway timeout */
3467 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3468 case 505: /* SIP version not supported */
3469 return AST_CAUSE_INTERWORKING;
3470 case 600: /* Busy everywhere */
3471 return AST_CAUSE_USER_BUSY;
3472 case 603: /* Decline */
3473 return AST_CAUSE_CALL_REJECTED;
3474 case 604: /* Does not exist anywhere */
3475 return AST_CAUSE_UNALLOCATED;
3476 case 606: /* Not acceptable */
3477 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3479 return AST_CAUSE_NORMAL;