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 /* Do _NOT_ make any changes to this enum, or the array following it;
242 if you think you are doing the right thing, you are probably
243 not doing the right thing. If you think there are changes
244 needed, get someone else to review them first _before_
245 submitting a patch. If these two lists do not match properly
246 bad things will happen.
250 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
251 If it fails, it's critical and will cause a teardown of the session */
252 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
253 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
256 enum parse_register_result {
257 PARSE_REGISTER_FAILED,
258 PARSE_REGISTER_UPDATE,
259 PARSE_REGISTER_QUERY,
262 enum subscriptiontype {
271 static const struct cfsubscription_types {
272 enum subscriptiontype type;
273 const char * const event;
274 const char * const mediatype;
275 const char * const text;
276 } subscription_types[] = {
277 { NONE, "-", "unknown", "unknown" },
278 /* RFC 4235: SIP Dialog event package */
279 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
280 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
281 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
282 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
283 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
286 /*! \brief SIP Request methods known by Asterisk */
288 SIP_UNKNOWN, /* Unknown response */
289 SIP_RESPONSE, /* Not request, response to outbound request */
295 SIP_PRACK, /* Not supported at all */
300 SIP_UPDATE, /* We can send UPDATE; but not accept it */
303 SIP_PUBLISH, /* Not supported at all */
304 SIP_PING, /* Not supported at all, no standard but still implemented out there */
307 /*! \brief Authentication types - proxy or www authentication
308 \note Endpoints, like Asterisk, should always use WWW authentication to
309 allow multiple authentications in the same call - to the proxy and
317 /*! \brief Authentication result from check_auth* functions */
318 enum check_auth_result {
319 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
320 /* XXX maybe this is the same as AUTH_NOT_FOUND */
323 AUTH_CHALLENGE_SENT = 1,
324 AUTH_SECRET_FAILED = -1,
325 AUTH_USERNAME_MISMATCH = -2,
326 AUTH_NOT_FOUND = -3, /* returned by register_verify */
328 AUTH_UNKNOWN_DOMAIN = -5,
331 /*! \brief States for outbound registrations (with register= lines in sip.conf */
332 enum sipregistrystate {
333 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
334 REG_STATE_REGSENT, /*!< Registration request sent */
335 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
336 REG_STATE_REGISTERED, /*!< Registred and done */
337 REG_STATE_REJECTED, /*!< Registration rejected */
338 REG_STATE_TIMEOUT, /*!< Registration timed out */
339 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
340 REG_STATE_FAILED, /*!< Registration failed after several tries */
343 enum can_create_dialog {
344 CAN_NOT_CREATE_DIALOG,
346 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
349 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
350 static const struct cfsip_methods {
352 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
354 enum can_create_dialog can_create;
356 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
357 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
358 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
359 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
360 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
361 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
362 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
363 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
364 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
365 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
366 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
367 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
368 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
369 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
370 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
371 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
372 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
375 /*! Define SIP option tags, used in Require: and Supported: headers
376 We need to be aware of these properties in the phones to use
377 the replace: header. We should not do that without knowing
378 that the other end supports it...
379 This is nothing we can configure, we learn by the dialog
380 Supported: header on the REGISTER (peer) or the INVITE
382 We are not using many of these today, but will in the future.
383 This is documented in RFC 3261
386 #define NOT_SUPPORTED 0
388 #define SIP_OPT_REPLACES (1 << 0)
389 #define SIP_OPT_100REL (1 << 1)
390 #define SIP_OPT_TIMER (1 << 2)
391 #define SIP_OPT_EARLY_SESSION (1 << 3)
392 #define SIP_OPT_JOIN (1 << 4)
393 #define SIP_OPT_PATH (1 << 5)
394 #define SIP_OPT_PREF (1 << 6)
395 #define SIP_OPT_PRECONDITION (1 << 7)
396 #define SIP_OPT_PRIVACY (1 << 8)
397 #define SIP_OPT_SDP_ANAT (1 << 9)
398 #define SIP_OPT_SEC_AGREE (1 << 10)
399 #define SIP_OPT_EVENTLIST (1 << 11)
400 #define SIP_OPT_GRUU (1 << 12)
401 #define SIP_OPT_TARGET_DIALOG (1 << 13)
402 #define SIP_OPT_NOREFERSUB (1 << 14)
403 #define SIP_OPT_HISTINFO (1 << 15)
404 #define SIP_OPT_RESPRIORITY (1 << 16)
406 /*! \brief List of well-known SIP options. If we get this in a require,
407 we should check the list and answer accordingly. */
408 static const struct cfsip_options {
409 int id; /*!< Bitmap ID */
410 int supported; /*!< Supported by Asterisk ? */
411 char * const text; /*!< Text id, as in standard */
412 } sip_options[] = { /* XXX used in 3 places */
413 /* RFC3891: Replaces: header for transfer */
414 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
415 /* One version of Polycom firmware has the wrong label */
416 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
417 /* RFC3262: PRACK 100% reliability */
418 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
419 /* RFC4028: SIP Session Timers */
420 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
421 /* RFC3959: SIP Early session support */
422 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
423 /* RFC3911: SIP Join header support */
424 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
425 /* RFC3327: Path support */
426 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
427 /* RFC3840: Callee preferences */
428 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
429 /* RFC3312: Precondition support */
430 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
431 /* RFC3323: Privacy with proxies*/
432 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
433 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
434 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
435 /* RFC3329: Security agreement mechanism */
436 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
437 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
438 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
439 /* GRUU: Globally Routable User Agent URI's */
440 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
441 /* Target-dialog: draft-ietf-sip-target-dialog-03.txt */
442 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
443 /* Disable the REFER subscription, RFC 4488 */
444 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
445 /* ietf-sip-history-info-06.txt */
446 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
447 /* ietf-sip-resource-priority-10.txt */
448 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
452 /*! \brief SIP Methods we support */
453 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
455 /*! \brief SIP Extensions we support */
456 #define SUPPORTED_EXTENSIONS "replaces"
458 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
459 #define STANDARD_SIP_PORT 5060
460 /* Note: in many SIP headers, absence of a port number implies port 5060,
461 * and this is why we cannot change the above constant.
462 * There is a limited number of places in asterisk where we could,
463 * in principle, use a different "default" port number, but
464 * we do not support this feature at the moment.
467 /* Default values, set and reset in reload_config before reading configuration */
468 /* These are default values in the source. There are other recommended values in the
469 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
470 yet encouraging new behaviour on new installations
472 #define DEFAULT_CONTEXT "default"
473 #define DEFAULT_MOHINTERPRET "default"
474 #define DEFAULT_MOHSUGGEST ""
475 #define DEFAULT_VMEXTEN "asterisk"
476 #define DEFAULT_CALLERID "asterisk"
477 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
478 #define DEFAULT_MWITIME 10
479 #define DEFAULT_ALLOWGUEST TRUE
480 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
481 #define DEFAULT_COMPACTHEADERS FALSE
482 #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. */
483 #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. */
484 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
485 #define DEFAULT_ALLOW_EXT_DOM TRUE
486 #define DEFAULT_REALM "asterisk"
487 #define DEFAULT_NOTIFYRINGING TRUE
488 #define DEFAULT_PEDANTIC FALSE
489 #define DEFAULT_AUTOCREATEPEER FALSE
490 #define DEFAULT_QUALIFY FALSE
491 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
492 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
493 #ifndef DEFAULT_USERAGENT
494 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
498 /* Default setttings are used as a channel setting and as a default when
499 configuring devices */
500 static char default_context[AST_MAX_CONTEXT];
501 static char default_subscribecontext[AST_MAX_CONTEXT];
502 static char default_language[MAX_LANGUAGE];
503 static char default_callerid[AST_MAX_EXTENSION];
504 static char default_fromdomain[AST_MAX_EXTENSION];
505 static char default_notifymime[AST_MAX_EXTENSION];
506 static int default_qualify; /*!< Default Qualify= setting */
507 static char default_vmexten[AST_MAX_EXTENSION];
508 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
509 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
510 * a bridged channel on hold */
511 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
512 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
514 /* Global settings only apply to the channel */
515 static int global_limitonpeers; /*!< Match call limit on peers only */
516 static int global_rtautoclear;
517 static int global_notifyringing; /*!< Send notifications on ringing */
518 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
519 static int global_srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
520 static int pedanticsipchecking; /*!< Extra checking ? Default off */
521 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
522 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
523 static int global_relaxdtmf; /*!< Relax DTMF */
524 static int global_rtptimeout; /*!< Time out call if no RTP */
525 static int global_rtpholdtimeout;
526 static int global_rtpkeepalive; /*!< Send RTP keepalives */
527 static int global_reg_timeout;
528 static int global_regattempts_max; /*!< Registration attempts before giving up */
529 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
530 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
531 the global setting is in globals_flags[1] */
532 static int global_mwitime; /*!< Time between MWI checks for peers */
533 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
534 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
535 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
536 static int compactheaders; /*!< send compact sip headers */
537 static int recordhistory; /*!< Record SIP history. Off by default */
538 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
539 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
540 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
541 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
542 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
543 static int global_callevents; /*!< Whether we send manager events or not */
544 static int global_t1min; /*!< T1 roundtrip time minimum */
545 static int global_autoframing; /*!< ?????????? */
546 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
548 /*! \brief Codecs that we support by default: */
549 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
550 static int noncodeccapability = AST_RTP_DTMF;
552 /* Object counters */
553 static int suserobjs = 0; /*!< Static users */
554 static int ruserobjs = 0; /*!< Realtime users */
555 static int speerobjs = 0; /*!< Statis peers */
556 static int rpeerobjs = 0; /*!< Realtime peers */
557 static int apeerobjs = 0; /*!< Autocreated peer objects */
558 static int regobjs = 0; /*!< Registry objects */
560 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
562 AST_MUTEX_DEFINE_STATIC(netlock);
564 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
565 when it's doing something critical. */
567 AST_MUTEX_DEFINE_STATIC(monlock);
569 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
571 /*! \brief This is the thread for the monitor which checks for input on the channels
572 which are not currently in use. */
573 static pthread_t monitor_thread = AST_PTHREADT_NULL;
575 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
576 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
578 static struct sched_context *sched; /*!< The scheduling context */
579 static struct io_context *io; /*!< The IO context */
580 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
582 #define DEC_CALL_LIMIT 0
583 #define INC_CALL_LIMIT 1
584 #define DEC_CALL_RINGING 2
585 #define INC_CALL_RINGING 3
587 /*! \brief sip_request: The data grabbed from the UDP socket */
589 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
590 char *rlPart2; /*!< The Request URI or Response Status */
591 int len; /*!< Length */
592 int headers; /*!< # of SIP Headers */
593 int method; /*!< Method of this request */
594 int lines; /*!< Body Content */
595 unsigned int flags; /*!< SIP_PKT Flags for this packet */
596 char *header[SIP_MAX_HEADERS];
597 char *line[SIP_MAX_LINES];
598 char data[SIP_MAX_PACKET];
599 unsigned int sdp_start; /*!< the line number where the SDP begins */
600 unsigned int sdp_end; /*!< the line number where the SDP ends */
604 * A sip packet is stored into the data[] buffer, with the header followed
605 * by an empty line and the body of the message.
606 * On outgoing packets, data is accumulated in data[] with len reflecting
607 * the next available byte, headers and lines count the number of lines
608 * in both parts. There are no '\0' in data[0..len-1].
610 * On received packet, the input read from the socket is copied into data[],
611 * len is set and the string is NUL-terminated. Then a parser fills up
612 * the other fields -header[] and line[] to point to the lines of the
613 * message, rlPart1 and rlPart2 parse the first lnie as below:
615 * Requests have in the first line METHOD URI SIP/2.0
616 * rlPart1 = method; rlPart2 = uri;
617 * Responses have in the first line SIP/2.0 code description
618 * rlPart1 = SIP/2.0; rlPart2 = code + description;
622 /*! \brief structure used in transfers */
624 struct ast_channel *chan1; /*!< First channel involved */
625 struct ast_channel *chan2; /*!< Second channel involved */
626 struct sip_request req; /*!< Request that caused the transfer (REFER) */
627 int seqno; /*!< Sequence number */
632 /*! \brief Parameters to the transmit_invite function */
633 struct sip_invite_param {
634 int addsipheaders; /*!< Add extra SIP headers */
635 const char *uri_options; /*!< URI options to add to the URI */
636 const char *vxml_url; /*!< VXML url for Cisco phones */
637 char *auth; /*!< Authentication */
638 char *authheader; /*!< Auth header */
639 enum sip_auth_type auth_type; /*!< Authentication type */
640 const char *replaces; /*!< Replaces header for call transfers */
641 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
644 /*! \brief Structure to save routing information for a SIP session */
646 struct sip_route *next;
650 /*! \brief Modes for SIP domain handling in the PBX */
652 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
653 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
656 /*! \brief Domain data structure.
657 \note In the future, we will connect this to a configuration tree specific
661 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
662 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
663 enum domain_mode mode; /*!< How did we find this domain? */
664 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
667 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
670 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
672 AST_LIST_ENTRY(sip_history) list;
673 char event[0]; /* actually more, depending on needs */
676 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
678 /*! \brief sip_auth: Credentials for authentication to other SIP services */
680 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
681 char username[256]; /*!< Username */
682 char secret[256]; /*!< Secret */
683 char md5secret[256]; /*!< MD5Secret */
684 struct sip_auth *next; /*!< Next auth structure in list */
687 /*--- Various flags for the flags field in the pvt structure */
688 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
689 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
690 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
691 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
692 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
693 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
694 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
695 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
696 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
697 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
698 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
699 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
700 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
701 #define SIP_OUTGOING (1 << 13) /*!< Direction of the last transaction in this dialog */
702 #define SIP_CAN_BYE (1 << 14) /*!< Can we send BYE on this dialog? */
703 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
704 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
705 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
706 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
707 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
708 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
710 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
711 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
712 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
713 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
714 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
715 /* re-INVITE related settings */
716 #define SIP_REINVITE (7 << 20) /*!< three bits used */
717 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
718 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
719 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
720 /* "insecure" settings */
721 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
722 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
723 /* Sending PROGRESS in-band settings */
724 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
725 #define SIP_PROG_INBAND_NEVER (0 << 25)
726 #define SIP_PROG_INBAND_NO (1 << 25)
727 #define SIP_PROG_INBAND_YES (2 << 25)
728 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */
729 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
730 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
731 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
732 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
734 #define SIP_FLAGS_TO_COPY \
735 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
736 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
737 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
739 /*--- a new page of flags (for flags[1] */
741 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
742 #define SIP_PAGE2_RTUPDATE (1 << 1)
743 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
744 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
745 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
746 /* Space for addition of other realtime flags in the future */
747 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
748 #define SIP_PAGE2_DEBUG (3 << 11)
749 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
750 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
751 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
752 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
753 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
754 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
755 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
756 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
757 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
758 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
759 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
760 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */
761 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */
762 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
763 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
764 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (2 << 24) /*!< 24: Inactive */
765 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 26)
767 #define SIP_PAGE2_FLAGS_TO_COPY \
768 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE)
770 /* SIP packet flags */
771 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
772 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
773 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
774 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
775 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
777 /* T.38 set of flags */
778 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
779 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
780 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
781 /* Rate management */
782 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
783 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
784 /* UDP Error correction */
785 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
786 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
787 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
788 /* T38 Spec version */
789 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
790 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
791 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
792 /* Maximum Fax Rate */
793 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
794 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
795 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
796 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
797 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
798 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
800 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
801 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
803 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
804 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
805 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
807 /*! \brief T38 States for a call */
809 T38_DISABLED = 0, /*!< Not enabled */
810 T38_LOCAL_DIRECT, /*!< Offered from local */
811 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
812 T38_PEER_DIRECT, /*!< Offered from peer */
813 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
814 T38_ENABLED /*!< Negotiated (enabled) */
817 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
818 struct t38properties {
819 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
820 int capability; /*!< Our T38 capability */
821 int peercapability; /*!< Peers T38 capability */
822 int jointcapability; /*!< Supported T38 capability at both ends */
823 enum t38state state; /*!< T.38 state */
826 /*! \brief Parameters to know status of transfer */
828 REFER_IDLE, /*!< No REFER is in progress */
829 REFER_SENT, /*!< Sent REFER to transferee */
830 REFER_RECEIVED, /*!< Received REFER from transferer */
831 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
832 REFER_ACCEPTED, /*!< Accepted by transferee */
833 REFER_RINGING, /*!< Target Ringing */
834 REFER_200OK, /*!< Answered by transfer target */
835 REFER_FAILED, /*!< REFER declined - go on */
836 REFER_NOAUTH /*!< We had no auth for REFER */
839 static const struct c_referstatusstring {
840 enum referstatus status;
842 } referstatusstrings[] = {
843 { REFER_IDLE, "<none>" },
844 { REFER_SENT, "Request sent" },
845 { REFER_RECEIVED, "Request received" },
846 { REFER_ACCEPTED, "Accepted" },
847 { REFER_RINGING, "Target ringing" },
848 { REFER_200OK, "Done" },
849 { REFER_FAILED, "Failed" },
850 { REFER_NOAUTH, "Failed - auth failure" }
853 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
854 /* OEJ: Should be moved to string fields */
856 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
857 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
858 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
859 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
860 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
861 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
862 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
863 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
864 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
865 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
866 struct sip_pvt *refer_call; /*!< Call we are referring */
867 int attendedtransfer; /*!< Attended or blind transfer? */
868 int localtransfer; /*!< Transfer to local domain? */
869 enum referstatus status; /*!< REFER status */
872 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
874 ast_mutex_t pvt_lock; /*!< Dialog private lock */
875 int method; /*!< SIP method that opened this dialog */
876 AST_DECLARE_STRING_FIELDS(
877 AST_STRING_FIELD(callid); /*!< Global CallID */
878 AST_STRING_FIELD(randdata); /*!< Random data */
879 AST_STRING_FIELD(accountcode); /*!< Account code */
880 AST_STRING_FIELD(realm); /*!< Authorization realm */
881 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
882 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
883 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
884 AST_STRING_FIELD(domain); /*!< Authorization domain */
885 AST_STRING_FIELD(from); /*!< The From: header */
886 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
887 AST_STRING_FIELD(exten); /*!< Extension where to start */
888 AST_STRING_FIELD(context); /*!< Context for this call */
889 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
890 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
891 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
892 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
893 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
894 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
895 AST_STRING_FIELD(language); /*!< Default language for this call */
896 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
897 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
898 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
899 AST_STRING_FIELD(redircause); /*!< Referring cause */
900 AST_STRING_FIELD(theirtag); /*!< Their tag */
901 AST_STRING_FIELD(username); /*!< [user] name */
902 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
903 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
904 AST_STRING_FIELD(uri); /*!< Original requested URI */
905 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
906 AST_STRING_FIELD(peersecret); /*!< Password */
907 AST_STRING_FIELD(peermd5secret);
908 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
909 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
910 AST_STRING_FIELD(via); /*!< Via: header */
911 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
912 /* we only store the part in <brackets> in this field. */
913 AST_STRING_FIELD(our_contact); /*!< Our contact header */
914 AST_STRING_FIELD(rpid); /*!< Our RPID header */
915 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
917 unsigned int ocseq; /*!< Current outgoing seqno */
918 unsigned int icseq; /*!< Current incoming seqno */
919 ast_group_t callgroup; /*!< Call group */
920 ast_group_t pickupgroup; /*!< Pickup group */
921 int lastinvite; /*!< Last Cseq of invite */
922 struct ast_flags flags[2]; /*!< SIP_ flags */
923 int timer_t1; /*!< SIP timer T1, ms rtt */
924 unsigned int sipoptions; /*!< Supported SIP options on the other end */
925 struct ast_codec_pref prefs; /*!< codec prefs */
926 int capability; /*!< Special capability (codec) */
927 int jointcapability; /*!< Supported capability at both ends (codecs) */
928 int peercapability; /*!< Supported peer capability */
929 int prefcodec; /*!< Preferred codec (outbound only) */
930 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
931 int redircodecs; /*!< Redirect codecs */
932 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
933 struct t38properties t38; /*!< T38 settings */
934 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
935 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
936 int callingpres; /*!< Calling presentation */
937 int authtries; /*!< Times we've tried to authenticate */
938 int expiry; /*!< How long we take to expire */
939 long branch; /*!< The branch identifier of this session */
940 char tag[11]; /*!< Our tag for this session */
941 int sessionid; /*!< SDP Session ID */
942 int sessionversion; /*!< SDP Session Version */
943 struct sockaddr_in sa; /*!< Our peer */
944 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
945 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
946 time_t lastrtprx; /*!< Last RTP received */
947 time_t lastrtptx; /*!< Last RTP sent */
948 int rtptimeout; /*!< RTP timeout time */
949 int rtpholdtimeout; /*!< RTP timeout when on hold */
950 int rtpkeepalive; /*!< Send RTP packets for keepalive */
951 struct sockaddr_in recv; /*!< Received as */
952 struct in_addr ourip; /*!< Our IP */
953 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
954 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
955 int route_persistant; /*!< Is this the "real" route? */
956 struct sip_auth *peerauth; /*!< Realm authentication */
957 int noncecount; /*!< Nonce-count */
958 char lastmsg[256]; /*!< Last Message sent/received */
959 int amaflags; /*!< AMA Flags */
960 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
961 struct sip_request initreq; /*!< Latest request that opened a new transaction
963 NOT the request that opened the dialog
966 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
967 int autokillid; /*!< Auto-kill ID (scheduler) */
968 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
969 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
970 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
971 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
972 int laststate; /*!< SUBSCRIBE: Last known extension state */
973 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
975 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
977 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
978 Used in peerpoke, mwi subscriptions */
979 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
980 struct ast_rtp *rtp; /*!< RTP Session */
981 struct ast_rtp *vrtp; /*!< Video RTP session */
982 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
983 struct sip_history_head *history; /*!< History of this SIP dialog */
984 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
985 struct sip_pvt *next; /*!< Next dialog in chain */
986 struct sip_invite_param *options; /*!< Options for INVITE */
987 int autoframing; /*!< The number of Asters we group in a Pyroflax
988 before strolling to the Grokyzpå
989 (A bit unsure of this, please correct if
993 static struct sip_pvt *dialoglist = NULL;
995 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
996 AST_MUTEX_DEFINE_STATIC(dialoglock);
998 /*! \brief hide the way the list is locked/unlocked */
999 static void dialoglist_lock(void)
1001 ast_mutex_lock(&dialoglock);
1004 static void dialoglist_unlock(void)
1006 ast_mutex_unlock(&dialoglock);
1009 #define FLAG_RESPONSE (1 << 0)
1010 #define FLAG_FATAL (1 << 1)
1012 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1014 struct sip_pkt *next; /*!< Next packet in linked list */
1015 int retrans; /*!< Retransmission number */
1016 int method; /*!< SIP method for this packet */
1017 int seqno; /*!< Sequence number */
1018 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
1019 struct sip_pvt *owner; /*!< Owner AST call */
1020 int retransid; /*!< Retransmission ID */
1021 int timer_a; /*!< SIP timer A, retransmission timer */
1022 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1023 int packetlen; /*!< Length of packet */
1027 /*! \brief Structure for SIP user data. User's place calls to us */
1029 /* Users who can access various contexts */
1030 ASTOBJ_COMPONENTS(struct sip_user);
1031 char secret[80]; /*!< Password */
1032 char md5secret[80]; /*!< Password in md5 */
1033 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1034 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1035 char cid_num[80]; /*!< Caller ID num */
1036 char cid_name[80]; /*!< Caller ID name */
1037 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1038 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1039 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1040 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1041 char useragent[256]; /*!< User agent in SIP request */
1042 struct ast_codec_pref prefs; /*!< codec prefs */
1043 ast_group_t callgroup; /*!< Call group */
1044 ast_group_t pickupgroup; /*!< Pickup Group */
1045 unsigned int sipoptions; /*!< Supported SIP options */
1046 struct ast_flags flags[2]; /*!< SIP_ flags */
1047 int amaflags; /*!< AMA flags for billing */
1048 int callingpres; /*!< Calling id presentation */
1049 int capability; /*!< Codec capability */
1050 int inUse; /*!< Number of calls in use */
1051 int call_limit; /*!< Limit of concurrent calls */
1052 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1053 struct ast_ha *ha; /*!< ACL setting */
1054 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1055 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1059 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1060 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1062 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1063 /*!< peer->name is the unique name of this object */
1064 char secret[80]; /*!< Password */
1065 char md5secret[80]; /*!< Password in MD5 */
1066 struct sip_auth *auth; /*!< Realm authentication list */
1067 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1068 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1069 char username[80]; /*!< Temporary username until registration */
1070 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1071 int amaflags; /*!< AMA Flags (for billing) */
1072 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1073 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1074 char fromuser[80]; /*!< From: user when calling this peer */
1075 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1076 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1077 char cid_num[80]; /*!< Caller ID num */
1078 char cid_name[80]; /*!< Caller ID name */
1079 int callingpres; /*!< Calling id presentation */
1080 int inUse; /*!< Number of calls in use */
1081 int inRinging; /*!< Number of calls ringing */
1082 int onHold; /*!< Peer has someone on hold */
1083 int call_limit; /*!< Limit of concurrent calls */
1084 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1085 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1086 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1087 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1088 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1089 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1090 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1091 struct ast_codec_pref prefs; /*!< codec prefs */
1093 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1094 unsigned int sipoptions; /*!< Supported SIP options */
1095 struct ast_flags flags[2]; /*!< SIP_ flags */
1096 int expire; /*!< When to expire this peer registration */
1097 int capability; /*!< Codec capability */
1098 int rtptimeout; /*!< RTP timeout */
1099 int rtpholdtimeout; /*!< RTP Hold Timeout */
1100 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1101 ast_group_t callgroup; /*!< Call group */
1102 ast_group_t pickupgroup; /*!< Pickup group */
1103 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1104 struct sockaddr_in addr; /*!< IP address of peer */
1105 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1108 struct sip_pvt *call; /*!< Call pointer */
1109 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1110 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1111 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1112 struct timeval ps; /*!< Ping send time */
1114 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1115 struct ast_ha *ha; /*!< Access control list */
1116 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1117 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1124 /*! \brief Registrations with other SIP proxies */
1125 struct sip_registry {
1126 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1127 AST_DECLARE_STRING_FIELDS(
1128 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1129 AST_STRING_FIELD(realm); /*!< Authorization realm */
1130 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1131 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1132 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1133 AST_STRING_FIELD(domain); /*!< Authorization domain */
1134 AST_STRING_FIELD(username); /*!< Who we are registering as */
1135 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1136 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1137 AST_STRING_FIELD(secret); /*!< Password in clear text */
1138 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1139 AST_STRING_FIELD(callback); /*!< Contact extension */
1140 AST_STRING_FIELD(random);
1142 int portno; /*!< Optional port override */
1143 int expire; /*!< Sched ID of expiration */
1144 int expiry; /*!< Value to use for the Expires header */
1145 int regattempts; /*!< Number of attempts (since the last success) */
1146 int timeout; /*!< sched id of sip_reg_timeout */
1147 int refresh; /*!< How often to refresh */
1148 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1149 enum sipregistrystate regstate; /*!< Registration state (see above) */
1150 time_t regtime; /*!< Last succesful registration time */
1151 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1152 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1153 struct sockaddr_in us; /*!< Who the server thinks we are */
1154 int noncecount; /*!< Nonce-count */
1155 char lastmsg[256]; /*!< Last Message sent/received */
1158 /* --- Linked lists of various objects --------*/
1160 /*! \brief The user list: Users and friends */
1161 static struct ast_user_list {
1162 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1165 /*! \brief The peer list: Peers and Friends */
1166 static struct ast_peer_list {
1167 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1170 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1171 static struct ast_register_list {
1172 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1176 static int temp_pvt_init(void *);
1177 static void temp_pvt_cleanup(void *);
1179 /*! \brief A per-thread temporary pvt structure */
1180 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1182 /*! \todo Move the sip_auth list to AST_LIST */
1183 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1186 /* --- Sockets and networking --------------*/
1187 static int sipsock = -1; /*!< Main socket for SIP network communication */
1188 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1189 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1190 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1191 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1192 static int externrefresh = 10;
1193 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1194 static struct in_addr __ourip;
1195 static struct sockaddr_in outboundproxyip;
1197 static struct sockaddr_in debugaddr;
1199 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1201 /*---------------------------- Forward declarations of functions in chan_sip.c */
1202 /*! \note This is added to help splitting up chan_sip.c into several files
1203 in coming releases */
1205 /*--- PBX interface functions */
1206 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1207 static int sip_devicestate(void *data);
1208 static int sip_sendtext(struct ast_channel *ast, const char *text);
1209 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1210 static int sip_hangup(struct ast_channel *ast);
1211 static int sip_answer(struct ast_channel *ast);
1212 static struct ast_frame *sip_read(struct ast_channel *ast);
1213 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1214 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1215 static int sip_transfer(struct ast_channel *ast, const char *dest);
1216 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1217 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1218 static int sip_senddigit_end(struct ast_channel *ast, char digit);
1220 /*--- Transmitting responses and requests */
1221 static int sipsock_read(int *id, int fd, short events, void *ignore);
1222 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1223 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1224 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1225 static int retrans_pkt(void *data);
1226 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1227 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);
1228 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1229 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1230 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1231 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1232 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1233 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);
1234 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1235 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1236 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1237 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1238 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1239 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1240 static int transmit_info_with_digit(struct sip_pvt *p, const char digit);
1241 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1242 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1243 static int transmit_refer(struct sip_pvt *p, const char *dest);
1244 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1245 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1246 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1247 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1248 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1249 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1250 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1251 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1252 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1253 static int does_peer_need_mwi(struct sip_peer *peer);
1255 /*--- Dialog management */
1256 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1257 int useglobal_nat, const int intended_method);
1258 static int __sip_autodestruct(void *data);
1259 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1260 static void sip_cancel_destroy(struct sip_pvt *p);
1261 static void sip_destroy(struct sip_pvt *p);
1262 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1263 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset);
1264 static void __sip_pretend_ack(struct sip_pvt *p);
1265 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1266 static int auto_congest(void *nothing);
1267 static int update_call_counter(struct sip_pvt *fup, int event);
1268 static int hangup_sip2cause(int cause);
1269 static const char *hangup_cause2sip(int cause);
1270 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1271 static void free_old_route(struct sip_route *route);
1272 static void list_route(struct sip_route *route);
1273 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1274 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1275 struct sip_request *req, char *uri);
1276 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1277 static void check_pendings(struct sip_pvt *p);
1278 static void *sip_park_thread(void *stuff);
1279 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1280 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1282 /*--- Codec handling / SDP */
1283 static void try_suggested_sip_codec(struct sip_pvt *p);
1284 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1285 static const char *get_sdp(struct sip_request *req, const char *name);
1286 static int find_sdp(struct sip_request *req);
1287 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1288 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1289 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1290 int debug, int *min_packet_size);
1291 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1292 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1294 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1295 static void do_setnat(struct sip_pvt *p, int natflags);
1297 /*--- Authentication stuff */
1298 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1299 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1300 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1301 const char *secret, const char *md5secret, int sipmethod,
1302 char *uri, enum xmittype reliable, int ignore);
1303 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1304 int sipmethod, char *uri, enum xmittype reliable,
1305 struct sockaddr_in *sin, struct sip_peer **authpeer);
1306 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1308 /*--- Domain handling */
1309 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1310 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1311 static void clear_sip_domains(void);
1313 /*--- SIP realm authentication */
1314 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1315 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1316 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1318 /*--- Misc functions */
1319 static int sip_do_reload(enum channelreloadreason reason);
1320 static int reload_config(enum channelreloadreason reason);
1321 static int expire_register(void *data);
1322 static void *do_monitor(void *data);
1323 static int restart_monitor(void);
1324 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1325 static void sip_destroy(struct sip_pvt *p);
1326 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1327 static int sip_refer_allocate(struct sip_pvt *p);
1328 static void ast_quiet_chan(struct ast_channel *chan);
1329 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1331 /*--- Device monitoring and Device/extension state handling */
1332 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1333 static int sip_devicestate(void *data);
1334 static int sip_poke_noanswer(void *data);
1335 static int sip_poke_peer(struct sip_peer *peer);
1336 static void sip_poke_all_peers(void);
1337 static void sip_peer_hold(struct sip_pvt *p, int hold);
1339 /*--- Applications, functions, CLI and manager command helpers */
1340 static const char *sip_nat_mode(const struct sip_pvt *p);
1341 static int sip_show_inuse(int fd, int argc, char *argv[]);
1342 static char *transfermode2str(enum transfermodes mode) attribute_const;
1343 static char *nat2str(int nat) attribute_const;
1344 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1345 static int sip_show_users(int fd, int argc, char *argv[]);
1346 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
1347 static int manager_sip_show_peers( struct mansession *s, struct message *m );
1348 static int sip_show_peers(int fd, int argc, char *argv[]);
1349 static int sip_show_objects(int fd, int argc, char *argv[]);
1350 static void print_group(int fd, ast_group_t group, int crlf);
1351 static const char *dtmfmode2str(int mode) attribute_const;
1352 static const char *insecure2str(int port, int invite) attribute_const;
1353 static void cleanup_stale_contexts(char *new, char *old);
1354 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1355 static const char *domain_mode_to_text(const enum domain_mode mode);
1356 static int sip_show_domains(int fd, int argc, char *argv[]);
1357 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1358 static int manager_sip_show_peer( struct mansession *s, struct message *m);
1359 static int sip_show_peer(int fd, int argc, char *argv[]);
1360 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1361 static int sip_show_user(int fd, int argc, char *argv[]);
1362 static int sip_show_registry(int fd, int argc, char *argv[]);
1363 static int sip_show_settings(int fd, int argc, char *argv[]);
1364 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1365 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1366 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1367 static int sip_show_channels(int fd, int argc, char *argv[]);
1368 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1369 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1370 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1371 static char *complete_sip_peer(const char *word, int state, int flags2);
1372 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1373 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1374 static char *complete_sip_user(const char *word, int state, int flags2);
1375 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1376 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1377 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1378 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1379 static int sip_show_channel(int fd, int argc, char *argv[]);
1380 static int sip_show_history(int fd, int argc, char *argv[]);
1381 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1382 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1383 static int sip_do_debug(int fd, int argc, char *argv[]);
1384 static int sip_no_debug(int fd, int argc, char *argv[]);
1385 static int sip_notify(int fd, int argc, char *argv[]);
1386 static int sip_do_history(int fd, int argc, char *argv[]);
1387 static int sip_no_history(int fd, int argc, char *argv[]);
1388 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1389 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1390 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1391 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1392 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1393 static int sip_addheader(struct ast_channel *chan, void *data);
1394 static int sip_do_reload(enum channelreloadreason reason);
1395 static int sip_reload(int fd, int argc, char *argv[]);
1398 Functions for enabling debug per IP or fully, or enabling history logging for
1401 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1402 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1403 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1404 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1405 static void sip_dump_history(struct sip_pvt *dialog);
1407 /*--- Device object handling */
1408 static struct sip_peer *temp_peer(const char *name);
1409 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1410 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1411 static int update_call_counter(struct sip_pvt *fup, int event);
1412 static void sip_destroy_peer(struct sip_peer *peer);
1413 static void sip_destroy_user(struct sip_user *user);
1414 static int sip_poke_peer(struct sip_peer *peer);
1415 static void set_peer_defaults(struct sip_peer *peer);
1416 static struct sip_peer *temp_peer(const char *name);
1417 static void register_peer_exten(struct sip_peer *peer, int onoff);
1418 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1419 static struct sip_user *find_user(const char *name, int realtime);
1420 static int sip_poke_peer_s(void *data);
1421 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1422 static void reg_source_db(struct sip_peer *peer);
1423 static void destroy_association(struct sip_peer *peer);
1424 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1426 /* Realtime device support */
1427 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1428 static struct sip_user *realtime_user(const char *username);
1429 static void update_peer(struct sip_peer *p, int expiry);
1430 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1431 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1433 /*--- Internal UA client handling (outbound registrations) */
1434 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1435 static void sip_registry_destroy(struct sip_registry *reg);
1436 static int sip_register(char *value, int lineno);
1437 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1438 static int sip_reregister(void *data);
1439 static int __sip_do_register(struct sip_registry *r);
1440 static int sip_reg_timeout(void *data);
1441 static void sip_send_all_registers(void);
1443 /*--- Parsing SIP requests and responses */
1444 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1445 static int determine_firstline_parts(struct sip_request *req);
1446 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1447 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1448 static int find_sip_method(const char *msg);
1449 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1450 static void parse_request(struct sip_request *req);
1451 static const char *get_header(const struct sip_request *req, const char *name);
1452 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1453 static int method_match(enum sipmethod id, const char *name);
1454 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1455 static char *get_in_brackets(char *tmp);
1456 static const char *find_alias(const char *name, const char *_default);
1457 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1458 static int lws2sws(char *msgbuf, int len);
1459 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1460 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1461 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1462 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1463 static int set_address_from_contact(struct sip_pvt *pvt);
1464 static void check_via(struct sip_pvt *p, struct sip_request *req);
1465 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1466 static int get_rpid_num(const char *input, char *output, int maxlen);
1467 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1468 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1469 static int get_msg_text(char *buf, int len, struct sip_request *req);
1470 static void free_old_route(struct sip_route *route);
1471 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1473 /*--- Constructing requests and responses */
1474 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1475 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1476 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1477 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1478 static int init_resp(struct sip_request *resp, const char *msg);
1479 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1480 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1481 static void build_via(struct sip_pvt *p);
1482 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1483 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1484 static char *generate_random_string(char *buf, size_t size);
1485 static void build_callid_pvt(struct sip_pvt *pvt);
1486 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1487 static void make_our_tag(char *tagbuf, size_t len);
1488 static int add_header(struct sip_request *req, const char *var, const char *value);
1489 static int add_header_contentLength(struct sip_request *req, int len);
1490 static int add_line(struct sip_request *req, const char *line);
1491 static int add_text(struct sip_request *req, const char *text);
1492 static int add_digit(struct sip_request *req, char digit);
1493 static int add_vidupdate(struct sip_request *req);
1494 static void add_route(struct sip_request *req, struct sip_route *route);
1495 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1496 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1497 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1498 static void set_destination(struct sip_pvt *p, char *uri);
1499 static void append_date(struct sip_request *req);
1500 static void build_contact(struct sip_pvt *p);
1501 static void build_rpid(struct sip_pvt *p);
1503 /*------Request handling functions */
1504 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1505 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);
1506 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1507 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1508 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1509 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1510 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1511 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1512 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1513 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1514 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1515 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1516 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1517 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1519 /*------Response handling functions */
1520 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1521 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1522 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1523 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1525 /*----- RTP interface functions */
1526 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1527 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1528 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1529 static int sip_get_codec(struct ast_channel *chan);
1530 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1532 /*------ T38 Support --------- */
1533 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1534 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1535 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1536 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1538 /*! \brief Definition of this channel for PBX channel registration */
1539 static const struct ast_channel_tech sip_tech = {
1541 .description = "Session Initiation Protocol (SIP)",
1542 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1543 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1544 .requester = sip_request_call,
1545 .devicestate = sip_devicestate,
1547 .hangup = sip_hangup,
1548 .answer = sip_answer,
1551 .write_video = sip_write,
1552 .indicate = sip_indicate,
1553 .transfer = sip_transfer,
1555 .send_digit_begin = sip_senddigit_begin,
1556 .send_digit_end = sip_senddigit_end,
1557 .bridge = ast_rtp_bridge,
1558 .early_bridge = ast_rtp_early_bridge,
1559 .send_text = sip_sendtext,
1562 /**--- some list management macros. **/
1564 #define UNLINK(element, head, prev) do { \
1566 (prev)->next = (element)->next; \
1568 (head) = (element)->next; \
1571 /*! \brief Interface structure with callbacks used to connect to RTP module */
1572 static struct ast_rtp_protocol sip_rtp = {
1574 get_rtp_info: sip_get_rtp_peer,
1575 get_vrtp_info: sip_get_vrtp_peer,
1576 set_rtp_peer: sip_set_rtp_peer,
1577 get_codec: sip_get_codec,
1581 * Helper functions to lock/unlock pvt, hiding the
1582 * underlying locking mechanism.
1584 static void sip_pvt_lock(struct sip_pvt *pvt)
1586 ast_mutex_lock(&pvt->pvt_lock);
1589 static void sip_pvt_unlock(struct sip_pvt *pvt)
1591 ast_mutex_unlock(&pvt->pvt_lock);
1595 * helper functions to unreference various types of objects.
1596 * By handling them this way, we don't have to declare the
1597 * destructor on each call, which removes the chance of errors.
1599 static void unref_peer(struct sip_peer *peer)
1601 ASTOBJ_UNREF(peer, sip_destroy_peer);
1604 static void unref_user(struct sip_user *user)
1606 ASTOBJ_UNREF(user, sip_destroy_user);
1609 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1610 static struct ast_udptl_protocol sip_udptl = {
1612 get_udptl_info: sip_get_udptl_peer,
1613 set_udptl_peer: sip_set_udptl_peer,
1616 /*! \brief Convert transfer status to string */
1617 static const char *referstatus2str(enum referstatus rstatus)
1619 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1622 for (x = 0; x < i; x++) {
1623 if (referstatusstrings[x].status == rstatus)
1624 return referstatusstrings[x].text;
1629 /*! \brief Initialize the initital request packet in the pvt structure.
1630 This packet is used for creating replies and future requests in
1632 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1634 if (p->initreq.headers && option_debug) {
1635 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1637 /* Use this as the basis */
1638 copy_request(&p->initreq, req);
1639 parse_request(&p->initreq);
1640 if (ast_test_flag(req, SIP_PKT_DEBUG))
1641 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1645 /*! \brief returns true if 'name' (with optional trailing whitespace)
1646 * matches the sip method 'id'.
1647 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1648 * a case-insensitive comparison to be more tolerant.
1649 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1651 static int method_match(enum sipmethod id, const char *name)
1653 int len = strlen(sip_methods[id].text);
1654 int l_name = name ? strlen(name) : 0;
1655 /* true if the string is long enough, and ends with whitespace, and matches */
1656 return (l_name >= len && name[len] < 33 &&
1657 !strncasecmp(sip_methods[id].text, name, len));
1660 /*! \brief find_sip_method: Find SIP method from header */
1661 static int find_sip_method(const char *msg)
1665 if (ast_strlen_zero(msg))
1667 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1668 if (method_match(i, msg))
1669 res = sip_methods[i].id;
1674 /*! \brief Parse supported header in incoming packet */
1675 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1679 unsigned int profile = 0;
1682 if (ast_strlen_zero(supported) )
1684 temp = ast_strdupa(supported);
1686 if (option_debug > 2 && sipdebug)
1687 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1689 for (next = temp; next; next = sep) {
1691 if ( (sep = strchr(next, ',')) != NULL)
1693 next = ast_skip_blanks(next);
1694 if (option_debug > 2 && sipdebug)
1695 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1696 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1697 if (!strcasecmp(next, sip_options[i].text)) {
1698 profile |= sip_options[i].id;
1700 if (option_debug > 2 && sipdebug)
1701 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1705 if (!found && option_debug > 2 && sipdebug) {
1706 if (!strncasecmp(next, "x-", 2))
1707 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1709 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1714 pvt->sipoptions = profile;
1718 /*! \brief See if we pass debug IP filter */
1719 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1723 if (debugaddr.sin_addr.s_addr) {
1724 if (((ntohs(debugaddr.sin_port) != 0)
1725 && (debugaddr.sin_port != addr->sin_port))
1726 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1732 /*! \brief The real destination address for a write */
1733 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1735 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1738 /*! \brief Display SIP nat mode */
1739 static const char *sip_nat_mode(const struct sip_pvt *p)
1741 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1744 /*! \brief Test PVT for debugging output */
1745 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1749 return sip_debug_test_addr(sip_real_dst(p));
1752 /*! \brief Transmit SIP message */
1753 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1756 const struct sockaddr_in *dst = sip_real_dst(p);
1757 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1760 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));
1765 /*! \brief Build a Via header for a request */
1766 static void build_via(struct sip_pvt *p)
1768 /* Work around buggy UNIDEN UIP200 firmware */
1769 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1771 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1772 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1773 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1776 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1778 * Using the localaddr structure built up with localnet statements in sip.conf
1779 * apply it to their address to see if we need to substitute our
1780 * externip or can get away with our internal bindaddr
1782 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1784 struct sockaddr_in theirs, ours;
1786 /* Get our local information */
1787 ast_ouraddrfor(them, us);
1788 theirs.sin_addr = *them;
1789 ours.sin_addr = *us;
1791 if (localaddr && externip.sin_addr.s_addr &&
1792 ast_apply_ha(localaddr, &theirs) &&
1793 !ast_apply_ha(localaddr, &ours)) {
1794 if (externexpire && time(NULL) >= externexpire) {
1795 struct ast_hostent ahp;
1798 externexpire = time(NULL) + externrefresh;
1799 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1800 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1802 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1804 *us = externip.sin_addr;
1806 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1807 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1809 } else if (bindaddr.sin_addr.s_addr)
1810 *us = bindaddr.sin_addr;
1814 /*! \brief Append to SIP dialog history
1815 \return Always returns 0 */
1816 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1818 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1819 __attribute__ ((format (printf, 2, 3)));
1821 /*! \brief Append to SIP dialog history with arg list */
1822 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1824 char buf[80], *c = buf; /* max history length */
1825 struct sip_history *hist;
1828 vsnprintf(buf, sizeof(buf), fmt, ap);
1829 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1830 l = strlen(buf) + 1;
1831 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1833 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1837 memcpy(hist->event, buf, l);
1838 AST_LIST_INSERT_TAIL(p->history, hist, list);
1841 /*! \brief Append to SIP dialog history with arg list */
1842 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1849 append_history_va(p, fmt, ap);
1855 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1856 static int retrans_pkt(void *data)
1858 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1859 int reschedule = DEFAULT_RETRANS;
1861 /* Lock channel PVT */
1862 sip_pvt_lock(pkt->owner);
1864 if (pkt->retrans < MAX_RETRANS) {
1866 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1867 if (sipdebug && option_debug > 3)
1868 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);
1872 if (sipdebug && option_debug > 3)
1873 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1877 pkt->timer_a = 2 * pkt->timer_a;
1879 /* For non-invites, a maximum of 4 secs */
1880 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1881 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1884 /* Reschedule re-transmit */
1885 reschedule = siptimer_a;
1886 if (option_debug > 3)
1887 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);
1890 if (sip_debug_test_pvt(pkt->owner)) {
1891 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1892 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1893 pkt->retrans, sip_nat_mode(pkt->owner),
1894 ast_inet_ntoa(dst->sin_addr),
1895 ntohs(dst->sin_port), pkt->data);
1898 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1899 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1900 sip_pvt_unlock(pkt->owner);
1903 /* Too many retries */
1904 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1905 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1906 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");
1908 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1909 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1911 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1913 pkt->retransid = -1;
1915 if (ast_test_flag(pkt, FLAG_FATAL)) {
1916 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1917 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
1919 sip_pvt_lock(pkt->owner);
1921 if (pkt->owner->owner) {
1922 ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1923 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1924 ast_queue_hangup(pkt->owner->owner);
1925 ast_channel_unlock(pkt->owner->owner);
1927 /* If no channel owner, destroy now */
1928 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1931 /* In any case, go ahead and remove the packet */
1932 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1938 prev->next = cur->next;
1940 pkt->owner->packets = cur->next;
1941 sip_pvt_unlock(pkt->owner);
1945 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1947 sip_pvt_unlock(pkt->owner);
1951 /*! \brief Transmit packet with retransmits
1952 \return 0 on success, -1 on failure to allocate packet
1954 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1956 struct sip_pkt *pkt;
1957 int siptimer_a = DEFAULT_RETRANS;
1959 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1961 memcpy(pkt->data, data, len);
1962 pkt->method = sipmethod;
1963 pkt->packetlen = len;
1964 pkt->next = p->packets;
1968 ast_set_flag(pkt, FLAG_RESPONSE);
1969 pkt->data[len] = '\0';
1970 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1972 ast_set_flag(pkt, FLAG_FATAL);
1974 siptimer_a = pkt->timer_t1 * 2;
1976 /* Schedule retransmission */
1977 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1978 if (option_debug > 3 && sipdebug)
1979 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1980 pkt->next = p->packets;
1983 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1984 if (sipmethod == SIP_INVITE) {
1985 /* Note this is a pending invite */
1986 p->pendinginvite = seqno;
1991 /*! \brief Kill a SIP dialog (called by scheduler) */
1992 static int __sip_autodestruct(void *data)
1994 struct sip_pvt *p = data;
1996 /* If this is a subscription, tell the phone that we got a timeout */
1997 if (p->subscribed) {
1998 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
1999 p->subscribed = NONE;
2000 append_history(p, "Subscribestatus", "timeout");
2001 if (option_debug > 2)
2002 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2003 return 10000; /* Reschedule this destruction so that we know that it's gone */
2006 if (p->subscribed == MWI_NOTIFICATION)
2008 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2010 /* Reset schedule ID */
2014 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2015 append_history(p, "AutoDestroy", "%s", p->callid);
2017 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2018 ast_queue_hangup(p->owner);
2019 } else if (p->refer)
2020 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2026 /*! \brief Schedule destruction of SIP dialog */
2027 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2030 if (p->timer_t1 == 0)
2031 p->timer_t1 = SIP_TIMER_T1; /* Set timer T1 if not set (RFC 3261) */
2032 ms = p->timer_t1 * 64;
2034 if (sip_debug_test_pvt(p))
2035 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2036 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2037 append_history(p, "SchedDestroy", "%d ms", ms);
2039 if (p->autokillid > -1)
2040 ast_sched_del(sched, p->autokillid);
2041 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2044 /*! \brief Cancel destruction of SIP dialog */
2045 static void sip_cancel_destroy(struct sip_pvt *p)
2047 if (p->autokillid > -1) {
2048 ast_sched_del(sched, p->autokillid);
2049 append_history(p, "CancelDestroy", "");
2054 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2055 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
2057 struct sip_pkt *cur, *prev = NULL;
2059 /* Just in case... */
2063 msg = sip_methods[sipmethod].text;
2066 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2067 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2068 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2069 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2070 if (!resp && (seqno == p->pendinginvite)) {
2072 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2073 p->pendinginvite = 0;
2075 /* this is our baby */
2077 UNLINK(cur, p->packets, prev);
2078 if (cur->retransid > -1) {
2079 if (sipdebug && option_debug > 3)
2080 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2081 ast_sched_del(sched, cur->retransid);
2090 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2093 /*! \brief Pretend to ack all packets
2094 * maybe the lock on p is not strictly necessary but there might be a race */
2095 static void __sip_pretend_ack(struct sip_pvt *p)
2097 struct sip_pkt *cur = NULL;
2099 while (p->packets) {
2101 if (cur == p->packets) {
2102 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2106 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2107 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method, FALSE);
2111 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2112 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2114 struct sip_pkt *cur;
2117 for (cur = p->packets; cur; cur = cur->next) {
2118 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2119 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2120 /* this is our baby */
2121 if (cur->retransid > -1) {
2122 if (option_debug > 3 && sipdebug)
2123 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2124 ast_sched_del(sched, cur->retransid);
2126 cur->retransid = -1;
2132 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");
2137 /*! \brief Copy SIP request, parse it */
2138 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2140 memset(dst, 0, sizeof(*dst));
2141 memcpy(dst->data, src->data, sizeof(dst->data));
2142 dst->len = src->len;
2146 /*! \brief add a blank line if no body */
2147 static void add_blank(struct sip_request *req)
2150 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2151 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2152 req->len += strlen(req->data + req->len);
2156 /*! \brief Transmit response on SIP request*/
2157 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2162 if (sip_debug_test_pvt(p)) {
2163 const struct sockaddr_in *dst = sip_real_dst(p);
2165 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2166 reliable ? "Reliably " : "", sip_nat_mode(p),
2167 ast_inet_ntoa(dst->sin_addr),
2168 ntohs(dst->sin_port), req->data);
2170 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2171 struct sip_request tmp;
2172 parse_copy(&tmp, req);
2173 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2174 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2177 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2178 __sip_xmit(p, req->data, req->len);
2184 /*! \brief Send SIP Request to the other part of the dialogue */
2185 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2190 if (sip_debug_test_pvt(p)) {
2191 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2192 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);
2194 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);
2196 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2197 struct sip_request tmp;
2198 parse_copy(&tmp, req);
2199 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2202 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2203 __sip_xmit(p, req->data, req->len);
2207 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2208 * optionally with a limit on the search.
2209 * start must be past the first quote.
2211 static const char *find_closing_quote(const char *start, const char *lim)
2213 char last_char = '\0';
2215 for (s = start; *s && s != lim; last_char = *s++) {
2216 if (*s == '"' && last_char != '\\')
2222 /*! \brief Pick out text in brackets from character string
2223 \return pointer to terminated stripped string
2224 \param tmp input string that will be modified
2227 "foo" <bar> valid input, returns bar
2228 foo returns the whole string
2229 < "foo ... > returns the string between brackets
2230 < "foo... bogus (missing closing bracket), returns the whole string
2231 XXX maybe should still skip the opening bracket
2233 static char *get_in_brackets(char *tmp)
2235 const char *parse = tmp;
2236 char *first_bracket;
2239 * Skip any quoted text until we find the part in brackets.
2240 * On any error give up and return the full string.
2242 while ( (first_bracket = strchr(parse, '<')) ) {
2243 char *first_quote = strchr(parse, '"');
2245 if (!first_quote || first_quote > first_bracket)
2246 break; /* no need to look at quoted part */
2247 /* the bracket is within quotes, so ignore it */
2248 parse = find_closing_quote(first_quote + 1, NULL);
2249 if (!*parse) { /* not found, return full string ? */
2250 /* XXX or be robust and return in-bracket part ? */
2251 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2256 if (first_bracket) {
2257 char *second_bracket = strchr(first_bracket + 1, '>');
2258 if (second_bracket) {
2259 *second_bracket = '\0';
2260 tmp = first_bracket + 1;
2262 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2269 * parses a URI in its components.
2270 * If scheme is specified, drop it from the top.
2271 * If a component is not requested, do not split around it.
2272 * This means that if we don't have domain, we cannot split
2273 * name:pass and domain:port.
2274 * It is safe to call with ret_name, pass, domain, port
2275 * pointing all to the same place.
2276 * Init pointers to empty string so we never get NULL dereferencing.
2277 * Overwrites the string.
2278 * return 0 on success, other values on error.
2280 static int parse_uri(char *uri, char *scheme,
2281 char **ret_name, char **pass, char **domain, char **port, char **options)
2286 /* init field as required */
2291 name = strsep(&uri, ";"); /* remove options */
2293 int l = strlen(scheme);
2294 if (!strncmp(name, scheme, l))
2297 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, name);
2302 /* if we don't want to split around domain, keep everything as a name,
2303 * so we need to do nothing here, except remember why.
2306 /* store the result in a temp. variable to avoid it being
2307 * overwritten if arguments point to the same place.
2311 if ((c = strchr(name, '@')) == NULL) {
2312 /* domain-only URI, according to the SIP RFC. */
2319 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2323 if (pass && (c = strchr(name, ':'))) { /* user:password */
2329 if (ret_name) /* same as for domain, store the result only at the end */
2332 *options = uri ? uri : "";
2337 /*! \brief Send SIP MESSAGE text within a call
2338 Called from PBX core sendtext() application */
2339 static int sip_sendtext(struct ast_channel *ast, const char *text)
2341 struct sip_pvt *p = ast->tech_pvt;
2342 int debug = sip_debug_test_pvt(p);
2345 ast_verbose("Sending text %s on %s\n", text, ast->name);
2348 if (ast_strlen_zero(text))
2351 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2352 transmit_message_with_text(p, text);
2356 /*! \brief Update peer object in realtime storage
2357 If the Asterisk system name is set in asterisk.conf, we will use
2358 that name and store that in the "regserver" field in the sippeers
2359 table to facilitate multi-server setups.
2361 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2364 char ipaddr[INET_ADDRSTRLEN];
2365 char regseconds[20];
2367 char *sysname = ast_config_AST_SYSTEM_NAME;
2368 char *syslabel = NULL;
2370 time_t nowtime = time(NULL) + expirey;
2371 const char *fc = fullcontact ? "fullcontact" : NULL;
2373 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2374 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2375 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2377 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2379 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2380 syslabel = "regserver";
2383 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2384 "port", port, "regseconds", regseconds,
2385 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2387 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2388 "port", port, "regseconds", regseconds,
2389 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2392 /*! \brief Automatically add peer extension to dial plan */
2393 static void register_peer_exten(struct sip_peer *peer, int onoff)
2396 char *stringp, *ext, *context;
2398 /* XXX note that global_regcontext is both a global 'enable' flag and
2399 * the name of the global regexten context, if not specified
2402 if (ast_strlen_zero(global_regcontext))
2405 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2407 while ((ext = strsep(&stringp, "&"))) {
2408 if ((context = strchr(ext, '@'))) {
2409 *context++ = '\0'; /* split ext@context */
2410 if (!ast_context_find(context)) {
2411 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2415 context = global_regcontext;
2418 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2419 ast_strdup(peer->name), ast_free, "SIP");
2421 ast_context_remove_extension(context, ext, 1, NULL);
2425 /*! \brief Destroy peer object from memory */
2426 static void sip_destroy_peer(struct sip_peer *peer)
2428 if (option_debug > 2)
2429 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2431 /* Delete it, it needs to disappear */
2433 sip_destroy(peer->call);
2435 if (peer->mwipvt) /* We have an active subscription, delete it */
2436 sip_destroy(peer->mwipvt);
2438 if (peer->chanvars) {
2439 ast_variables_destroy(peer->chanvars);
2440 peer->chanvars = NULL;
2442 if (peer->expire > -1)
2443 ast_sched_del(sched, peer->expire);
2444 if (peer->pokeexpire > -1)
2445 ast_sched_del(sched, peer->pokeexpire);
2446 register_peer_exten(peer, FALSE);
2447 ast_free_ha(peer->ha);
2448 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2450 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2454 clear_realm_authentication(peer->auth);
2457 ast_dnsmgr_release(peer->dnsmgr);
2461 /*! \brief Update peer data in database (if used) */
2462 static void update_peer(struct sip_peer *p, int expiry)
2464 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2465 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2466 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2467 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2472 /*! \brief realtime_peer: Get peer from realtime storage
2473 * Checks the "sippeers" realtime family from extconfig.conf
2474 * \todo Consider adding check of port address when matching here to follow the same
2475 * algorithm as for static peers. Will we break anything by adding that?
2477 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2479 struct sip_peer *peer;
2480 struct ast_variable *var = NULL;
2481 struct ast_variable *tmp;
2482 char ipaddr[INET_ADDRSTRLEN];
2484 /* First check on peer name */
2486 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2487 else if (sin) { /* Then check on IP address for dynamic peers */
2488 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2489 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2491 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */
2497 for (tmp = var; tmp; tmp = tmp->next) {
2498 /* If this is type=user, then skip this object. */
2499 if (!strcasecmp(tmp->name, "type") &&
2500 !strcasecmp(tmp->value, "user")) {
2501 ast_variables_destroy(var);
2503 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2504 newpeername = tmp->value;
2508 if (!newpeername) { /* Did not find peer in realtime */
2509 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2510 ast_variables_destroy(var);
2514 /* Peer found in realtime, now build it in memory */
2515 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2517 ast_variables_destroy(var);
2521 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2523 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2524 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2525 if (peer->expire > -1) {
2526 ast_sched_del(sched, peer->expire);
2528 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2530 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2532 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2534 ast_variables_destroy(var);
2539 /*! \brief Support routine for find_peer */
2540 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2542 /* We know name is the first field, so we can cast */
2543 struct sip_peer *p = (struct sip_peer *) name;
2544 return !(!inaddrcmp(&p->addr, sin) ||
2545 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2546 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2549 /*! \brief Locate peer by name or ip address
2550 * This is used on incoming SIP message to find matching peer on ip
2551 or outgoing message to find matching peer on name */
2552 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2554 struct sip_peer *p = NULL;
2557 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2559 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2562 p = realtime_peer(peer, sin);
2567 /*! \brief Remove user object from in-memory storage */
2568 static void sip_destroy_user(struct sip_user *user)
2570 if (option_debug > 2)
2571 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2572 ast_free_ha(user->ha);
2573 if (user->chanvars) {
2574 ast_variables_destroy(user->chanvars);
2575 user->chanvars = NULL;
2577 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2584 /*! \brief Load user from realtime storage
2585 * Loads user from "sipusers" category in realtime (extconfig.conf)
2586 * Users are matched on From: user name (the domain in skipped) */
2587 static struct sip_user *realtime_user(const char *username)
2589 struct ast_variable *var;
2590 struct ast_variable *tmp;
2591 struct sip_user *user = NULL;
2593 var = ast_load_realtime("sipusers", "name", username, NULL);
2598 for (tmp = var; tmp; tmp = tmp->next) {
2599 if (!strcasecmp(tmp->name, "type") &&
2600 !strcasecmp(tmp->value, "peer")) {
2601 ast_variables_destroy(var);
2606 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2608 if (!user) { /* No user found */
2609 ast_variables_destroy(var);
2613 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2614 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2616 ASTOBJ_CONTAINER_LINK(&userl,user);
2618 /* Move counter from s to r... */
2621 ast_set_flag(&user->flags[0], SIP_REALTIME);
2623 ast_variables_destroy(var);
2627 /*! \brief Locate user by name
2628 * Locates user by name (From: sip uri user name part) first
2629 * from in-memory list (static configuration) then from
2630 * realtime storage (defined in extconfig.conf) */
2631 static struct sip_user *find_user(const char *name, int realtime)
2633 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2635 u = realtime_user(name);
2639 /*! \brief Set nat mode on the various data sockets */
2640 static void do_setnat(struct sip_pvt *p, int natflags)
2642 const char *mode = natflags ? "On" : "Off";
2646 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2647 ast_rtp_setnat(p->rtp, natflags);
2651 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2652 ast_rtp_setnat(p->vrtp, natflags);
2656 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2657 ast_udptl_setnat(p->udptl, natflags);
2661 /*! \brief Create address structure from peer reference.
2662 * return -1 on error, 0 on success.
2664 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2666 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2667 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2668 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2669 dialog->recv = dialog->sa;
2673 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2674 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2675 dialog->capability = peer->capability;
2676 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && dialog->vrtp) {
2677 ast_rtp_destroy(dialog->vrtp);
2678 dialog->vrtp = NULL;
2680 dialog->prefs = peer->prefs;
2681 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2682 dialog->t38.capability = global_t38_capability;
2683 if (dialog->udptl) {
2684 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2685 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2686 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2687 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2688 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2689 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2690 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2691 if (option_debug > 1)
2692 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2694 dialog->t38.jointcapability = dialog->t38.capability;
2695 } else if (dialog->udptl) {
2696 ast_udptl_destroy(dialog->udptl);
2697 dialog->udptl = NULL;
2699 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2702 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2703 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2706 ast_rtp_setdtmf(dialog->vrtp, 0);
2707 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2710 /* Set Frame packetization */
2712 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2713 dialog->autoframing = peer->autoframing;
2715 ast_string_field_set(dialog, peername, peer->username);
2716 ast_string_field_set(dialog, authname, peer->username);
2717 ast_string_field_set(dialog, username, peer->username);
2718 ast_string_field_set(dialog, peersecret, peer->secret);
2719 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2720 ast_string_field_set(dialog, tohost, peer->tohost);
2721 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2722 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2725 tmpcall = ast_strdupa(dialog->callid);
2726 c = strchr(tmpcall, '@');
2729 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2732 if (ast_strlen_zero(dialog->tohost))
2733 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2734 if (!ast_strlen_zero(peer->fromdomain))
2735 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2736 if (!ast_strlen_zero(peer->fromuser))
2737 ast_string_field_set(dialog, fromuser, peer->fromuser);
2738 dialog->callgroup = peer->callgroup;
2739 dialog->pickupgroup = peer->pickupgroup;
2740 dialog->allowtransfer = peer->allowtransfer;
2741 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2742 /* Minimum is settable or default to 100 ms */
2743 if (peer->maxms && peer->lastms)
2744 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2745 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2746 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2747 dialog->noncodeccapability |= AST_RTP_DTMF;
2749 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2750 ast_string_field_set(dialog, context, peer->context);
2751 dialog->rtptimeout = peer->rtptimeout;
2752 dialog->rtpholdtimeout = peer->rtpholdtimeout;
2753 dialog->rtpkeepalive = peer->rtpkeepalive;
2754 if (peer->call_limit)
2755 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2756 dialog->maxcallbitrate = peer->maxcallbitrate;
2761 /*! \brief create address structure from peer name
2762 * Or, if peer not found, find it in the global DNS
2763 * returns TRUE (-1) on failure, FALSE on success */
2764 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2767 struct ast_hostent ahp;
2768 struct sip_peer *peer;
2771 char host[MAXHOSTNAMELEN], *hostn;
2774 ast_copy_string(peername, opeer, sizeof(peername));
2775 port = strchr(peername, ':');
2778 dialog->sa.sin_family = AF_INET;
2779 dialog->timer_t1 = SIP_TIMER_T1; /* Default SIP retransmission timer T1 (RFC 3261) */
2780 peer = find_peer(peername, NULL, 1);
2783 int res = create_addr_from_peer(dialog, peer);
2788 portno = port ? atoi(port) : STANDARD_SIP_PORT;
2789 if (global_srvlookup) {
2790 char service[MAXHOSTNAMELEN];
2794 snprintf(service, sizeof(service), "_sip._udp.%s", peername);
2795 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2801 hp = ast_gethostbyname(hostn, &ahp);
2803 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2806 ast_string_field_set(dialog, tohost, peername);
2807 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2808 dialog->sa.sin_port = htons(portno);
2809 dialog->recv = dialog->sa;
2813 /*! \brief Scheduled congestion on a call */
2814 static int auto_congest(void *nothing)
2816 struct sip_pvt *p = nothing;
2821 /* XXX fails on possible deadlock */
2822 if (!ast_channel_trylock(p->owner)) {
2823 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2824 append_history(p, "Cong", "Auto-congesting (timer)");
2825 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2826 ast_channel_unlock(p->owner);
2834 /*! \brief Initiate SIP call from PBX
2835 * used from the dial() application */
2836 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2840 struct varshead *headp;
2841 struct ast_var_t *current;
2842 const char *referer = NULL; /* SIP refererer */
2845 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2846 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2850 /* Check whether there is vxml_url, distinctive ring variables */
2851 headp=&ast->varshead;
2852 AST_LIST_TRAVERSE(headp,current,entries) {
2853 /* Check whether there is a VXML_URL variable */
2854 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2855 p->options->vxml_url = ast_var_value(current);
2856 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2857 p->options->uri_options = ast_var_value(current);
2858 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2859 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2860 p->options->addsipheaders = 1;
2861 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2862 /* This is a transfered call */
2863 p->options->transfer = 1;
2864 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2865 /* This is the referer */
2866 referer = ast_var_value(current);
2867 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2868 /* We're replacing a call. */
2869 p->options->replaces = ast_var_value(current);
2870 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2871 p->t38.state = T38_LOCAL_DIRECT;
2873 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2879 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2881 if (p->options->transfer) {
2885 if (sipdebug && option_debug > 2)
2886 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2887 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2889 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2890 ast_string_field_set(p, cid_name, buf);
2893 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2895 res = update_call_counter(p, INC_CALL_RINGING);
2897 p->callingpres = ast->cid.cid_pres;
2898 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
2900 /* If there are no audio formats left to offer, punt */
2901 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
2902 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
2905 p->t38.jointcapability = p->t38.capability;
2906 if (option_debug > 1)
2907 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2908 transmit_invite(p, SIP_INVITE, 1, 2);
2910 /* Initialize auto-congest time */
2911 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2917 /*! \brief Destroy registry object
2918 Objects created with the register= statement in static configuration */
2919 static void sip_registry_destroy(struct sip_registry *reg)
2922 if (option_debug > 2)
2923 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2926 /* Clear registry before destroying to ensure
2927 we don't get reentered trying to grab the registry lock */
2928 reg->call->registry = NULL;
2929 if (option_debug > 2)
2930 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2931 sip_destroy(reg->call);
2933 if (reg->expire > -1)
2934 ast_sched_del(sched, reg->expire);
2935 if (reg->timeout > -1)
2936 ast_sched_del(sched, reg->timeout);
2937 ast_string_field_free_pools(reg);
2943 /*! \brief Execute destruction of SIP dialog structure, release memory */
2944 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
2946 struct sip_pvt *cur, *prev = NULL;
2949 if (sip_debug_test_pvt(p) || option_debug > 2)
2950 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2952 /* Remove link from peer to subscription of MWI */
2953 if (p->relatedpeer && p->relatedpeer->mwipvt)
2954 p->relatedpeer->mwipvt = NULL;
2957 sip_dump_history(p);
2962 if (p->stateid > -1)
2963 ast_extension_state_del(p->stateid, NULL);
2965 ast_sched_del(sched, p->initid);
2966 if (p->autokillid > -1)
2967 ast_sched_del(sched, p->autokillid);
2970 ast_rtp_destroy(p->rtp);
2972 ast_rtp_destroy(p->vrtp);
2974 ast_udptl_destroy(p->udptl);
2978 free_old_route(p->route);
2982 if (p->registry->call == p)
2983 p->registry->call = NULL;
2984 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2987 /* Unlink us from the owner if we have one */
2990 ast_channel_lock(p->owner);
2992 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2993 p->owner->tech_pvt = NULL;
2995 ast_channel_unlock(p->owner);
2999 struct sip_history *hist;
3000 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
3006 /* Lock dialog list before removing ourselves from the list */
3009 for (prev = NULL, cur = dialoglist; cur; prev = cur, cur = cur->next) {
3011 UNLINK(cur, dialoglist, prev);
3016 dialoglist_unlock();
3018 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
3022 /* remove all current packets in this dialog */
3023 while((cp = p->packets)) {
3024 p->packets = p->packets->next;
3025 if (cp->retransid > -1)
3026 ast_sched_del(sched, cp->retransid);
3030 ast_variables_destroy(p->chanvars);
3033 ast_mutex_destroy(&p->pvt_lock);
3035 ast_string_field_free_pools(p);
3040 /*! \brief update_call_counter: Handle call_limit for SIP users
3041 * Setting a call-limit will cause calls above the limit not to be accepted.
3043 * Remember that for a type=friend, there's one limit for the user and
3044 * another for the peer, not a combined call limit.
3045 * This will cause unexpected behaviour in subscriptions, since a "friend"
3046 * is *two* devices in Asterisk, not one.
3048 * Thought: For realtime, we should propably update storage with inuse counter...
3050 * \return 0 if call is ok (no call limit, below treshold)
3051 * -1 on rejection of call
3054 static int update_call_counter(struct sip_pvt *fup, int event)