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/lock.h"
117 #include "asterisk/sched.h"
118 #include "asterisk/io.h"
119 #include "asterisk/rtp.h"
120 #include "asterisk/udptl.h"
121 #include "asterisk/acl.h"
122 #include "asterisk/manager.h"
123 #include "asterisk/callerid.h"
124 #include "asterisk/cli.h"
125 #include "asterisk/app.h"
126 #include "asterisk/musiconhold.h"
127 #include "asterisk/dsp.h"
128 #include "asterisk/features.h"
129 #include "asterisk/acl.h"
130 #include "asterisk/srv.h"
131 #include "asterisk/astdb.h"
132 #include "asterisk/causes.h"
133 #include "asterisk/utils.h"
134 #include "asterisk/file.h"
135 #include "asterisk/astobj.h"
136 #include "asterisk/dnsmgr.h"
137 #include "asterisk/devicestate.h"
138 #include "asterisk/linkedlists.h"
139 #include "asterisk/stringfields.h"
140 #include "asterisk/monitor.h"
141 #include "asterisk/localtime.h"
142 #include "asterisk/abstract_jb.h"
143 #include "asterisk/compiler.h"
144 #include "asterisk/threadstorage.h"
145 #include "asterisk/translate.h"
155 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
156 #ifndef IPTOS_MINCOST
157 #define IPTOS_MINCOST 0x02
160 /* #define VOCAL_DATA_HACK */
162 #define DEFAULT_DEFAULT_EXPIRY 120
163 #define DEFAULT_MIN_EXPIRY 60
164 #define DEFAULT_MAX_EXPIRY 3600
165 #define DEFAULT_REGISTRATION_TIMEOUT 20
166 #define DEFAULT_MAX_FORWARDS "70"
168 /* guard limit must be larger than guard secs */
169 /* guard min must be < 1000, and should be >= 250 */
170 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
171 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
173 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
174 GUARD_PCT turns out to be lower than this, it
175 will use this time instead.
176 This is in milliseconds. */
177 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
178 below EXPIRY_GUARD_LIMIT */
179 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
181 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
182 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
183 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
184 static int expiry = DEFAULT_EXPIRY;
187 #define MAX(a,b) ((a) > (b) ? (a) : (b))
190 #define CALLERID_UNKNOWN "Unknown"
192 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
193 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
194 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
196 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
197 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
198 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
199 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
200 \todo Use known T1 for timeout (peerpoke)
202 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
203 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
205 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
206 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
207 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
209 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
211 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
212 static struct ast_jb_conf default_jbconf =
216 .resync_threshold = -1,
219 static struct ast_jb_conf global_jbconf;
221 static const char config[] = "sip.conf";
222 static const char notify_config[] = "sip_notify.conf";
227 /*! \brief Authorization scheme for call transfers
228 \note Not a bitfield flag, since there are plans for other modes,
229 like "only allow transfers for authenticated devices" */
231 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
232 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
241 /*! \brief States for the INVITE transaction, not the dialog
242 \note this is for the INVITE that sets up the dialog
245 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
246 INV_CALLING = 1, /*!< Invite sent, no answer */
247 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
248 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
249 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
250 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
251 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
252 The only way out of this is a BYE from one side */
253 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
256 /* Do _NOT_ make any changes to this enum, or the array following it;
257 if you think you are doing the right thing, you are probably
258 not doing the right thing. If you think there are changes
259 needed, get someone else to review them first _before_
260 submitting a patch. If these two lists do not match properly
261 bad things will happen.
265 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
266 If it fails, it's critical and will cause a teardown of the session */
267 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
268 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
271 enum parse_register_result {
272 PARSE_REGISTER_FAILED,
273 PARSE_REGISTER_UPDATE,
274 PARSE_REGISTER_QUERY,
277 enum subscriptiontype {
286 static const struct cfsubscription_types {
287 enum subscriptiontype type;
288 const char * const event;
289 const char * const mediatype;
290 const char * const text;
291 } subscription_types[] = {
292 { NONE, "-", "unknown", "unknown" },
293 /* RFC 4235: SIP Dialog event package */
294 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
295 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
296 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
297 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
298 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
301 /*! \brief SIP Request methods known by Asterisk */
303 SIP_UNKNOWN, /* Unknown response */
304 SIP_RESPONSE, /* Not request, response to outbound request */
310 SIP_PRACK, /* Not supported at all */
315 SIP_UPDATE, /* We can send UPDATE; but not accept it */
318 SIP_PUBLISH, /* Not supported at all */
319 SIP_PING, /* Not supported at all, no standard but still implemented out there */
322 /*! \brief Authentication types - proxy or www authentication
323 \note Endpoints, like Asterisk, should always use WWW authentication to
324 allow multiple authentications in the same call - to the proxy and
332 /*! \brief Authentication result from check_auth* functions */
333 enum check_auth_result {
334 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
335 /* XXX maybe this is the same as AUTH_NOT_FOUND */
338 AUTH_CHALLENGE_SENT = 1,
339 AUTH_SECRET_FAILED = -1,
340 AUTH_USERNAME_MISMATCH = -2,
341 AUTH_NOT_FOUND = -3, /* returned by register_verify */
343 AUTH_UNKNOWN_DOMAIN = -5,
346 /*! \brief States for outbound registrations (with register= lines in sip.conf */
347 enum sipregistrystate {
348 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
349 REG_STATE_REGSENT, /*!< Registration request sent */
350 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
351 REG_STATE_REGISTERED, /*!< Registred and done */
352 REG_STATE_REJECTED, /*!< Registration rejected */
353 REG_STATE_TIMEOUT, /*!< Registration timed out */
354 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
355 REG_STATE_FAILED, /*!< Registration failed after several tries */
358 enum can_create_dialog {
359 CAN_NOT_CREATE_DIALOG,
361 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
364 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
365 static const struct cfsip_methods {
367 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
369 enum can_create_dialog can_create;
371 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
372 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
373 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
374 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
375 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
376 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
377 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
378 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
379 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
380 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
381 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
382 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
383 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
384 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
385 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
386 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
387 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
390 /*! Define SIP option tags, used in Require: and Supported: headers
391 We need to be aware of these properties in the phones to use
392 the replace: header. We should not do that without knowing
393 that the other end supports it...
394 This is nothing we can configure, we learn by the dialog
395 Supported: header on the REGISTER (peer) or the INVITE
397 We are not using many of these today, but will in the future.
398 This is documented in RFC 3261
401 #define NOT_SUPPORTED 0
403 #define SIP_OPT_REPLACES (1 << 0)
404 #define SIP_OPT_100REL (1 << 1)
405 #define SIP_OPT_TIMER (1 << 2)
406 #define SIP_OPT_EARLY_SESSION (1 << 3)
407 #define SIP_OPT_JOIN (1 << 4)
408 #define SIP_OPT_PATH (1 << 5)
409 #define SIP_OPT_PREF (1 << 6)
410 #define SIP_OPT_PRECONDITION (1 << 7)
411 #define SIP_OPT_PRIVACY (1 << 8)
412 #define SIP_OPT_SDP_ANAT (1 << 9)
413 #define SIP_OPT_SEC_AGREE (1 << 10)
414 #define SIP_OPT_EVENTLIST (1 << 11)
415 #define SIP_OPT_GRUU (1 << 12)
416 #define SIP_OPT_TARGET_DIALOG (1 << 13)
417 #define SIP_OPT_NOREFERSUB (1 << 14)
418 #define SIP_OPT_HISTINFO (1 << 15)
419 #define SIP_OPT_RESPRIORITY (1 << 16)
421 /*! \brief List of well-known SIP options. If we get this in a require,
422 we should check the list and answer accordingly. */
423 static const struct cfsip_options {
424 int id; /*!< Bitmap ID */
425 int supported; /*!< Supported by Asterisk ? */
426 char * const text; /*!< Text id, as in standard */
427 } sip_options[] = { /* XXX used in 3 places */
428 /* RFC3891: Replaces: header for transfer */
429 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
430 /* One version of Polycom firmware has the wrong label */
431 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
432 /* RFC3262: PRACK 100% reliability */
433 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
434 /* RFC4028: SIP Session Timers */
435 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
436 /* RFC3959: SIP Early session support */
437 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
438 /* RFC3911: SIP Join header support */
439 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
440 /* RFC3327: Path support */
441 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
442 /* RFC3840: Callee preferences */
443 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
444 /* RFC3312: Precondition support */
445 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
446 /* RFC3323: Privacy with proxies*/
447 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
448 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
449 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
450 /* RFC3329: Security agreement mechanism */
451 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
452 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
453 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
454 /* GRUU: Globally Routable User Agent URI's */
455 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
456 /* Target-dialog: draft-ietf-sip-target-dialog-03.txt */
457 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
458 /* Disable the REFER subscription, RFC 4488 */
459 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
460 /* ietf-sip-history-info-06.txt */
461 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
462 /* ietf-sip-resource-priority-10.txt */
463 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
467 /*! \brief SIP Methods we support */
468 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
470 /*! \brief SIP Extensions we support */
471 #define SUPPORTED_EXTENSIONS "replaces"
473 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
474 #define STANDARD_SIP_PORT 5060
475 /* Note: in many SIP headers, absence of a port number implies port 5060,
476 * and this is why we cannot change the above constant.
477 * There is a limited number of places in asterisk where we could,
478 * in principle, use a different "default" port number, but
479 * we do not support this feature at the moment.
482 /* Default values, set and reset in reload_config before reading configuration */
483 /* These are default values in the source. There are other recommended values in the
484 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
485 yet encouraging new behaviour on new installations
487 #define DEFAULT_CONTEXT "default"
488 #define DEFAULT_MOHINTERPRET "default"
489 #define DEFAULT_MOHSUGGEST ""
490 #define DEFAULT_VMEXTEN "asterisk"
491 #define DEFAULT_CALLERID "asterisk"
492 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
493 #define DEFAULT_MWITIME 10
494 #define DEFAULT_ALLOWGUEST TRUE
495 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
496 #define DEFAULT_COMPACTHEADERS FALSE
497 #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. */
498 #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. */
499 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
500 #define DEFAULT_ALLOW_EXT_DOM TRUE
501 #define DEFAULT_REALM "asterisk"
502 #define DEFAULT_NOTIFYRINGING TRUE
503 #define DEFAULT_PEDANTIC FALSE
504 #define DEFAULT_AUTOCREATEPEER FALSE
505 #define DEFAULT_QUALIFY FALSE
506 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
507 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
508 #ifndef DEFAULT_USERAGENT
509 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
513 /* Default setttings are used as a channel setting and as a default when
514 configuring devices */
515 static char default_context[AST_MAX_CONTEXT];
516 static char default_subscribecontext[AST_MAX_CONTEXT];
517 static char default_language[MAX_LANGUAGE];
518 static char default_callerid[AST_MAX_EXTENSION];
519 static char default_fromdomain[AST_MAX_EXTENSION];
520 static char default_notifymime[AST_MAX_EXTENSION];
521 static int default_qualify; /*!< Default Qualify= setting */
522 static char default_vmexten[AST_MAX_EXTENSION];
523 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
524 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
525 * a bridged channel on hold */
526 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
527 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
529 /* Global settings only apply to the channel */
530 static int global_limitonpeers; /*!< Match call limit on peers only */
531 static int global_rtautoclear;
532 static int global_notifyringing; /*!< Send notifications on ringing */
533 static int global_notifyhold; /*!< Send notifications on hold */
534 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
535 static int global_srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
536 static int pedanticsipchecking; /*!< Extra checking ? Default off */
537 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
538 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
539 static int global_relaxdtmf; /*!< Relax DTMF */
540 static int global_rtptimeout; /*!< Time out call if no RTP */
541 static int global_rtpholdtimeout;
542 static int global_rtpkeepalive; /*!< Send RTP keepalives */
543 static int global_reg_timeout;
544 static int global_regattempts_max; /*!< Registration attempts before giving up */
545 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
546 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
547 the global setting is in globals_flags[1] */
548 static int global_mwitime; /*!< Time between MWI checks for peers */
549 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
550 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
551 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
552 static int compactheaders; /*!< send compact sip headers */
553 static int recordhistory; /*!< Record SIP history. Off by default */
554 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
555 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
556 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
557 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
558 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
559 static int global_callevents; /*!< Whether we send manager events or not */
560 static int global_t1min; /*!< T1 roundtrip time minimum */
561 static int global_autoframing; /*!< Turn autoframing on or off. */
562 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
564 /*! \brief Codecs that we support by default: */
565 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
566 static int noncodeccapability = AST_RTP_DTMF;
568 /* Object counters */
569 static int suserobjs = 0; /*!< Static users */
570 static int ruserobjs = 0; /*!< Realtime users */
571 static int speerobjs = 0; /*!< Statis peers */
572 static int rpeerobjs = 0; /*!< Realtime peers */
573 static int apeerobjs = 0; /*!< Autocreated peer objects */
574 static int regobjs = 0; /*!< Registry objects */
576 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
578 AST_MUTEX_DEFINE_STATIC(netlock);
580 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
581 when it's doing something critical. */
583 AST_MUTEX_DEFINE_STATIC(monlock);
585 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
587 /*! \brief This is the thread for the monitor which checks for input on the channels
588 which are not currently in use. */
589 static pthread_t monitor_thread = AST_PTHREADT_NULL;
591 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
592 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
594 static struct sched_context *sched; /*!< The scheduling context */
595 static struct io_context *io; /*!< The IO context */
596 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
598 #define DEC_CALL_LIMIT 0
599 #define INC_CALL_LIMIT 1
600 #define DEC_CALL_RINGING 2
601 #define INC_CALL_RINGING 3
603 /*! \brief sip_request: The data grabbed from the UDP socket */
605 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
606 char *rlPart2; /*!< The Request URI or Response Status */
607 int len; /*!< Length */
608 int headers; /*!< # of SIP Headers */
609 int method; /*!< Method of this request */
610 int lines; /*!< Body Content */
611 unsigned int flags; /*!< SIP_PKT Flags for this packet */
612 char *header[SIP_MAX_HEADERS];
613 char *line[SIP_MAX_LINES];
614 char data[SIP_MAX_PACKET];
615 unsigned int sdp_start; /*!< the line number where the SDP begins */
616 unsigned int sdp_end; /*!< the line number where the SDP ends */
620 * A sip packet is stored into the data[] buffer, with the header followed
621 * by an empty line and the body of the message.
622 * On outgoing packets, data is accumulated in data[] with len reflecting
623 * the next available byte, headers and lines count the number of lines
624 * in both parts. There are no '\0' in data[0..len-1].
626 * On received packet, the input read from the socket is copied into data[],
627 * len is set and the string is NUL-terminated. Then a parser fills up
628 * the other fields -header[] and line[] to point to the lines of the
629 * message, rlPart1 and rlPart2 parse the first lnie as below:
631 * Requests have in the first line METHOD URI SIP/2.0
632 * rlPart1 = method; rlPart2 = uri;
633 * Responses have in the first line SIP/2.0 code description
634 * rlPart1 = SIP/2.0; rlPart2 = code + description;
638 /*! \brief structure used in transfers */
640 struct ast_channel *chan1; /*!< First channel involved */
641 struct ast_channel *chan2; /*!< Second channel involved */
642 struct sip_request req; /*!< Request that caused the transfer (REFER) */
643 int seqno; /*!< Sequence number */
648 /*! \brief Parameters to the transmit_invite function */
649 struct sip_invite_param {
650 int addsipheaders; /*!< Add extra SIP headers */
651 const char *uri_options; /*!< URI options to add to the URI */
652 const char *vxml_url; /*!< VXML url for Cisco phones */
653 char *auth; /*!< Authentication */
654 char *authheader; /*!< Auth header */
655 enum sip_auth_type auth_type; /*!< Authentication type */
656 const char *replaces; /*!< Replaces header for call transfers */
657 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
660 /*! \brief Structure to save routing information for a SIP session */
662 struct sip_route *next;
666 /*! \brief Modes for SIP domain handling in the PBX */
668 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
669 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
672 /*! \brief Domain data structure.
673 \note In the future, we will connect this to a configuration tree specific
677 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
678 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
679 enum domain_mode mode; /*!< How did we find this domain? */
680 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
683 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
686 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
688 AST_LIST_ENTRY(sip_history) list;
689 char event[0]; /* actually more, depending on needs */
692 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
694 /*! \brief sip_auth: Credentials for authentication to other SIP services */
696 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
697 char username[256]; /*!< Username */
698 char secret[256]; /*!< Secret */
699 char md5secret[256]; /*!< MD5Secret */
700 struct sip_auth *next; /*!< Next auth structure in list */
703 /*--- Various flags for the flags field in the pvt structure */
704 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
705 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
706 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
707 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
708 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
709 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
710 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
711 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
712 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
713 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
714 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
715 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
716 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
717 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
718 #define SIP_FREE_BIT (1 << 14) /*!< ---- */
719 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
720 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
721 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
722 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
723 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
724 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
726 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
727 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
728 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
729 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
730 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
731 /* re-INVITE related settings */
732 #define SIP_REINVITE (7 << 20) /*!< three bits used */
733 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
734 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
735 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
736 /* "insecure" settings */
737 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
738 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
739 /* Sending PROGRESS in-band settings */
740 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
741 #define SIP_PROG_INBAND_NEVER (0 << 25)
742 #define SIP_PROG_INBAND_NO (1 << 25)
743 #define SIP_PROG_INBAND_YES (2 << 25)
744 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
745 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
746 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
747 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
748 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
750 #define SIP_FLAGS_TO_COPY \
751 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
752 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
753 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
755 /*--- a new page of flags (for flags[1] */
757 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
758 #define SIP_PAGE2_RTUPDATE (1 << 1)
759 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
760 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
761 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
762 /* Space for addition of other realtime flags in the future */
763 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
764 #define SIP_PAGE2_DEBUG (3 << 11)
765 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
766 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
767 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
768 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
769 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
770 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
771 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
772 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
773 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
774 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
775 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
776 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
777 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
778 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
779 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
780 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (1 << 24) /*!< 24: Inactive */
781 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
783 #define SIP_PAGE2_FLAGS_TO_COPY \
784 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE)
786 /* SIP packet flags */
787 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
788 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
789 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
791 /* T.38 set of flags */
792 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
793 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
794 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
795 /* Rate management */
796 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
797 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
798 /* UDP Error correction */
799 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
800 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
801 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
802 /* T38 Spec version */
803 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
804 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
805 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
806 /* Maximum Fax Rate */
807 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
808 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
809 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
810 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
811 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
812 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
814 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
815 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
817 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
818 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
819 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
821 /*! \brief T38 States for a call */
823 T38_DISABLED = 0, /*!< Not enabled */
824 T38_LOCAL_DIRECT, /*!< Offered from local */
825 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
826 T38_PEER_DIRECT, /*!< Offered from peer */
827 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
828 T38_ENABLED /*!< Negotiated (enabled) */
831 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
832 struct t38properties {
833 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
834 int capability; /*!< Our T38 capability */
835 int peercapability; /*!< Peers T38 capability */
836 int jointcapability; /*!< Supported T38 capability at both ends */
837 enum t38state state; /*!< T.38 state */
840 /*! \brief Parameters to know status of transfer */
842 REFER_IDLE, /*!< No REFER is in progress */
843 REFER_SENT, /*!< Sent REFER to transferee */
844 REFER_RECEIVED, /*!< Received REFER from transferrer */
845 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
846 REFER_ACCEPTED, /*!< Accepted by transferee */
847 REFER_RINGING, /*!< Target Ringing */
848 REFER_200OK, /*!< Answered by transfer target */
849 REFER_FAILED, /*!< REFER declined - go on */
850 REFER_NOAUTH /*!< We had no auth for REFER */
853 static const struct c_referstatusstring {
854 enum referstatus status;
856 } referstatusstrings[] = {
857 { REFER_IDLE, "<none>" },
858 { REFER_SENT, "Request sent" },
859 { REFER_RECEIVED, "Request received" },
860 { REFER_ACCEPTED, "Accepted" },
861 { REFER_RINGING, "Target ringing" },
862 { REFER_200OK, "Done" },
863 { REFER_FAILED, "Failed" },
864 { REFER_NOAUTH, "Failed - auth failure" }
867 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
868 /* OEJ: Should be moved to string fields */
870 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
871 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
872 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
873 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
874 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
875 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
876 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
877 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
878 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
879 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
880 struct sip_pvt *refer_call; /*!< Call we are referring */
881 int attendedtransfer; /*!< Attended or blind transfer? */
882 int localtransfer; /*!< Transfer to local domain? */
883 enum referstatus status; /*!< REFER status */
886 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
888 ast_mutex_t pvt_lock; /*!< Dialog private lock */
889 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
890 int method; /*!< SIP method that opened this dialog */
891 AST_DECLARE_STRING_FIELDS(
892 AST_STRING_FIELD(callid); /*!< Global CallID */
893 AST_STRING_FIELD(randdata); /*!< Random data */
894 AST_STRING_FIELD(accountcode); /*!< Account code */
895 AST_STRING_FIELD(realm); /*!< Authorization realm */
896 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
897 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
898 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
899 AST_STRING_FIELD(domain); /*!< Authorization domain */
900 AST_STRING_FIELD(from); /*!< The From: header */
901 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
902 AST_STRING_FIELD(exten); /*!< Extension where to start */
903 AST_STRING_FIELD(context); /*!< Context for this call */
904 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
905 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
906 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
907 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
908 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
909 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
910 AST_STRING_FIELD(language); /*!< Default language for this call */
911 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
912 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
913 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
914 AST_STRING_FIELD(redircause); /*!< Referring cause */
915 AST_STRING_FIELD(theirtag); /*!< Their tag */
916 AST_STRING_FIELD(username); /*!< [user] name */
917 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
918 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
919 AST_STRING_FIELD(uri); /*!< Original requested URI */
920 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
921 AST_STRING_FIELD(peersecret); /*!< Password */
922 AST_STRING_FIELD(peermd5secret);
923 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
924 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
925 AST_STRING_FIELD(via); /*!< Via: header */
926 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
927 /* we only store the part in <brackets> in this field. */
928 AST_STRING_FIELD(our_contact); /*!< Our contact header */
929 AST_STRING_FIELD(rpid); /*!< Our RPID header */
930 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
932 unsigned int ocseq; /*!< Current outgoing seqno */
933 unsigned int icseq; /*!< Current incoming seqno */
934 ast_group_t callgroup; /*!< Call group */
935 ast_group_t pickupgroup; /*!< Pickup group */
936 int lastinvite; /*!< Last Cseq of invite */
937 struct ast_flags flags[2]; /*!< SIP_ flags */
938 int timer_t1; /*!< SIP timer T1, ms rtt */
939 unsigned int sipoptions; /*!< Supported SIP options on the other end */
940 struct ast_codec_pref prefs; /*!< codec prefs */
941 int capability; /*!< Special capability (codec) */
942 int jointcapability; /*!< Supported capability at both ends (codecs) */
943 int peercapability; /*!< Supported peer capability */
944 int prefcodec; /*!< Preferred codec (outbound only) */
945 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
946 int redircodecs; /*!< Redirect codecs */
947 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
948 struct t38properties t38; /*!< T38 settings */
949 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
950 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
951 int callingpres; /*!< Calling presentation */
952 int authtries; /*!< Times we've tried to authenticate */
953 int expiry; /*!< How long we take to expire */
954 long branch; /*!< The branch identifier of this session */
955 char tag[11]; /*!< Our tag for this session */
956 int sessionid; /*!< SDP Session ID */
957 int sessionversion; /*!< SDP Session Version */
958 struct sockaddr_in sa; /*!< Our peer */
959 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
960 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
961 time_t lastrtprx; /*!< Last RTP received */
962 time_t lastrtptx; /*!< Last RTP sent */
963 int rtptimeout; /*!< RTP timeout time */
964 struct sockaddr_in recv; /*!< Received as */
965 struct in_addr ourip; /*!< Our IP */
966 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
967 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
968 int route_persistant; /*!< Is this the "real" route? */
969 struct sip_auth *peerauth; /*!< Realm authentication */
970 int noncecount; /*!< Nonce-count */
971 char lastmsg[256]; /*!< Last Message sent/received */
972 int amaflags; /*!< AMA Flags */
973 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
974 struct sip_request initreq; /*!< Latest request that opened a new transaction
976 NOT the request that opened the dialog
979 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
980 int autokillid; /*!< Auto-kill ID (scheduler) */
981 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
982 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
983 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
984 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
985 int laststate; /*!< SUBSCRIBE: Last known extension state */
986 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
988 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
990 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
991 Used in peerpoke, mwi subscriptions */
992 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
993 struct ast_rtp *rtp; /*!< RTP Session */
994 struct ast_rtp *vrtp; /*!< Video RTP session */
995 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
996 struct sip_history_head *history; /*!< History of this SIP dialog */
997 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
998 struct sip_pvt *next; /*!< Next dialog in chain */
999 struct sip_invite_param *options; /*!< Options for INVITE */
1000 int autoframing; /*!< The number of Asters we group in a Pyroflax
1001 before strolling to the Grokyzpå
1002 (A bit unsure of this, please correct if
1006 static struct sip_pvt *dialoglist = NULL;
1008 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1009 AST_MUTEX_DEFINE_STATIC(dialoglock);
1011 /*! \brief hide the way the list is locked/unlocked */
1012 static void dialoglist_lock(void)
1014 ast_mutex_lock(&dialoglock);
1017 static void dialoglist_unlock(void)
1019 ast_mutex_unlock(&dialoglock);
1022 #define FLAG_RESPONSE (1 << 0)
1023 #define FLAG_FATAL (1 << 1)
1025 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1027 struct sip_pkt *next; /*!< Next packet in linked list */
1028 int retrans; /*!< Retransmission number */
1029 int method; /*!< SIP method for this packet */
1030 int seqno; /*!< Sequence number */
1031 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1032 struct sip_pvt *owner; /*!< Owner AST call */
1033 int retransid; /*!< Retransmission ID */
1034 int timer_a; /*!< SIP timer A, retransmission timer */
1035 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1036 int packetlen; /*!< Length of packet */
1040 /*! \brief Structure for SIP user data. User's place calls to us */
1042 /* Users who can access various contexts */
1043 ASTOBJ_COMPONENTS(struct sip_user);
1044 char secret[80]; /*!< Password */
1045 char md5secret[80]; /*!< Password in md5 */
1046 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1047 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1048 char cid_num[80]; /*!< Caller ID num */
1049 char cid_name[80]; /*!< Caller ID name */
1050 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1051 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1052 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1053 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1054 char useragent[256]; /*!< User agent in SIP request */
1055 struct ast_codec_pref prefs; /*!< codec prefs */
1056 ast_group_t callgroup; /*!< Call group */
1057 ast_group_t pickupgroup; /*!< Pickup Group */
1058 unsigned int sipoptions; /*!< Supported SIP options */
1059 struct ast_flags flags[2]; /*!< SIP_ flags */
1060 int amaflags; /*!< AMA flags for billing */
1061 int callingpres; /*!< Calling id presentation */
1062 int capability; /*!< Codec capability */
1063 int inUse; /*!< Number of calls in use */
1064 int call_limit; /*!< Limit of concurrent calls */
1065 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1066 struct ast_ha *ha; /*!< ACL setting */
1067 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1068 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1072 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1073 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1075 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1076 /*!< peer->name is the unique name of this object */
1077 char secret[80]; /*!< Password */
1078 char md5secret[80]; /*!< Password in MD5 */
1079 struct sip_auth *auth; /*!< Realm authentication list */
1080 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1081 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1082 char username[80]; /*!< Temporary username until registration */
1083 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1084 int amaflags; /*!< AMA Flags (for billing) */
1085 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1086 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1087 char fromuser[80]; /*!< From: user when calling this peer */
1088 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1089 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1090 char cid_num[80]; /*!< Caller ID num */
1091 char cid_name[80]; /*!< Caller ID name */
1092 int callingpres; /*!< Calling id presentation */
1093 int inUse; /*!< Number of calls in use */
1094 int inRinging; /*!< Number of calls ringing */
1095 int onHold; /*!< Peer has someone on hold */
1096 int call_limit; /*!< Limit of concurrent calls */
1097 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1098 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1099 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1100 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1101 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1102 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1103 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1104 struct ast_codec_pref prefs; /*!< codec prefs */
1106 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1107 unsigned int sipoptions; /*!< Supported SIP options */
1108 struct ast_flags flags[2]; /*!< SIP_ flags */
1109 int expire; /*!< When to expire this peer registration */
1110 int capability; /*!< Codec capability */
1111 int rtptimeout; /*!< RTP timeout */
1112 int rtpholdtimeout; /*!< RTP Hold Timeout */
1113 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1114 ast_group_t callgroup; /*!< Call group */
1115 ast_group_t pickupgroup; /*!< Pickup group */
1116 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1117 struct sockaddr_in addr; /*!< IP address of peer */
1118 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1121 struct sip_pvt *call; /*!< Call pointer */
1122 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1123 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1124 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1125 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1126 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1127 struct ast_ha *ha; /*!< Access control list */
1128 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1129 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1136 /*! \brief Registrations with other SIP proxies */
1137 struct sip_registry {
1138 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1139 AST_DECLARE_STRING_FIELDS(
1140 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1141 AST_STRING_FIELD(realm); /*!< Authorization realm */
1142 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1143 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1144 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1145 AST_STRING_FIELD(domain); /*!< Authorization domain */
1146 AST_STRING_FIELD(username); /*!< Who we are registering as */
1147 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1148 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1149 AST_STRING_FIELD(secret); /*!< Password in clear text */
1150 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1151 AST_STRING_FIELD(callback); /*!< Contact extension */
1152 AST_STRING_FIELD(random);
1154 int portno; /*!< Optional port override */
1155 int expire; /*!< Sched ID of expiration */
1156 int expiry; /*!< Value to use for the Expires header */
1157 int regattempts; /*!< Number of attempts (since the last success) */
1158 int timeout; /*!< sched id of sip_reg_timeout */
1159 int refresh; /*!< How often to refresh */
1160 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1161 enum sipregistrystate regstate; /*!< Registration state (see above) */
1162 time_t regtime; /*!< Last successful registration time */
1163 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1164 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1165 struct sockaddr_in us; /*!< Who the server thinks we are */
1166 int noncecount; /*!< Nonce-count */
1167 char lastmsg[256]; /*!< Last Message sent/received */
1170 /* --- Linked lists of various objects --------*/
1172 /*! \brief The user list: Users and friends */
1173 static struct ast_user_list {
1174 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1177 /*! \brief The peer list: Peers and Friends */
1178 static struct ast_peer_list {
1179 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1182 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1183 static struct ast_register_list {
1184 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1188 static int temp_pvt_init(void *);
1189 static void temp_pvt_cleanup(void *);
1191 /*! \brief A per-thread temporary pvt structure */
1192 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1194 /*! \todo Move the sip_auth list to AST_LIST */
1195 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1198 /* --- Sockets and networking --------------*/
1199 static int sipsock = -1; /*!< Main socket for SIP network communication */
1200 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1201 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1202 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1203 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1204 static int externrefresh = 10;
1205 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1206 static struct in_addr __ourip;
1207 static struct sockaddr_in outboundproxyip;
1209 static struct sockaddr_in debugaddr;
1211 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1213 /*---------------------------- Forward declarations of functions in chan_sip.c */
1214 /*! \note This is added to help splitting up chan_sip.c into several files
1215 in coming releases */
1217 /*--- PBX interface functions */
1218 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1219 static int sip_devicestate(void *data);
1220 static int sip_sendtext(struct ast_channel *ast, const char *text);
1221 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1222 static int sip_hangup(struct ast_channel *ast);
1223 static int sip_answer(struct ast_channel *ast);
1224 static struct ast_frame *sip_read(struct ast_channel *ast);
1225 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1226 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1227 static int sip_transfer(struct ast_channel *ast, const char *dest);
1228 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1229 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1230 static int sip_senddigit_end(struct ast_channel *ast, char digit);
1232 /*--- Transmitting responses and requests */
1233 static int sipsock_read(int *id, int fd, short events, void *ignore);
1234 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1235 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1236 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1237 static int retrans_pkt(void *data);
1238 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1239 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);
1240 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1241 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1242 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1243 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1244 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1245 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);
1246 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1247 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1248 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1249 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1250 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1251 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1252 static int transmit_info_with_digit(struct sip_pvt *p, const char digit);
1253 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1254 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1255 static int transmit_refer(struct sip_pvt *p, const char *dest);
1256 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1257 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1258 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1259 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1260 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1261 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1262 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1263 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1264 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1265 static int does_peer_need_mwi(struct sip_peer *peer);
1267 /*--- Dialog management */
1268 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1269 int useglobal_nat, const int intended_method);
1270 static int __sip_autodestruct(void *data);
1271 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1272 static void sip_cancel_destroy(struct sip_pvt *p);
1273 static void sip_destroy(struct sip_pvt *p);
1274 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1275 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1276 static void __sip_pretend_ack(struct sip_pvt *p);
1277 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1278 static int auto_congest(void *nothing);
1279 static int update_call_counter(struct sip_pvt *fup, int event);
1280 static int hangup_sip2cause(int cause);
1281 static const char *hangup_cause2sip(int cause);
1282 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1283 static void free_old_route(struct sip_route *route);
1284 static void list_route(struct sip_route *route);
1285 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1286 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1287 struct sip_request *req, char *uri);
1288 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1289 static void check_pendings(struct sip_pvt *p);
1290 static void *sip_park_thread(void *stuff);
1291 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1292 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1294 /*--- Codec handling / SDP */
1295 static void try_suggested_sip_codec(struct sip_pvt *p);
1296 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1297 static const char *get_sdp(struct sip_request *req, const char *name);
1298 static int find_sdp(struct sip_request *req);
1299 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1300 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1301 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1302 int debug, int *min_packet_size);
1303 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1304 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1306 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1307 static void do_setnat(struct sip_pvt *p, int natflags);
1309 /*--- Authentication stuff */
1310 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1311 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1312 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1313 const char *secret, const char *md5secret, int sipmethod,
1314 char *uri, enum xmittype reliable, int ignore);
1315 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1316 int sipmethod, char *uri, enum xmittype reliable,
1317 struct sockaddr_in *sin, struct sip_peer **authpeer);
1318 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1320 /*--- Domain handling */
1321 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1322 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1323 static void clear_sip_domains(void);
1325 /*--- SIP realm authentication */
1326 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1327 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1328 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1330 /*--- Misc functions */
1331 static int sip_do_reload(enum channelreloadreason reason);
1332 static int reload_config(enum channelreloadreason reason);
1333 static int expire_register(void *data);
1334 static void *do_monitor(void *data);
1335 static int restart_monitor(void);
1336 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1337 static void sip_destroy(struct sip_pvt *p);
1338 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1339 static int sip_refer_allocate(struct sip_pvt *p);
1340 static void ast_quiet_chan(struct ast_channel *chan);
1341 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1343 /*--- Device monitoring and Device/extension state handling */
1344 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1345 static int sip_devicestate(void *data);
1346 static int sip_poke_noanswer(void *data);
1347 static int sip_poke_peer(struct sip_peer *peer);
1348 static void sip_poke_all_peers(void);
1349 static void sip_peer_hold(struct sip_pvt *p, int hold);
1351 /*--- Applications, functions, CLI and manager command helpers */
1352 static const char *sip_nat_mode(const struct sip_pvt *p);
1353 static int sip_show_inuse(int fd, int argc, char *argv[]);
1354 static char *transfermode2str(enum transfermodes mode) attribute_const;
1355 static char *nat2str(int nat) attribute_const;
1356 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1357 static int sip_show_users(int fd, int argc, char *argv[]);
1358 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
1359 static int manager_sip_show_peers( struct mansession *s, struct message *m );
1360 static int sip_show_peers(int fd, int argc, char *argv[]);
1361 static int sip_show_objects(int fd, int argc, char *argv[]);
1362 static void print_group(int fd, ast_group_t group, int crlf);
1363 static const char *dtmfmode2str(int mode) attribute_const;
1364 static const char *insecure2str(int port, int invite) attribute_const;
1365 static void cleanup_stale_contexts(char *new, char *old);
1366 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1367 static const char *domain_mode_to_text(const enum domain_mode mode);
1368 static int sip_show_domains(int fd, int argc, char *argv[]);
1369 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1370 static int manager_sip_show_peer( struct mansession *s, struct message *m);
1371 static int sip_show_peer(int fd, int argc, char *argv[]);
1372 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1373 static int sip_show_user(int fd, int argc, char *argv[]);
1374 static int sip_show_registry(int fd, int argc, char *argv[]);
1375 static int sip_show_settings(int fd, int argc, char *argv[]);
1376 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1377 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1378 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1379 static int sip_show_channels(int fd, int argc, char *argv[]);
1380 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1381 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1382 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1383 static char *complete_sip_peer(const char *word, int state, int flags2);
1384 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1385 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1386 static char *complete_sip_user(const char *word, int state, int flags2);
1387 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1388 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1389 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1390 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1391 static int sip_show_channel(int fd, int argc, char *argv[]);
1392 static int sip_show_history(int fd, int argc, char *argv[]);
1393 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1394 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1395 static int sip_do_debug(int fd, int argc, char *argv[]);
1396 static int sip_no_debug(int fd, int argc, char *argv[]);
1397 static int sip_notify(int fd, int argc, char *argv[]);
1398 static int sip_do_history(int fd, int argc, char *argv[]);
1399 static int sip_no_history(int fd, int argc, char *argv[]);
1400 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1401 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1402 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1403 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1404 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1405 static int sip_addheader(struct ast_channel *chan, void *data);
1406 static int sip_do_reload(enum channelreloadreason reason);
1407 static int sip_reload(int fd, int argc, char *argv[]);
1410 Functions for enabling debug per IP or fully, or enabling history logging for
1413 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1414 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1415 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1416 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1417 static void sip_dump_history(struct sip_pvt *dialog);
1419 /*--- Device object handling */
1420 static struct sip_peer *temp_peer(const char *name);
1421 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1422 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1423 static int update_call_counter(struct sip_pvt *fup, int event);
1424 static void sip_destroy_peer(struct sip_peer *peer);
1425 static void sip_destroy_user(struct sip_user *user);
1426 static int sip_poke_peer(struct sip_peer *peer);
1427 static void set_peer_defaults(struct sip_peer *peer);
1428 static struct sip_peer *temp_peer(const char *name);
1429 static void register_peer_exten(struct sip_peer *peer, int onoff);
1430 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1431 static struct sip_user *find_user(const char *name, int realtime);
1432 static int sip_poke_peer_s(void *data);
1433 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1434 static void reg_source_db(struct sip_peer *peer);
1435 static void destroy_association(struct sip_peer *peer);
1436 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1438 /* Realtime device support */
1439 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1440 static struct sip_user *realtime_user(const char *username);
1441 static void update_peer(struct sip_peer *p, int expiry);
1442 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1443 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1445 /*--- Internal UA client handling (outbound registrations) */
1446 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1447 static void sip_registry_destroy(struct sip_registry *reg);
1448 static int sip_register(char *value, int lineno);
1449 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1450 static int sip_reregister(void *data);
1451 static int __sip_do_register(struct sip_registry *r);
1452 static int sip_reg_timeout(void *data);
1453 static void sip_send_all_registers(void);
1455 /*--- Parsing SIP requests and responses */
1456 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1457 static int determine_firstline_parts(struct sip_request *req);
1458 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1459 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1460 static int find_sip_method(const char *msg);
1461 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1462 static void parse_request(struct sip_request *req);
1463 static const char *get_header(const struct sip_request *req, const char *name);
1464 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1465 static int method_match(enum sipmethod id, const char *name);
1466 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1467 static char *get_in_brackets(char *tmp);
1468 static const char *find_alias(const char *name, const char *_default);
1469 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1470 static int lws2sws(char *msgbuf, int len);
1471 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1472 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1473 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1474 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1475 static int set_address_from_contact(struct sip_pvt *pvt);
1476 static void check_via(struct sip_pvt *p, struct sip_request *req);
1477 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1478 static int get_rpid_num(const char *input, char *output, int maxlen);
1479 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1480 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1481 static int get_msg_text(char *buf, int len, struct sip_request *req);
1482 static void free_old_route(struct sip_route *route);
1483 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1485 /*--- Constructing requests and responses */
1486 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1487 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1488 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1489 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1490 static int init_resp(struct sip_request *resp, const char *msg);
1491 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1492 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1493 static void build_via(struct sip_pvt *p);
1494 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1495 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1496 static char *generate_random_string(char *buf, size_t size);
1497 static void build_callid_pvt(struct sip_pvt *pvt);
1498 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1499 static void make_our_tag(char *tagbuf, size_t len);
1500 static int add_header(struct sip_request *req, const char *var, const char *value);
1501 static int add_header_contentLength(struct sip_request *req, int len);
1502 static int add_line(struct sip_request *req, const char *line);
1503 static int add_text(struct sip_request *req, const char *text);
1504 static int add_digit(struct sip_request *req, char digit);
1505 static int add_vidupdate(struct sip_request *req);
1506 static void add_route(struct sip_request *req, struct sip_route *route);
1507 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1508 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1509 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1510 static void set_destination(struct sip_pvt *p, char *uri);
1511 static void append_date(struct sip_request *req);
1512 static void build_contact(struct sip_pvt *p);
1513 static void build_rpid(struct sip_pvt *p);
1515 /*------Request handling functions */
1516 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1517 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);
1518 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1519 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1520 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1521 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1522 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1523 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1524 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1525 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1526 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1527 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1528 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1529 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1531 /*------Response handling functions */
1532 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1533 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1534 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1535 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1537 /*----- RTP interface functions */
1538 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1539 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1540 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1541 static int sip_get_codec(struct ast_channel *chan);
1542 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1544 /*------ T38 Support --------- */
1545 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1546 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1547 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1548 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1550 /*! \brief Definition of this channel for PBX channel registration */
1551 static const struct ast_channel_tech sip_tech = {
1553 .description = "Session Initiation Protocol (SIP)",
1554 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1555 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1556 .requester = sip_request_call,
1557 .devicestate = sip_devicestate,
1559 .hangup = sip_hangup,
1560 .answer = sip_answer,
1563 .write_video = sip_write,
1564 .indicate = sip_indicate,
1565 .transfer = sip_transfer,
1567 .send_digit_begin = sip_senddigit_begin,
1568 .send_digit_end = sip_senddigit_end,
1569 .bridge = ast_rtp_bridge,
1570 .early_bridge = ast_rtp_early_bridge,
1571 .send_text = sip_sendtext,
1574 /**--- some list management macros. **/
1576 #define UNLINK(element, head, prev) do { \
1578 (prev)->next = (element)->next; \
1580 (head) = (element)->next; \
1583 /*! \brief Interface structure with callbacks used to connect to RTP module */
1584 static struct ast_rtp_protocol sip_rtp = {
1586 get_rtp_info: sip_get_rtp_peer,
1587 get_vrtp_info: sip_get_vrtp_peer,
1588 set_rtp_peer: sip_set_rtp_peer,
1589 get_codec: sip_get_codec,
1592 /*! \brief Helper function to lock, hiding the underlying locking mechanism. */
1593 static void sip_pvt_lock(struct sip_pvt *pvt)
1595 ast_mutex_lock(&pvt->pvt_lock);
1598 /*! \brief Helper function to unlock pvt, hiding the underlying locking mechanism. */
1599 static void sip_pvt_unlock(struct sip_pvt *pvt)
1601 ast_mutex_unlock(&pvt->pvt_lock);
1605 * helper functions to unreference various types of objects.
1606 * By handling them this way, we don't have to declare the
1607 * destructor on each call, which removes the chance of errors.
1609 static void unref_peer(struct sip_peer *peer)
1611 ASTOBJ_UNREF(peer, sip_destroy_peer);
1614 static void unref_user(struct sip_user *user)
1616 ASTOBJ_UNREF(user, sip_destroy_user);
1619 static void unref_registry(struct sip_registry *reg)
1621 ASTOBJ_UNREF(reg, sip_registry_destroy);
1624 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1625 static struct ast_udptl_protocol sip_udptl = {
1627 get_udptl_info: sip_get_udptl_peer,
1628 set_udptl_peer: sip_set_udptl_peer,
1631 /*! \brief Convert transfer status to string */
1632 static const char *referstatus2str(enum referstatus rstatus)
1634 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1637 for (x = 0; x < i; x++) {
1638 if (referstatusstrings[x].status == rstatus)
1639 return referstatusstrings[x].text;
1644 /*! \brief Initialize the initital request packet in the pvt structure.
1645 This packet is used for creating replies and future requests in
1647 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1650 if (p->initreq.headers)
1651 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1653 ast_log(LOG_DEBUG, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1655 /* Use this as the basis */
1656 copy_request(&p->initreq, req);
1657 parse_request(&p->initreq);
1658 if (ast_test_flag(req, SIP_PKT_DEBUG))
1659 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1662 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1663 static void sip_alreadygone(struct sip_pvt *dialog)
1665 if (option_debug > 2)
1666 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1667 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1671 /*! \brief returns true if 'name' (with optional trailing whitespace)
1672 * matches the sip method 'id'.
1673 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1674 * a case-insensitive comparison to be more tolerant.
1675 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1677 static int method_match(enum sipmethod id, const char *name)
1679 int len = strlen(sip_methods[id].text);
1680 int l_name = name ? strlen(name) : 0;
1681 /* true if the string is long enough, and ends with whitespace, and matches */
1682 return (l_name >= len && name[len] < 33 &&
1683 !strncasecmp(sip_methods[id].text, name, len));
1686 /*! \brief find_sip_method: Find SIP method from header */
1687 static int find_sip_method(const char *msg)
1691 if (ast_strlen_zero(msg))
1693 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1694 if (method_match(i, msg))
1695 res = sip_methods[i].id;
1700 /*! \brief Parse supported header in incoming packet */
1701 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1705 unsigned int profile = 0;
1708 if (ast_strlen_zero(supported) )
1710 temp = ast_strdupa(supported);
1712 if (option_debug > 2 && sipdebug)
1713 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1715 for (next = temp; next; next = sep) {
1717 if ( (sep = strchr(next, ',')) != NULL)
1719 next = ast_skip_blanks(next);
1720 if (option_debug > 2 && sipdebug)
1721 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1722 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1723 if (!strcasecmp(next, sip_options[i].text)) {
1724 profile |= sip_options[i].id;
1726 if (option_debug > 2 && sipdebug)
1727 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1731 if (!found && option_debug > 2 && sipdebug) {
1732 if (!strncasecmp(next, "x-", 2))
1733 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1735 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1740 pvt->sipoptions = profile;
1744 /*! \brief See if we pass debug IP filter */
1745 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1749 if (debugaddr.sin_addr.s_addr) {
1750 if (((ntohs(debugaddr.sin_port) != 0)
1751 && (debugaddr.sin_port != addr->sin_port))
1752 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1758 /*! \brief The real destination address for a write */
1759 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1761 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1764 /*! \brief Display SIP nat mode */
1765 static const char *sip_nat_mode(const struct sip_pvt *p)
1767 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1770 /*! \brief Test PVT for debugging output */
1771 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1775 return sip_debug_test_addr(sip_real_dst(p));
1778 /*! \brief Transmit SIP message */
1779 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1782 const struct sockaddr_in *dst = sip_real_dst(p);
1783 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1786 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));
1791 /*! \brief Build a Via header for a request */
1792 static void build_via(struct sip_pvt *p)
1794 /* Work around buggy UNIDEN UIP200 firmware */
1795 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1797 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1798 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1799 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1802 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1804 * Using the localaddr structure built up with localnet statements in sip.conf
1805 * apply it to their address to see if we need to substitute our
1806 * externip or can get away with our internal bindaddr
1808 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1810 struct sockaddr_in theirs, ours;
1812 /* Get our local information */
1813 ast_ouraddrfor(them, us);
1814 theirs.sin_addr = *them;
1815 ours.sin_addr = *us;
1817 if (localaddr && externip.sin_addr.s_addr &&
1818 ast_apply_ha(localaddr, &theirs) &&
1819 !ast_apply_ha(localaddr, &ours)) {
1820 if (externexpire && time(NULL) >= externexpire) {
1821 struct ast_hostent ahp;
1824 externexpire = time(NULL) + externrefresh;
1825 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1826 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1828 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1830 *us = externip.sin_addr;
1832 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1833 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1835 } else if (bindaddr.sin_addr.s_addr)
1836 *us = bindaddr.sin_addr;
1840 /*! \brief Append to SIP dialog history
1841 \return Always returns 0 */
1842 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1844 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1845 __attribute__ ((format (printf, 2, 3)));
1847 /*! \brief Append to SIP dialog history with arg list */
1848 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1850 char buf[80], *c = buf; /* max history length */
1851 struct sip_history *hist;
1854 vsnprintf(buf, sizeof(buf), fmt, ap);
1855 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1856 l = strlen(buf) + 1;
1857 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1859 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1863 memcpy(hist->event, buf, l);
1864 AST_LIST_INSERT_TAIL(p->history, hist, list);
1867 /*! \brief Append to SIP dialog history with arg list */
1868 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1875 append_history_va(p, fmt, ap);
1881 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1882 static int retrans_pkt(void *data)
1884 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1885 int reschedule = DEFAULT_RETRANS;
1887 /* Lock channel PVT */
1888 sip_pvt_lock(pkt->owner);
1890 if (pkt->retrans < MAX_RETRANS) {
1892 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1893 if (sipdebug && option_debug > 3)
1894 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);
1898 if (sipdebug && option_debug > 3)
1899 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1903 pkt->timer_a = 2 * pkt->timer_a;
1905 /* For non-invites, a maximum of 4 secs */
1906 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1907 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1910 /* Reschedule re-transmit */
1911 reschedule = siptimer_a;
1912 if (option_debug > 3)
1913 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);
1916 if (sip_debug_test_pvt(pkt->owner)) {
1917 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1918 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1919 pkt->retrans, sip_nat_mode(pkt->owner),
1920 ast_inet_ntoa(dst->sin_addr),
1921 ntohs(dst->sin_port), pkt->data);
1924 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1925 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1926 sip_pvt_unlock(pkt->owner);
1929 /* Too many retries */
1930 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1931 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1932 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");
1934 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1935 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1937 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1939 pkt->retransid = -1;
1941 if (ast_test_flag(pkt, FLAG_FATAL)) {
1942 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1943 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
1945 sip_pvt_lock(pkt->owner);
1947 if (pkt->owner->owner) {
1948 sip_alreadygone(pkt->owner);
1949 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1950 ast_queue_hangup(pkt->owner->owner);
1951 ast_channel_unlock(pkt->owner->owner);
1953 /* If no channel owner, destroy now */
1955 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1956 if (pkt->method != SIP_OPTIONS)
1957 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1960 /* Remove the packet */
1961 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1963 UNLINK(cur, pkt->owner->packets, prev);
1964 sip_pvt_unlock(pkt->owner);
1970 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1971 sip_pvt_unlock(pkt->owner);
1975 /*! \brief Transmit packet with retransmits
1976 \return 0 on success, -1 on failure to allocate packet
1978 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1980 struct sip_pkt *pkt;
1981 int siptimer_a = DEFAULT_RETRANS;
1983 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1985 memcpy(pkt->data, data, len);
1986 pkt->method = sipmethod;
1987 pkt->packetlen = len;
1988 pkt->next = p->packets;
1992 ast_set_flag(pkt, FLAG_RESPONSE);
1993 pkt->data[len] = '\0';
1994 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1996 ast_set_flag(pkt, FLAG_FATAL);
1998 siptimer_a = pkt->timer_t1 * 2;
2000 /* Schedule retransmission */
2001 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2002 if (option_debug > 3 && sipdebug)
2003 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
2004 pkt->next = p->packets;
2007 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
2008 if (sipmethod == SIP_INVITE) {
2009 /* Note this is a pending invite */
2010 p->pendinginvite = seqno;
2015 /*! \brief Kill a SIP dialog (called by scheduler) */
2016 static int __sip_autodestruct(void *data)
2018 struct sip_pvt *p = data;
2020 /* If this is a subscription, tell the phone that we got a timeout */
2021 if (p->subscribed) {
2022 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
2023 p->subscribed = NONE;
2024 append_history(p, "Subscribestatus", "timeout");
2025 if (option_debug > 2)
2026 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2027 return 10000; /* Reschedule this destruction so that we know that it's gone */
2030 if (p->subscribed == MWI_NOTIFICATION)
2032 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2034 /* Reset schedule ID */
2038 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2039 ast_queue_hangup(p->owner);
2040 } else if (p->refer) {
2041 if (option_debug > 2)
2042 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2043 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2044 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2045 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2047 append_history(p, "AutoDestroy", "%s", p->callid);
2049 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2050 sip_destroy(p); /* Go ahead and destroy dialog. All attempts to recover is done */
2055 /*! \brief Schedule destruction of SIP dialog */
2056 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2059 if (p->timer_t1 == 0)
2060 p->timer_t1 = SIP_TIMER_T1; /* Set timer T1 if not set (RFC 3261) */
2061 ms = p->timer_t1 * 64;
2063 if (sip_debug_test_pvt(p))
2064 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2065 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2066 append_history(p, "SchedDestroy", "%d ms", ms);
2068 if (p->autokillid > -1)
2069 ast_sched_del(sched, p->autokillid);
2070 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2073 /*! \brief Cancel destruction of SIP dialog */
2074 static void sip_cancel_destroy(struct sip_pvt *p)
2076 if (p->autokillid > -1) {
2077 ast_sched_del(sched, p->autokillid);
2078 append_history(p, "CancelDestroy", "");
2083 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2084 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2086 struct sip_pkt *cur, *prev = NULL;
2087 const char *msg = "Not Found"; /* used only for debugging */
2090 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2091 if (cur->seqno != seqno || ast_test_flag(cur, FLAG_RESPONSE) != resp)
2093 if (ast_test_flag(cur, FLAG_RESPONSE) || cur->method == sipmethod) {
2095 if (!resp && (seqno == p->pendinginvite)) {
2097 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2098 p->pendinginvite = 0;
2100 if (cur->retransid > -1) {
2101 if (sipdebug && option_debug > 3)
2102 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2103 ast_sched_del(sched, cur->retransid);
2104 cur->retransid = -1;
2106 UNLINK(cur, p->packets, prev);
2113 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2114 p->callid, resp ? "Response" : "Request", seqno, msg);
2117 /*! \brief Pretend to ack all packets
2118 * maybe the lock on p is not strictly necessary but there might be a race */
2119 static void __sip_pretend_ack(struct sip_pvt *p)
2121 struct sip_pkt *cur = NULL;
2123 while (p->packets) {
2125 if (cur == p->packets) {
2126 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2130 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2131 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2135 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2136 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2138 struct sip_pkt *cur;
2141 for (cur = p->packets; cur; cur = cur->next) {
2142 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2143 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2144 /* this is our baby */
2145 if (cur->retransid > -1) {
2146 if (option_debug > 3 && sipdebug)
2147 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2148 ast_sched_del(sched, cur->retransid);
2149 cur->retransid = -1;
2156 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");
2161 /*! \brief Copy SIP request, parse it */
2162 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2164 memset(dst, 0, sizeof(*dst));
2165 memcpy(dst->data, src->data, sizeof(dst->data));
2166 dst->len = src->len;
2170 /*! \brief add a blank line if no body */
2171 static void add_blank(struct sip_request *req)
2174 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2175 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2176 req->len += strlen(req->data + req->len);
2180 /*! \brief Transmit response on SIP request*/
2181 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2186 if (sip_debug_test_pvt(p)) {
2187 const struct sockaddr_in *dst = sip_real_dst(p);
2189 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2190 reliable ? "Reliably " : "", sip_nat_mode(p),
2191 ast_inet_ntoa(dst->sin_addr),
2192 ntohs(dst->sin_port), req->data);
2194 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2195 struct sip_request tmp;
2196 parse_copy(&tmp, req);
2197 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2198 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2201 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2202 __sip_xmit(p, req->data, req->len);
2208 /*! \brief Send SIP Request to the other part of the dialogue */
2209 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2214 if (sip_debug_test_pvt(p)) {
2215 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2216 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);
2218 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);
2220 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2221 struct sip_request tmp;
2222 parse_copy(&tmp, req);
2223 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2226 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2227 __sip_xmit(p, req->data, req->len);
2231 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2232 * optionally with a limit on the search.
2233 * start must be past the first quote.
2235 static const char *find_closing_quote(const char *start, const char *lim)
2237 char last_char = '\0';
2239 for (s = start; *s && s != lim; last_char = *s++) {
2240 if (*s == '"' && last_char != '\\')
2246 /*! \brief Pick out text in brackets from character string
2247 \return pointer to terminated stripped string
2248 \param tmp input string that will be modified
2251 "foo" <bar> valid input, returns bar
2252 foo returns the whole string
2253 < "foo ... > returns the string between brackets
2254 < "foo... bogus (missing closing bracket), returns the whole string
2255 XXX maybe should still skip the opening bracket
2257 static char *get_in_brackets(char *tmp)
2259 const char *parse = tmp;
2260 char *first_bracket;
2263 * Skip any quoted text until we find the part in brackets.
2264 * On any error give up and return the full string.
2266 while ( (first_bracket = strchr(parse, '<')) ) {
2267 char *first_quote = strchr(parse, '"');
2269 if (!first_quote || first_quote > first_bracket)
2270 break; /* no need to look at quoted part */
2271 /* the bracket is within quotes, so ignore it */
2272 parse = find_closing_quote(first_quote + 1, NULL);
2273 if (!*parse) { /* not found, return full string ? */
2274 /* XXX or be robust and return in-bracket part ? */
2275 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2280 if (first_bracket) {
2281 char *second_bracket = strchr(first_bracket + 1, '>');
2282 if (second_bracket) {
2283 *second_bracket = '\0';
2284 tmp = first_bracket + 1;
2286 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2293 * parses a URI in its components.
2294 * If scheme is specified, drop it from the top.
2295 * If a component is not requested, do not split around it.
2296 * This means that if we don't have domain, we cannot split
2297 * name:pass and domain:port.
2298 * It is safe to call with ret_name, pass, domain, port
2299 * pointing all to the same place.
2300 * Init pointers to empty string so we never get NULL dereferencing.
2301 * Overwrites the string.
2302 * return 0 on success, other values on error.
2304 static int parse_uri(char *uri, char *scheme,
2305 char **ret_name, char **pass, char **domain, char **port, char **options)
2310 /* init field as required */
2315 name = strsep(&uri, ";"); /* remove options */
2317 int l = strlen(scheme);
2318 if (!strncmp(name, scheme, l))
2321 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, name);
2326 /* if we don't want to split around domain, keep everything as a name,
2327 * so we need to do nothing here, except remember why.
2330 /* store the result in a temp. variable to avoid it being
2331 * overwritten if arguments point to the same place.
2335 if ((c = strchr(name, '@')) == NULL) {
2336 /* domain-only URI, according to the SIP RFC. */
2343 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2347 if (pass && (c = strchr(name, ':'))) { /* user:password */
2353 if (ret_name) /* same as for domain, store the result only at the end */
2356 *options = uri ? uri : "";
2361 /*! \brief Send SIP MESSAGE text within a call
2362 Called from PBX core sendtext() application */
2363 static int sip_sendtext(struct ast_channel *ast, const char *text)
2365 struct sip_pvt *p = ast->tech_pvt;
2366 int debug = sip_debug_test_pvt(p);
2369 ast_verbose("Sending text %s on %s\n", text, ast->name);
2372 if (ast_strlen_zero(text))
2375 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2376 transmit_message_with_text(p, text);
2380 /*! \brief Update peer object in realtime storage
2381 If the Asterisk system name is set in asterisk.conf, we will use
2382 that name and store that in the "regserver" field in the sippeers
2383 table to facilitate multi-server setups.
2385 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2388 char ipaddr[INET_ADDRSTRLEN];
2389 char regseconds[20];
2391 char *sysname = ast_config_AST_SYSTEM_NAME;
2392 char *syslabel = NULL;
2394 time_t nowtime = time(NULL) + expirey;
2395 const char *fc = fullcontact ? "fullcontact" : NULL;
2397 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2398 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2399 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2401 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2403 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2404 syslabel = "regserver";
2407 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2408 "port", port, "regseconds", regseconds,
2409 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2411 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2412 "port", port, "regseconds", regseconds,
2413 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2416 /*! \brief Automatically add peer extension to dial plan */
2417 static void register_peer_exten(struct sip_peer *peer, int onoff)
2420 char *stringp, *ext, *context;
2422 /* XXX note that global_regcontext is both a global 'enable' flag and
2423 * the name of the global regexten context, if not specified
2426 if (ast_strlen_zero(global_regcontext))
2429 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2431 while ((ext = strsep(&stringp, "&"))) {
2432 if ((context = strchr(ext, '@'))) {
2433 *context++ = '\0'; /* split ext@context */
2434 if (!ast_context_find(context)) {
2435 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2439 context = global_regcontext;
2442 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2443 ast_strdup(peer->name), ast_free, "SIP");
2445 ast_context_remove_extension(context, ext, 1, NULL);
2449 /*! \brief Destroy peer object from memory */
2450 static void sip_destroy_peer(struct sip_peer *peer)
2452 if (option_debug > 2)
2453 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2455 /* Delete it, it needs to disappear */
2457 sip_destroy(peer->call);
2459 if (peer->mwipvt) /* We have an active subscription, delete it */
2460 sip_destroy(peer->mwipvt);
2462 if (peer->chanvars) {
2463 ast_variables_destroy(peer->chanvars);
2464 peer->chanvars = NULL;
2466 if (peer->expire > -1)
2467 ast_sched_del(sched, peer->expire);
2469 if (peer->pokeexpire > -1)
2470 ast_sched_del(sched, peer->pokeexpire);
2471 register_peer_exten(peer, FALSE);
2472 ast_free_ha(peer->ha);
2473 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2475 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
2477 if (option_debug > 2)
2478 ast_log(LOG_DEBUG,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
2481 clear_realm_authentication(peer->auth);
2484 ast_dnsmgr_release(peer->dnsmgr);
2488 /*! \brief Update peer data in database (if used) */
2489 static void update_peer(struct sip_peer *p, int expiry)
2491 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2492 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2493 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2494 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2499 /*! \brief realtime_peer: Get peer from realtime storage
2500 * Checks the "sippeers" realtime family from extconfig.conf
2501 * \todo Consider adding check of port address when matching here to follow the same
2502 * algorithm as for static peers. Will we break anything by adding that?
2504 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2506 struct sip_peer *peer;
2507 struct ast_variable *var = NULL;
2508 struct ast_variable *tmp;
2509 char ipaddr[INET_ADDRSTRLEN];
2511 /* First check on peer name */
2513 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2514 else if (sin) { /* Then check on IP address for dynamic peers */
2515 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2516 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2518 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */
2524 for (tmp = var; tmp; tmp = tmp->next) {
2525 /* If this is type=user, then skip this object. */
2526 if (!strcasecmp(tmp->name, "type") &&
2527 !strcasecmp(tmp->value, "user")) {
2528 ast_variables_destroy(var);
2530 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2531 newpeername = tmp->value;
2535 if (!newpeername) { /* Did not find peer in realtime */
2536 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2537 ast_variables_destroy(var);
2542 /* Peer found in realtime, now build it in memory */
2543 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2545 ast_variables_destroy(var);
2549 if (option_debug > 2)
2550 ast_log(LOG_DEBUG,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
2552 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2554 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2555 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2556 if (peer->expire > -1) {
2557 ast_sched_del(sched, peer->expire);
2559 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2561 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2563 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2565 ast_variables_destroy(var);
2570 /*! \brief Support routine for find_peer */
2571 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2573 /* We know name is the first field, so we can cast */
2574 struct sip_peer *p = (struct sip_peer *) name;
2575 return !(!inaddrcmp(&p->addr, sin) ||
2576 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2577 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2580 /*! \brief Locate peer by name or ip address
2581 * This is used on incoming SIP message to find matching peer on ip
2582 or outgoing message to find matching peer on name */
2583 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2585 struct sip_peer *p = NULL;
2588 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2590 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2593 p = realtime_peer(peer, sin);
2598 /*! \brief Remove user object from in-memory storage */
2599 static void sip_destroy_user(struct sip_user *user)
2601 if (option_debug > 2)
2602 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2603 ast_free_ha(user->ha);
2604 if (user->chanvars) {
2605 ast_variables_destroy(user->chanvars);
2606 user->chanvars = NULL;
2608 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2615 /*! \brief Load user from realtime storage
2616 * Loads user from "sipusers" category in realtime (extconfig.conf)
2617 * Users are matched on From: user name (the domain in skipped) */
2618 static struct sip_user *realtime_user(const char *username)
2620 struct ast_variable *var;
2621 struct ast_variable *tmp;
2622 struct sip_user *user = NULL;
2624 var = ast_load_realtime("sipusers", "name", username, NULL);
2629 for (tmp = var; tmp; tmp = tmp->next) {
2630 if (!strcasecmp(tmp->name, "type") &&
2631 !strcasecmp(tmp->value, "peer")) {
2632 ast_variables_destroy(var);
2637 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2639 if (!user) { /* No user found */
2640 ast_variables_destroy(var);
2644 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2645 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2647 ASTOBJ_CONTAINER_LINK(&userl,user);
2649 /* Move counter from s to r... */
2652 ast_set_flag(&user->flags[0], SIP_REALTIME);
2654 ast_variables_destroy(var);
2658 /*! \brief Locate user by name
2659 * Locates user by name (From: sip uri user name part) first
2660 * from in-memory list (static configuration) then from
2661 * realtime storage (defined in extconfig.conf) */
2662 static struct sip_user *find_user(const char *name, int realtime)
2664 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2666 u = realtime_user(name);
2670 /*! \brief Set nat mode on the various data sockets */
2671 static void do_setnat(struct sip_pvt *p, int natflags)
2673 const char *mode = natflags ? "On" : "Off";
2677 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2678 ast_rtp_setnat(p->rtp, natflags);
2682 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2683 ast_rtp_setnat(p->vrtp, natflags);
2687 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2688 ast_udptl_setnat(p->udptl, natflags);
2692 /*! \brief Create address structure from peer reference.
2693 * return -1 on error, 0 on success.
2695 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2697 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2698 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2699 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2700 dialog->recv = dialog->sa;
2704 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2705 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2706 dialog->capability = peer->capability;
2707 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2708 ast_rtp_destroy(dialog->vrtp);
2709 dialog->vrtp = NULL;
2711 dialog->prefs = peer->prefs;
2712 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2713 dialog->t38.capability = global_t38_capability;
2714 if (dialog->udptl) {
2715 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2716 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2717 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2718 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2719 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2720 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2721 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2722 if (option_debug > 1)
2723 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2725 dialog->t38.jointcapability = dialog->t38.capability;
2726 } else if (dialog->udptl) {
2727 ast_udptl_destroy(dialog->udptl);
2728 dialog->udptl = NULL;
2730 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2733 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2734 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2735 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2736 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2737 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2738 /* Set Frame packetization */
2739 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2740 dialog->autoframing = peer->autoframing;
2743 ast_rtp_setdtmf(dialog->vrtp, 0);
2744 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2745 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2746 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2747 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2750 ast_string_field_set(dialog, peername, peer->username);
2751 ast_string_field_set(dialog, authname, peer->username);
2752 ast_string_field_set(dialog, username, peer->username);
2753 ast_string_field_set(dialog, peersecret, peer->secret);
2754 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2755 ast_string_field_set(dialog, tohost, peer->tohost);
2756 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2757 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2760 tmpcall = ast_strdupa(dialog->callid);
2761 c = strchr(tmpcall, '@');
2764 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2767 if (ast_strlen_zero(dialog->tohost))
2768 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2769 if (!ast_strlen_zero(peer->fromdomain))
2770 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2771 if (!ast_strlen_zero(peer->fromuser))
2772 ast_string_field_set(dialog, fromuser, peer->fromuser);
2773 dialog->callgroup = peer->callgroup;
2774 dialog->pickupgroup = peer->pickupgroup;
2775 dialog->allowtransfer = peer->allowtransfer;
2776 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2777 /* Minimum is settable or default to 100 ms */
2778 if (peer->maxms && peer->lastms)
2779 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2780 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2781 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2782 dialog->noncodeccapability |= AST_RTP_DTMF;
2784 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2785 ast_string_field_set(dialog, context, peer->context);
2786 dialog->rtptimeout = peer->rtptimeout;
2787 if (peer->call_limit)
2788 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2789 dialog->maxcallbitrate = peer->maxcallbitrate;
2794 /*! \brief create address structure from peer name
2795 * Or, if peer not found, find it in the global DNS
2796 * returns TRUE (-1) on failure, FALSE on success */
2797 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2800 struct ast_hostent ahp;
2801 struct sip_peer *peer;
2804 char host[MAXHOSTNAMELEN], *hostn;
2807 ast_copy_string(peername, opeer, sizeof(peername));
2808 port = strchr(peername, ':');
2811 dialog->sa.sin_family = AF_INET;
2812 dialog->timer_t1 = SIP_TIMER_T1; /* Default SIP retransmission timer T1 (RFC 3261) */
2813 peer = find_peer(peername, NULL, 1);
2816 int res = create_addr_from_peer(dialog, peer);
2821 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2822 if (global_srvlookup) {
2823 char service[MAXHOSTNAMELEN];
2827 snprintf(service, sizeof(service), "_sip._udp.%s", peername);
2828 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2834 hp = ast_gethostbyname(hostn, &ahp);
2836 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2839 ast_string_field_set(dialog, tohost, peername);
2840 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2841 dialog->sa.sin_port = htons(portno);
2842 dialog->recv = dialog->sa;
2846 /*! \brief Scheduled congestion on a call */
2847 static int auto_congest(void *nothing)
2849 struct sip_pvt *p = nothing;
2854 /* XXX fails on possible deadlock */
2855 if (!ast_channel_trylock(p->owner)) {
2856 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2857 append_history(p, "Cong", "Auto-congesting (timer)");
2858 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2859 ast_channel_unlock(p->owner);
2867 /*! \brief Initiate SIP call from PBX
2868 * used from the dial() application */
2869 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2873 struct varshead *headp;
2874 struct ast_var_t *current;
2875 const char *referer = NULL; /* SIP referrer */
2878 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2879 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2883 /* Check whether there is vxml_url, distinctive ring variables */
2884 headp=&ast->varshead;
2885 AST_LIST_TRAVERSE(headp,current,entries) {
2886 /* Check whether there is a VXML_URL variable */
2887 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2888 p->options->vxml_url = ast_var_value(current);
2889 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2890 p->options->uri_options = ast_var_value(current);
2891 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2892 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2893 p->options->addsipheaders = 1;
2894 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2895 /* This is a transfered call */
2896 p->options->transfer = 1;
2897 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2898 /* This is the referrer */
2899 referer = ast_var_value(current);
2900 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2901 /* We're replacing a call. */
2902 p->options->replaces = ast_var_value(current);
2903 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2904 p->t38.state = T38_LOCAL_DIRECT;
2906 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2912 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2914 if (p->options->transfer) {
2918 if (sipdebug && option_debug > 2)
2919 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2920 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2922 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2923 ast_string_field_set(p, cid_name, buf);
2926 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2928 res = update_call_counter(p, INC_CALL_RINGING);
2933 p->callingpres = ast->cid.cid_pres;
2934 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
2936 /* If there are no audio formats left to offer, punt */
2937 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
2938 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
2941 p->t38.jointcapability = p->t38.capability;
2942 if (option_debug > 1)
2943 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2944 transmit_invite(p, SIP_INVITE, 1, 2);
2945 p->invitestate = INV_CALLING;
2947 /* Initialize auto-congest time */
2948 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2954 /*! \brief Destroy registry object
2955 Objects created with the register= statement in static configuration */
2956 static void sip_registry_destroy(struct sip_registry *reg)
2959 if (option_debug > 2)
2960 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2963 /* Clear registry before destroying to ensure
2964 we don't get reentered trying to grab the registry lock */
2965 reg->call->registry = NULL;
2966 if (option_debug > 2)
2967 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2968 sip_destroy(reg->call);
2970 if (reg->expire > -1)
2971 ast_sched_del(sched, reg->expire);
2972 if (reg->timeout > -1)
2973 ast_sched_del(sched, reg->timeout);
2974 ast_string_field_free_pools(reg);
2980 /*! \brief Execute destruction of SIP dialog structure, release memory */
2981 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
2983 struct sip_pvt *cur, *prev = NULL;
2986 if (sip_debug_test_pvt(p) || option_debug > 2)
2987 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2989 /* Remove link from peer to subscription of MWI */
2990 if (p->relatedpeer && p->relatedpeer->mwipvt)
2991 p->relatedpeer->mwipvt = NULL;
2994 sip_dump_history(p);
2999 if (p->stateid > -1)
3000 ast_extension_state_del(p->stateid, NULL);
3002 ast_sched_del(sched, p->initid);
3003 if (p->autokillid > -1)
3004 ast_sched_del(sched, p->autokillid);
3007 ast_rtp_destroy(p->rtp);
3009 ast_rtp_destroy(p->vrtp);
3011 ast_udptl_destroy(p->udptl);
3015 free_old_route(p->route);
3019 if (p->registry->call == p)
3020 p->registry->call = NULL;
3021 unref_registry(p->registry);
3024 /* Unlink us from the owner if we have one */
3027 ast_channel_lock(p->owner);
3029 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3030 p->owner->tech_pvt = NULL;
3032 ast_channel_unlock(p->owner);
3036 struct sip_history *hist;
3037 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
3043 /* Lock dialog list before removing ourselves from the list */
3046 for (prev = NULL, cur = dialoglist; cur; prev = cur, cur = cur->next) {
3048 UNLINK(cur, dialoglist, prev);
3053 dialoglist_unlock();
3055 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3059 /* remove all current packets in this dialog */
3060 while((cp = p->packets)) {
3061 p->packets = p->packets->next;
3062 if (cp->retransid > -1)
3063 ast_sched_del(sched, cp->retransid);
3067 ast_variables_destroy(p->chanvars);
3070 ast_mutex_destroy(&p->pvt_lock);
3072 ast_string_field_free_pools(p);
3077 /*! \brief update_call_counter: Handle call_limit for SIP users
3078 * Setting a call-limit will cause calls above the limit not to be accepted.
3080 * Remember that for a type=friend, there's one limit for the user and
3081 * another for the peer, not a combined call limit.
3082 * This will cause unexpected behaviour in subscriptions, since a "friend"
3083 * is *two* devices in Asterisk, not one.
3085 * Thought: For realtime, we should probably update storage with inuse counter...
3087 * \return 0 if call is ok (no call limit, below threshold)
3088 * -1 on rejection of call
3091 static int update_call_counter(struct sip_pvt *fup, int event)
3094 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
3095 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
3096 struct sip_user *u = NULL;
3097 struct sip_peer *p = NULL;
3099 if (option_debug > 2)
3100 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
3101 /* Test if we need to check call limits, in order to avoid
3102 realtime lookups if we do not need it */
3103 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
3106 ast_copy_string(name, fup->username, sizeof(name));
3108 /* Check the list of users only for incoming calls */
3109 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
3111 call_limit = &u->call_limit;
3113 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
3115 call_limit = &p->call_limit;
3116 inringing = &p->inRinging;
3117 ast_copy_string(name, fup->peername, sizeof(name));
3120 if (option_debug > 1)
3121 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
3126 /* incoming and outgoing affects the inUse counter */
3127 case DEC_CALL_LIMIT:
3129 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
3135 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3139 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
3140 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3143 if (option_debug > 1 || sipdebug) {
3144 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
3148 case INC_CALL_RINGING:
3149 case INC_CALL_LIMIT:
3150 if (*call_limit > 0 ) {
3151 if (*inuse >= *call_limit) {
3152 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);
3160 if (inringing && (event == INC_CALL_RINGING)) {
3161 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3163 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3168 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
3169 if (option_debug > 1 || sipdebug) {
3170 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
3174 case DEC_CALL_RINGING:
3176 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
3180 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
3181 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
3187 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
3190 ast_device_state_changed("SIP/%s", p->name);
3192 } else /* u must be set */
3197 /*! \brief Destroy SIP call structure */
3198 static void sip_destroy(struct sip_pvt *p)
3200 if (option_debug > 2)
3201 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3202 __sip_destroy(p, TRUE, TRUE);
3205 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3206 static int hangup_sip2cause(int cause)
3208 /* Possible values taken from causes.h */
3211 case 401: /* Unauthorized */
3212 return AST_CAUSE_CALL_REJECTED;
3213 case 403: /* Not found */
3214 return AST_CAUSE_CALL_REJECTED;
3215 case 404: /* Not found */
3216 return AST_CAUSE_UNALLOCATED;
3217 case 405: /* Method not allowed */
3218 return AST_CAUSE_INTERWORKING;
3219 case 407: /* Proxy authentication required */
3220 return AST_CAUSE_CALL_REJECTED;
3221 case 408: /* No reaction */
3222 return AST_CAUSE_NO_USER_RESPONSE;
3223 case 409: /* Conflict */
3224 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3225 case 410: /* Gone */
3226 return AST_CAUSE_UNALLOCATED;
3227 case 411: /* Length required */
3228 return AST_CAUSE_INTERWORKING;
3229 case 413: /* Request entity too large */
3230 return AST_CAUSE_INTERWORKING;
3231 case 414: /* Request URI too large */
3232 return AST_CAUSE_INTERWORKING;
3233 case 415: /* Unsupported media type */
3234 return AST_CAUSE_INTERWORKING;
3235 case 420: /* Bad extension */
3236 return AST_CAUSE_NO_ROUTE_DESTINATION;
3237 case 480: /* No answer */
3238 return AST_CAUSE_NO_ANSWER;
3239 case 481: /* No answer */
3240 return AST_CAUSE_INTERWORKING;
3241 case 482: /* Loop detected */
3242 return AST_CAUSE_INTERWORKING;
3243 case 483: /* Too many hops */
3244 return AST_CAUSE_NO_ANSWER;
3245 case 484: /* Address incomplete */
3246 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3247 case 485: /* Ambiguous */
3248 return AST_CAUSE_UNALLOCATED;
3249 case 486: /* Busy everywhere */
3250 return AST_CAUSE_BUSY;
3251 case 487: /* Request terminated */
3252 return AST_CAUSE_INTERWORKING;
3253 case 488: /* No codecs approved */
3254 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3255 case 491: /* Request pending */
3256 return AST_CAUSE_INTERWORKING;
3257 case 493: /* Undecipherable */
3258 return AST_CAUSE_INTERWORKING;
3259 case 500: /* Server internal failure */
3260 return AST_CAUSE_FAILURE;
3261 case 501: /* Call rejected */
3262 return AST_CAUSE_FACILITY_REJECTED;
3264 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3265 case 503: /* Service unavailable */
3266 return AST_CAUSE_CONGESTION;
3267 case 504: /* Gateway timeout */
3268 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3269 case 505: /* SIP version not supported */
3270 return AST_CAUSE_INTERWORKING;
3271 case 600: /* Busy everywhere */
3272 return AST_CAUSE_USER_BUSY;
3273 case 603: /* Decline */
3274 return AST_CAUSE_CALL_REJECTED;
3275 case 604: /* Does not exist anywhere */
3276 return AST_CAUSE_UNALLOCATED;
3277 case 606: /* Not acceptable */
3278 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3280 return AST_CAUSE_NORMAL;
3286 /*! \brief Convert Asterisk hangup causes to SIP codes
3288 Possible values from causes.h
3289 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3290 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3292 In addition to these, a lot of PRI codes is defined in causes.h
3293 ...should we take care of them too ?
3297 ISUP Cause value SIP response
3298 ---------------- ------------
3299 1 unallocated number 404 Not Found
3300 2 no route to network 404 Not found
3301 3 no route to destination 404 Not found
3302 16 normal call clearing --- (*)
3303 17 user busy 486 Busy here
3304 18 no user responding 408 Request Timeout
3305 19 no answer from the user 480 Temporarily unavailable
3306 20 subscriber absent 480 Temporarily unavailable
3307 21 call rejected 403 Forbidden (+)
3308 22 number changed (w/o diagnostic) 410 Gone
3309 22 number changed (w/ diagnostic) 301 Moved Permanently
3310 23 redirection to new destination 410 Gone
3311 26 non-selected user clearing 404 Not Found (=)
3312 27 destination out of order 502 Bad Gateway
3313 28 address incomplete 484 Address incomplete
3314 29 facility rejected 501 Not implemented
3315 31 normal unspecified 480 Temporarily unavailable
3318 static const char *hangup_cause2sip(int cause)
3321 case AST_CAUSE_UNALLOCATED: /* 1 */
3322 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3323 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3324 return "404 Not Found";
3325 case AST_CAUSE_CONGESTION: /* 34 */
3326 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3327 return "503 Service Unavailable";
3328 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3329 return "408 Request Timeout";
3330 case AST_CAUSE_NO_ANSWER: /* 19 */
3331 return "480 Temporarily unavailable";
3332 case AST_CAUSE_CALL_REJECTED: /* 21 */
3333 return "403 Forbidden";
3334 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3336 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3337 return "480 Temporarily unavailable";
3338 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3339 return "484 Address incomplete";
3340 case AST_CAUSE_USER_BUSY:
3341 return "486 Busy here";
3342 case AST_CAUSE_FAILURE:
3343 return "500 Server internal failure";
3344 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3345 return "501 Not Implemented";
3346 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3347 return "503 Service Unavailable";
3348 /* Used in chan_iax2 */
3349 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3350 return "502 Bad Gateway";
3351 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3352 return "488 Not Acceptable Here";
3354 case AST_CAUSE_NOTDEFINED:
3357 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3366 /*! \brief sip_hangup: Hangup SIP call
3367 * Part of PBX interface, called from ast_hangup */
3368 static int sip_hangup(struct ast_channel *ast)
3370 struct sip_pvt *p = ast->tech_pvt;
3371 int needcancel = FALSE;
3372 int needdestroy = 0;
3373 struct ast_channel *oldowner = ast;
3377 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3381 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3382 if (option_debug >3)
3383 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3384 if (p->autokillid > -1)
3385 sip_cancel_destroy(p);
3386 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3387 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3388 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3389 p->owner->tech_pvt = NULL;
3390 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3394 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3395 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3398 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3401 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3402 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3405 if (option_debug && sipdebug)
3406 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3407 update_call_counter(p, DEC_CALL_LIMIT);
3409 /* Determine how to disconnect */
3410 if (p->owner != ast) {
3411 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3415 /* If the call is not UP, we need to send CANCEL instead of BYE */
3416 if (p->invitestate < INV_COMPLETED) {
3418 if (option_debug > 3)
3419 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3424 ast_dsp_free(p->vad);
3427 ast->tech_pvt = NULL;
3429 /* Do not destroy this pvt until we have timeout or
3430 get an answer to the BYE or INVITE/CANCEL
3431 If we get no answer during retransmit period, drop the call anyway.
3432 (Sorry, mother-in-law, you can't deny a hangup by sending
3433 603 declined to BYE...)
3435 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3436 needdestroy = 1; /* Set destroy flag at end of this function */
3437 else if (p->invitestate != INV_CALLING)
3438 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3440 /* Start the process if it's not already started */
3441 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3442 if (needcancel) { /* Outgoing call, not up */
3443 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3444 /* stop retransmitting an INVITE that has not received a response */
3445 __sip_pretend_ack(p);
3447 /* if we can't send right now, mark it pending */
3448 if (p->invitestate == INV_CALLING) {
3449 /* We can't send anything in CALLING state */
3450 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3451 /* Do we need a timer here if we don't hear from them at all? */
3453 /* Send a new request: CANCEL */
3454 transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
3455 /* Actually don't destroy us yet, wait for the 487 on our original
3456 INVITE, but do set an autodestruct just in case we never get it. */
3458 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3460 if ( p->initid != -1 ) {
3461 /* channel still up - reverse dec of inUse counter
3462 only if the channel is not auto-congested */
3463 update_call_counter(p, INC_CALL_LIMIT);