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
36 * \ingroup channel_drivers
45 #include <sys/socket.h>
46 #include <sys/ioctl.h>
53 #include <sys/signal.h>
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <arpa/inet.h>
57 #include <netinet/ip.h>
62 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
64 #include "asterisk/lock.h"
65 #include "asterisk/channel.h"
66 #include "asterisk/config.h"
67 #include "asterisk/logger.h"
68 #include "asterisk/module.h"
69 #include "asterisk/pbx.h"
70 #include "asterisk/options.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/sched.h"
73 #include "asterisk/io.h"
74 #include "asterisk/rtp.h"
75 #include "asterisk/acl.h"
76 #include "asterisk/manager.h"
77 #include "asterisk/callerid.h"
78 #include "asterisk/cli.h"
79 #include "asterisk/app.h"
80 #include "asterisk/musiconhold.h"
81 #include "asterisk/dsp.h"
82 #include "asterisk/features.h"
83 #include "asterisk/acl.h"
84 #include "asterisk/srv.h"
85 #include "asterisk/astdb.h"
86 #include "asterisk/causes.h"
87 #include "asterisk/utils.h"
88 #include "asterisk/file.h"
89 #include "asterisk/astobj.h"
90 #include "asterisk/dnsmgr.h"
91 #include "asterisk/devicestate.h"
92 #include "asterisk/linkedlists.h"
93 #include "asterisk/stringfields.h"
94 #include "asterisk/monitor.h"
104 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
105 #ifndef IPTOS_MINCOST
106 #define IPTOS_MINCOST 0x02
109 /* #define VOCAL_DATA_HACK */
111 #define DEFAULT_DEFAULT_EXPIRY 120
112 #define DEFAULT_MIN_EXPIRY 60
113 #define DEFAULT_MAX_EXPIRY 3600
114 #define DEFAULT_REGISTRATION_TIMEOUT 20
115 #define DEFAULT_MAX_FORWARDS "70"
117 /* guard limit must be larger than guard secs */
118 /* guard min must be < 1000, and should be >= 250 */
119 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
120 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
122 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
123 GUARD_PCT turns out to be lower than this, it
124 will use this time instead.
125 This is in milliseconds. */
126 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
127 below EXPIRY_GUARD_LIMIT */
128 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
130 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
131 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
132 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
133 static int expiry = DEFAULT_EXPIRY;
136 #define MAX(a,b) ((a) > (b) ? (a) : (b))
139 #define CALLERID_UNKNOWN "Unknown"
141 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
142 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
143 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
145 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
146 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
147 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
149 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
150 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
151 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
153 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
155 static const char desc[] = "Session Initiation Protocol (SIP)";
156 static const char config[] = "sip.conf";
157 static const char notify_config[] = "sip_notify.conf";
158 static int usecnt = 0;
164 /* Do _NOT_ make any changes to this enum, or the array following it;
165 if you think you are doing the right thing, you are probably
166 not doing the right thing. If you think there are changes
167 needed, get someone else to review them first _before_
168 submitting a patch. If these two lists do not match properly
169 bad things will happen.
173 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
174 If it fails, it's critical and will cause a teardown of the session */
175 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
176 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
179 enum subscriptiontype {
189 static const struct cfsubscription_types {
190 enum subscriptiontype type;
191 const char * const event;
192 const char * const mediatype;
193 const char * const text;
194 } subscription_types[] = {
195 { NONE, "-", "unknown", "unknown" },
196 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
197 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
198 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
199 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
200 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
201 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* Mailbox notification */
228 /* States for outbound registrations (with register= lines in sip.conf */
229 enum sipregistrystate {
230 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
231 REG_STATE_REGSENT, /*!< Registration request sent */
232 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
233 REG_STATE_REGISTERED, /*!< Registred and done */
234 REG_STATE_REJECTED, /*!< Registration rejected */
235 REG_STATE_TIMEOUT, /*!< Registration timed out */
236 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
237 REG_STATE_FAILED, /*!< Registration failed after several tries */
241 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
242 static const struct cfsip_methods {
244 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
247 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
248 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
249 { SIP_REGISTER, NO_RTP, "REGISTER" },
250 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
251 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
252 { SIP_INVITE, RTP, "INVITE" },
253 { SIP_ACK, NO_RTP, "ACK" },
254 { SIP_PRACK, NO_RTP, "PRACK" },
255 { SIP_BYE, NO_RTP, "BYE" },
256 { SIP_REFER, NO_RTP, "REFER" },
257 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
258 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
259 { SIP_UPDATE, NO_RTP, "UPDATE" },
260 { SIP_INFO, NO_RTP, "INFO" },
261 { SIP_CANCEL, NO_RTP, "CANCEL" },
262 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
265 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
266 static const struct cfalias {
267 char * const fullname;
268 char * const shortname;
270 { "Content-Type", "c" },
271 { "Content-Encoding", "e" },
275 { "Content-Length", "l" },
278 { "Supported", "k" },
280 { "Referred-By", "b" },
281 { "Allow-Events", "u" },
284 { "Accept-Contact", "a" },
285 { "Reject-Contact", "j" },
286 { "Request-Disposition", "d" },
287 { "Session-Expires", "x" },
290 /*! Define SIP option tags, used in Require: and Supported: headers
291 We need to be aware of these properties in the phones to use
292 the replace: header. We should not do that without knowing
293 that the other end supports it...
294 This is nothing we can configure, we learn by the dialog
295 Supported: header on the REGISTER (peer) or the INVITE
297 We are not using many of these today, but will in the future.
298 This is documented in RFC 3261
301 #define NOT_SUPPORTED 0
303 #define SIP_OPT_REPLACES (1 << 0)
304 #define SIP_OPT_100REL (1 << 1)
305 #define SIP_OPT_TIMER (1 << 2)
306 #define SIP_OPT_EARLY_SESSION (1 << 3)
307 #define SIP_OPT_JOIN (1 << 4)
308 #define SIP_OPT_PATH (1 << 5)
309 #define SIP_OPT_PREF (1 << 6)
310 #define SIP_OPT_PRECONDITION (1 << 7)
311 #define SIP_OPT_PRIVACY (1 << 8)
312 #define SIP_OPT_SDP_ANAT (1 << 9)
313 #define SIP_OPT_SEC_AGREE (1 << 10)
314 #define SIP_OPT_EVENTLIST (1 << 11)
315 #define SIP_OPT_GRUU (1 << 12)
316 #define SIP_OPT_TARGET_DIALOG (1 << 13)
318 /*! \brief List of well-known SIP options. If we get this in a require,
319 we should check the list and answer accordingly. */
320 static const struct cfsip_options {
321 int id; /*!< Bitmap ID */
322 int supported; /*!< Supported by Asterisk ? */
323 char * const text; /*!< Text id, as in standard */
324 } sip_options[] = { /* XXX used in 3 places */
325 /* Replaces: header for transfer */
326 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
327 /* RFC3262: PRACK 100% reliability */
328 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
329 /* SIP Session Timers */
330 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
331 /* RFC3959: SIP Early session support */
332 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
333 /* SIP Join header support */
334 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
335 /* RFC3327: Path support */
336 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
337 /* RFC3840: Callee preferences */
338 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
339 /* RFC3312: Precondition support */
340 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
341 /* RFC3323: Privacy with proxies*/
342 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
343 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
344 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
345 /* RFC3329: Security agreement mechanism */
346 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
347 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
348 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
349 /* GRUU: Globally Routable User Agent URI's */
350 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
351 /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
352 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
356 /*! \brief SIP Methods we support */
357 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
359 /*! \brief SIP Extensions we support */
360 #define SUPPORTED_EXTENSIONS "replaces"
363 /* Default values, set and reset in reload_config before reading configuration */
364 /* These are default values in the source. There are other recommended values in the
365 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
366 yet encouraging new behaviour on new installations
368 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
369 #define DEFAULT_CONTEXT "default"
370 #define DEFAULT_MUSICCLASS "default"
371 #define DEFAULT_VMEXTEN "asterisk"
372 #define DEFAULT_CALLERID "asterisk"
373 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
374 #define DEFAULT_MWITIME 10
375 #define DEFAULT_ALLOWGUEST TRUE
376 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
377 #define DEFAULT_COMPACTHEADERS FALSE
378 #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. */
379 #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. */
380 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
381 #define DEFAULT_ALLOW_EXT_DOM TRUE
382 #define DEFAULT_REALM "asterisk"
383 #define DEFAULT_NOTIFYRINGING TRUE
384 #define DEFAULT_PEDANTIC FALSE
385 #define DEFAULT_AUTOCREATEPEER FALSE
386 #define DEFAULT_QUALIFY FALSE
387 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
388 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
389 #ifndef DEFAULT_USERAGENT
390 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
394 /* Default setttings are used as a channel setting and as a default when
395 configuring devices */
396 static char default_context[AST_MAX_CONTEXT];
397 static char default_subscribecontext[AST_MAX_CONTEXT];
398 static char default_language[MAX_LANGUAGE];
399 static char default_callerid[AST_MAX_EXTENSION];
400 static char default_fromdomain[AST_MAX_EXTENSION];
401 static char default_notifymime[AST_MAX_EXTENSION];
402 static int default_qualify; /*!< Default Qualify= setting */
403 static char default_vmexten[AST_MAX_EXTENSION];
404 static char default_musicclass[MAX_MUSICCLASS]; /*!< Global music on hold class */
405 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
406 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
408 /* Global settings only apply to the channel */
409 static int global_rtautoclear;
410 static int global_notifyringing; /*!< Send notifications on ringing */
411 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
412 static int pedanticsipchecking; /*!< Extra checking ? Default off */
413 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
414 static int global_relaxdtmf; /*!< Relax DTMF */
415 static int global_rtptimeout; /*!< Time out call if no RTP */
416 static int global_rtpholdtimeout;
417 static int global_rtpkeepalive; /*!< Send RTP keepalives */
418 static int global_reg_timeout;
419 static int global_regattempts_max; /*!< Registration attempts before giving up */
420 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
421 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
422 the global setting is in globals_flags[1] */
423 static int global_mwitime; /*!< Time between MWI checks for peers */
424 static int global_tos_sip; /*!< IP type of service for SIP packets */
425 static int global_tos_audio; /*!< IP type of service for audio RTP packets */
426 static int global_tos_video; /*!< IP type of service for video RTP packets */
427 static int compactheaders; /*!< send compact sip headers */
428 static int recordhistory; /*!< Record SIP history. Off by default */
429 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
430 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
431 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
432 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
433 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
434 static int global_callevents; /*!< Whether we send manager events or not */
435 static int global_t1min; /*!< T1 roundtrip time minimum */
437 /*! \brief Codecs that we support by default: */
438 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
439 static int noncodeccapability = AST_RTP_DTMF;
441 /* Object counters */
442 static int suserobjs = 0; /*!< Static users */
443 static int ruserobjs = 0; /*!< Realtime users */
444 static int speerobjs = 0; /*!< Statis peers */
445 static int rpeerobjs = 0; /*!< Realtime peers */
446 static int apeerobjs = 0; /*!< Autocreated peer objects */
447 static int regobjs = 0; /*!< Registry objects */
449 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
451 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
453 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
454 AST_MUTEX_DEFINE_STATIC(iflock);
456 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
457 when it's doing something critical. */
458 AST_MUTEX_DEFINE_STATIC(netlock);
460 AST_MUTEX_DEFINE_STATIC(monlock);
462 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
464 /*! \brief This is the thread for the monitor which checks for input on the channels
465 which are not currently in use. */
466 static pthread_t monitor_thread = AST_PTHREADT_NULL;
468 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
469 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
471 static struct sched_context *sched; /*!< The scheduling context */
472 static struct io_context *io; /*!< The IO context */
474 #define DEC_CALL_LIMIT 0
475 #define INC_CALL_LIMIT 1
478 /*! \brief sip_request: The data grabbed from the UDP socket */
480 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
481 char *rlPart2; /*!< The Request URI or Response Status */
482 int len; /*!< Length */
483 int headers; /*!< # of SIP Headers */
484 int method; /*!< Method of this request */
485 int lines; /*!< SDP Content */
486 unsigned int flags; /*!< SIP_PKT Flags for this packet */
487 char *header[SIP_MAX_HEADERS];
488 char *line[SIP_MAX_LINES];
489 char data[SIP_MAX_PACKET];
493 * A sip packet is stored into the data[] buffer, with the header followed
494 * by an empty line and the body of the message.
495 * On outgoing packets, data is accumulated in data[] with len reflecting
496 * the next available byte, headers and lines count the number of lines
497 * in both parts. There are no '\0' in data[0..len-1].
499 * On received packet, the input read from the socket is copied into data[],
500 * len is set and the string is NUL-terminated. Then a parser fills up
501 * the other fields -header[] and line[] to point to the lines of the
502 * message, rlPart1 and rlPart2 parse the first lnie as below:
504 * Requests have in the first line METHOD URI SIP/2.0
505 * rlPart1 = method; rlPart2 = uri;
506 * Responses have in the first line SIP/2.0 code description
507 * rlPart1 = SIP/2.0; rlPart2 = code + description;
511 /*! \brief structure used in transfers */
513 struct ast_channel *chan1;
514 struct ast_channel *chan2;
515 struct sip_request req;
520 /*! \brief Parameters to the transmit_invite function */
521 struct sip_invite_param {
522 const char *distinctive_ring; /*!< Distinctive ring header */
523 int addsipheaders; /*!< Add extra SIP headers */
524 const char *uri_options; /*!< URI options to add to the URI */
525 const char *vxml_url; /*!< VXML url for Cisco phones */
526 char *auth; /*!< Authentication */
527 char *authheader; /*!< Auth header */
528 enum sip_auth_type auth_type; /*!< Authentication type */
531 /*! \brief Structure to save routing information for a SIP session */
533 struct sip_route *next;
537 /*! \brief Modes for SIP domain handling in the PBX */
539 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
540 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
544 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
545 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
546 enum domain_mode mode; /*!< How did we find this domain? */
547 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
550 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
553 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
555 AST_LIST_ENTRY(sip_history) list;
556 char event[0]; /* actually more, depending on needs */
559 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
561 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
563 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
564 char username[256]; /*!< Username */
565 char secret[256]; /*!< Secret */
566 char md5secret[256]; /*!< MD5Secret */
567 struct sip_auth *next; /*!< Next auth structure in list */
570 /*--- Various flags for the flags field in the pvt structure
571 Peer only flags should be set in PAGE2 below
573 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
574 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed */
575 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
576 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
577 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
578 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
579 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
580 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
581 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
582 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
583 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
584 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
585 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
586 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
587 #define SIP_FREEBIT (1 << 14) /*!< Free for session-related use */
588 #define SIP_FREEBIT3 (1 << 15) /*!< Free for session-related use */
589 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
590 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
591 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
592 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
593 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
595 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
596 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
597 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
598 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
599 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
600 /* re-INVITE related settings */
601 #define SIP_REINVITE (3 << 20) /*!< two bits used */
602 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
603 #define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
604 /* "insecure" settings */
605 #define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */
606 #define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */
607 /* Sending PROGRESS in-band settings */
608 #define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */
609 #define SIP_PROG_INBAND_NEVER (0 << 24)
610 #define SIP_PROG_INBAND_NO (1 << 24)
611 #define SIP_PROG_INBAND_YES (2 << 24)
612 #define SIP_CALL_ONHOLD (1 << 26) /*!< Call states */
613 #define SIP_CALL_LIMIT (1 << 27) /*!< Call limit enforced for this call */
614 #define SIP_SENDRPID (1 << 28) /*!< Remote Party-ID Support */
615 #define SIP_INC_COUNT (1 << 29) /*!< Did this connection increment the counter of in-use calls? */
617 #define SIP_FLAGS_TO_COPY \
618 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
619 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | \
620 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
622 /* a new page of flags for peers */
623 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
624 #define SIP_PAGE2_RTUPDATE (1 << 1)
625 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
626 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
627 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
628 #define SIP_PAGE2_DEBUG (3 << 5)
629 #define SIP_PAGE2_DEBUG_CONFIG (1 << 5)
630 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 6)
631 #define SIP_PAGE2_DYNAMIC (1 << 7) /*!< Dynamic Peers register with Asterisk */
632 #define SIP_PAGE2_SELFDESTRUCT (1 << 8) /*!< Automatic peers need to destruct themselves */
633 #define SIP_PAGE2_VIDEOSUPPORT (1 << 9)
634 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 10) /*!< Allow subscriptions from this peer? */
635 #define SIP_PAGE2_ALLOWOVERLAP (1 << 11) /*!< Allow overlap dialing ? */
636 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 12) /*!< Only issue MWI notification if subscribed to */
639 #define SIP_PAGE2_FLAGS_TO_COPY \
640 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT)
642 /* SIP packet flags */
643 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
644 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
646 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
647 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
648 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
650 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
651 static struct sip_pvt {
652 ast_mutex_t lock; /*!< Dialog private lock */
653 int method; /*!< SIP method that opened this dialog */
654 AST_DECLARE_STRING_FIELDS(
655 AST_STRING_FIELD(callid); /*!< Global CallID */
656 AST_STRING_FIELD(randdata); /*!< Random data */
657 AST_STRING_FIELD(accountcode); /*!< Account code */
658 AST_STRING_FIELD(realm); /*!< Authorization realm */
659 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
660 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
661 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
662 AST_STRING_FIELD(domain); /*!< Authorization domain */
663 AST_STRING_FIELD(refer_to); /*!< Place to store REFER-TO extension */
664 AST_STRING_FIELD(referred_by); /*!< Place to store REFERRED-BY extension */
665 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
666 AST_STRING_FIELD(from); /*!< The From: header */
667 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
668 AST_STRING_FIELD(exten); /*!< Extension where to start */
669 AST_STRING_FIELD(context); /*!< Context for this call */
670 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
671 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
672 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
673 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
674 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
675 AST_STRING_FIELD(language); /*!< Default language for this call */
676 AST_STRING_FIELD(musicclass); /*!< Music on Hold class */
677 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
678 AST_STRING_FIELD(theirtag); /*!< Their tag */
679 AST_STRING_FIELD(username); /*!< [user] name */
680 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
681 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
682 AST_STRING_FIELD(uri); /*!< Original requested URI */
683 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
684 AST_STRING_FIELD(peersecret); /*!< Password */
685 AST_STRING_FIELD(peermd5secret);
686 AST_STRING_FIELD(cid_num); /*!< Caller*ID */
687 AST_STRING_FIELD(cid_name); /*!< Caller*ID */
688 AST_STRING_FIELD(via); /*!< Via: header */
689 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
690 AST_STRING_FIELD(our_contact); /*!< Our contact header */
691 AST_STRING_FIELD(rpid); /*!< Our RPID header */
692 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
694 struct ast_codec_pref prefs; /*!< codec prefs */
695 unsigned int ocseq; /*!< Current outgoing seqno */
696 unsigned int icseq; /*!< Current incoming seqno */
697 ast_group_t callgroup; /*!< Call group */
698 ast_group_t pickupgroup; /*!< Pickup group */
699 int lastinvite; /*!< Last Cseq of invite */
700 struct ast_flags flags[2]; /*!< SIP_ flags */
701 int timer_t1; /*!< SIP timer T1, ms rtt */
702 unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */
703 int capability; /*!< Special capability (codec) */
704 int jointcapability; /*!< Supported capability at both ends (codecs ) */
705 int peercapability; /*!< Supported peer capability */
706 int prefcodec; /*!< Preferred codec (outbound only) */
707 int noncodeccapability;
708 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
709 int callingpres; /*!< Calling presentation */
710 int authtries; /*!< Times we've tried to authenticate */
711 int expiry; /*!< How long we take to expire */
712 long branch; /*!< One random number */
713 char tag[11]; /*!< Another random number */
714 int sessionid; /*!< SDP Session ID */
715 int sessionversion; /*!< SDP Session Version */
716 struct sockaddr_in sa; /*!< Our peer */
717 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
718 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
719 int redircodecs; /*!< Redirect codecs */
720 struct sockaddr_in recv; /*!< Received as */
721 struct in_addr ourip; /*!< Our IP */
722 struct ast_channel *owner; /*!< Who owns us */
723 struct sip_pvt *refer_call; /*!< Call we are referring */
724 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
725 int route_persistant; /*!< Is this the "real" route? */
726 struct sip_auth *peerauth; /*!< Realm authentication */
727 int noncecount; /*!< Nonce-count */
728 char lastmsg[256]; /*!< Last Message sent/received */
729 int amaflags; /*!< AMA Flags */
730 int pendinginvite; /*!< Any pending invite */
731 struct sip_request initreq; /*!< Initial request that opened the SIP dialog */
733 int maxtime; /*!< Max time for first response */
734 int initid; /*!< Auto-congest ID if appropriate */
735 int autokillid; /*!< Auto-kill ID */
736 time_t lastrtprx; /*!< Last RTP received */
737 time_t lastrtptx; /*!< Last RTP sent */
738 int rtptimeout; /*!< RTP timeout time */
739 int rtpholdtimeout; /*!< RTP timeout when on hold */
740 int rtpkeepalive; /*!< Send RTP packets for keepalive */
741 enum subscriptiontype subscribed; /*!< Is this dialog a subscription? */
743 int laststate; /*!< Last known extension state */
746 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
748 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
749 Used in peerpoke, mwi subscriptions */
750 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
751 struct ast_rtp *rtp; /*!< RTP Session */
752 struct ast_rtp *vrtp; /*!< Video RTP session */
753 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
754 struct sip_history_head *history; /*!< History of this SIP dialog */
755 struct ast_variable *chanvars; /*!< Channel variables to set for call */
756 struct sip_pvt *next; /*!< Next dialog in chain */
757 struct sip_invite_param *options; /*!< Options for INVITE */
760 #define FLAG_RESPONSE (1 << 0)
761 #define FLAG_FATAL (1 << 1)
763 /*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
765 struct sip_pkt *next; /*!< Next packet */
766 int retrans; /*!< Retransmission number */
767 int method; /*!< SIP method for this packet */
768 int seqno; /*!< Sequence number */
769 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
770 struct sip_pvt *owner; /*!< Owner AST call */
771 int retransid; /*!< Retransmission ID */
772 int timer_a; /*!< SIP timer A, retransmission timer */
773 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
774 int packetlen; /*!< Length of packet */
778 /*! \brief Structure for SIP user data. User's place calls to us */
780 /* Users who can access various contexts */
781 ASTOBJ_COMPONENTS(struct sip_user);
782 char secret[80]; /*!< Password */
783 char md5secret[80]; /*!< Password in md5 */
784 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
785 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
786 char cid_num[80]; /*!< Caller ID num */
787 char cid_name[80]; /*!< Caller ID name */
788 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
789 char language[MAX_LANGUAGE]; /*!< Default language for this user */
790 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
791 char useragent[256]; /*!< User agent in SIP request */
792 struct ast_codec_pref prefs; /*!< codec prefs */
793 ast_group_t callgroup; /*!< Call group */
794 ast_group_t pickupgroup; /*!< Pickup Group */
795 unsigned int sipoptions; /*!< Supported SIP options */
796 struct ast_flags flags[2]; /*!< SIP_ flags */
797 int amaflags; /*!< AMA flags for billing */
798 int callingpres; /*!< Calling id presentation */
799 int capability; /*!< Codec capability */
800 int inUse; /*!< Number of calls in use */
801 int call_limit; /*!< Limit of concurrent calls */
802 struct ast_ha *ha; /*!< ACL setting */
803 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
804 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
807 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
808 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
810 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
811 /*!< peer->name is the unique name of this object */
812 char secret[80]; /*!< Password */
813 char md5secret[80]; /*!< Password in MD5 */
814 struct sip_auth *auth; /*!< Realm authentication list */
815 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
816 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
817 char username[80]; /*!< Temporary username until registration */
818 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
819 int amaflags; /*!< AMA Flags (for billing) */
820 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
821 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
822 char fromuser[80]; /*!< From: user when calling this peer */
823 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
824 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
825 char cid_num[80]; /*!< Caller ID num */
826 char cid_name[80]; /*!< Caller ID name */
827 int callingpres; /*!< Calling id presentation */
828 int inUse; /*!< Number of calls in use */
829 int call_limit; /*!< Limit of concurrent calls */
830 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
831 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
832 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
833 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
834 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
835 struct ast_codec_pref prefs; /*!< codec prefs */
837 time_t lastmsgcheck; /*!< Last time we checked for MWI */
838 unsigned int sipoptions; /*!< Supported SIP options */
839 struct ast_flags flags[2]; /*!< SIP_ flags */
840 int expire; /*!< When to expire this peer registration */
841 int capability; /*!< Codec capability */
842 int rtptimeout; /*!< RTP timeout */
843 int rtpholdtimeout; /*!< RTP Hold Timeout */
844 int rtpkeepalive; /*!< Send RTP packets for keepalive */
845 ast_group_t callgroup; /*!< Call group */
846 ast_group_t pickupgroup; /*!< Pickup group */
847 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
848 struct sockaddr_in addr; /*!< IP address of peer */
849 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
852 struct sip_pvt *call; /*!< Call pointer */
853 int pokeexpire; /*!< When to expire poke (qualify= checking) */
854 int lastms; /*!< How long last response took (in ms), or -1 for no response */
855 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
856 struct timeval ps; /*!< Ping send time */
858 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
859 struct ast_ha *ha; /*!< Access control list */
860 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
861 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
867 /*! \brief Registrations with other SIP proxies */
868 struct sip_registry {
869 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
870 AST_DECLARE_STRING_FIELDS(
871 AST_STRING_FIELD(callid); /*!< Global Call-ID */
872 AST_STRING_FIELD(realm); /*!< Authorization realm */
873 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
874 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
875 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
876 AST_STRING_FIELD(domain); /*!< Authorization domain */
877 AST_STRING_FIELD(username); /*!< Who we are registering as */
878 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
879 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
880 AST_STRING_FIELD(secret); /*!< Password in clear text */
881 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
882 AST_STRING_FIELD(contact); /*!< Contact extension */
883 AST_STRING_FIELD(random);
885 int portno; /*!< Optional port override */
886 int expire; /*!< Sched ID of expiration */
887 int regattempts; /*!< Number of attempts (since the last success) */
888 int timeout; /*!< sched id of sip_reg_timeout */
889 int refresh; /*!< How often to refresh */
890 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
891 enum sipregistrystate regstate; /*!< Registration state (see above) */
892 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
893 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
894 struct sockaddr_in us; /*!< Who the server thinks we are */
895 int noncecount; /*!< Nonce-count */
896 char lastmsg[256]; /*!< Last Message sent/received */
899 /* --- Linked lists of various objects --------*/
901 /*! \brief The user list: Users and friends */
902 static struct ast_user_list {
903 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
906 /*! \brief The peer list: Peers and Friends */
907 static struct ast_peer_list {
908 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
911 /*! \brief The register list: Other SIP proxys we register with and place calls to */
912 static struct ast_register_list {
913 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
917 /*! \todo Move the sip_auth list to AST_LIST */
918 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
921 /* --- Sockets and networking --------------*/
922 static int sipsock = -1; /*!< Main socket for SIP network communication */
923 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
924 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
925 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
926 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
927 static int externrefresh = 10;
928 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
929 static struct in_addr __ourip;
930 static struct sockaddr_in outboundproxyip;
932 static struct sockaddr_in debugaddr;
934 struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
938 /*---------------------------- Forward declarations of functions in chan_sip.c */
939 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
940 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, enum xmittype reliable);
941 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *unsupported);
942 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
943 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
944 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
945 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
946 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
947 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
948 static int transmit_info_with_vidupdate(struct sip_pvt *p);
949 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
950 static int transmit_refer(struct sip_pvt *p, const char *dest);
951 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
952 static struct sip_peer *temp_peer(const char *name);
953 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
954 static void free_old_route(struct sip_route *route);
955 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
956 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
957 static int update_call_counter(struct sip_pvt *fup, int event);
958 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
959 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
960 static int sip_do_reload(enum channelreloadreason reason);
961 static int expire_register(void *data);
962 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
963 static int sip_devicestate(void *data);
964 static int sip_sendtext(struct ast_channel *ast, const char *text);
965 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
966 static int sip_hangup(struct ast_channel *ast);
967 static int sip_answer(struct ast_channel *ast);
968 static struct ast_frame *sip_read(struct ast_channel *ast);
969 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
970 static int sip_indicate(struct ast_channel *ast, int condition);
971 static int sip_transfer(struct ast_channel *ast, const char *dest);
972 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
973 static int sip_senddigit(struct ast_channel *ast, char digit);
974 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
975 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
976 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
977 static int check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
978 const char *secret, const char *md5secret, int sipmethod,
979 char *uri, enum xmittype reliable, int ignore);
980 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
981 static void append_date(struct sip_request *req); /* Append date to SIP packet */
982 static int determine_firstline_parts(struct sip_request *req);
983 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
984 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
985 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
986 static const char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
987 static int find_sip_method(const char *msg);
988 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
989 static void sip_destroy(struct sip_pvt *p);
990 static void sip_destroy_peer(struct sip_peer *peer);
991 static void sip_destroy_user(struct sip_user *user);
992 static void parse_request(struct sip_request *req);
993 static const char *get_header(struct sip_request *req, const char *name);
994 static void copy_request(struct sip_request *dst,struct sip_request *src);
995 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
996 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
997 static int sip_poke_peer(struct sip_peer *peer);
998 static int __sip_do_register(struct sip_registry *r);
999 static int restart_monitor(void);
1000 static void set_peer_defaults(struct sip_peer *peer);
1001 static struct sip_peer *temp_peer(const char *name);
1002 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1003 static int sip_scheddestroy(struct sip_pvt *p, int ms);
1006 /*----- RTP interface functions */
1007 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1008 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
1009 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
1010 static int sip_get_codec(struct ast_channel *chan);
1012 /*! \brief Definition of this channel for PBX channel registration */
1013 static const struct ast_channel_tech sip_tech = {
1015 .description = "Session Initiation Protocol (SIP)",
1016 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1017 .properties = AST_CHAN_TP_WANTSJITTER,
1018 .requester = sip_request_call,
1019 .devicestate = sip_devicestate,
1021 .hangup = sip_hangup,
1022 .answer = sip_answer,
1025 .write_video = sip_write,
1026 .indicate = sip_indicate,
1027 .transfer = sip_transfer,
1029 .send_digit = sip_senddigit,
1030 .bridge = ast_rtp_bridge,
1031 .send_text = sip_sendtext,
1034 /*! \brief Interface structure with callbacks used to connect to RTP module */
1035 static struct ast_rtp_protocol sip_rtp = {
1037 get_rtp_info: sip_get_rtp_peer,
1038 get_vrtp_info: sip_get_vrtp_peer,
1039 set_rtp_peer: sip_set_rtp_peer,
1040 get_codec: sip_get_codec,
1044 /*! \brief returns true if 'name' (with optional trailing whitespace)
1045 * matches the sip method 'id'.
1046 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1047 * a case-insensitive comparison to be more tolerant.
1048 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1050 static int method_match(enum sipmethod id, const char *name)
1052 int len = strlen(sip_methods[id].text);
1053 int l_name = name ? strlen(name) : 0;
1054 /* true if the string is long enough, and ends with whitespace, and matches */
1055 return (l_name >= len && name[len] < 33 &&
1056 !strncasecmp(sip_methods[id].text, name, len));
1059 /*! \brief find_sip_method: Find SIP method from header */
1060 static int find_sip_method(const char *msg)
1064 if (ast_strlen_zero(msg))
1066 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1067 if (method_match(i, msg))
1068 res = sip_methods[i].id;
1073 /*! \brief Parse supported header in incoming packet */
1074 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1077 char *temp = ast_strdupa(supported);
1078 unsigned int profile = 0;
1081 if (!pvt || ast_strlen_zero(supported) )
1084 if (option_debug > 2 && sipdebug)
1085 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1087 for (next = temp; next; next = sep) {
1089 if ( (sep = strchr(next, ',')) != NULL)
1091 next = ast_skip_blanks(next);
1092 if (option_debug > 2 && sipdebug)
1093 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1094 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1095 if (!strcasecmp(next, sip_options[i].text)) {
1096 profile |= sip_options[i].id;
1098 if (option_debug > 2 && sipdebug)
1099 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1103 if (!found && option_debug > 2 && sipdebug)
1104 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1107 pvt->sipoptions = profile;
1111 /*! \brief See if we pass debug IP filter */
1112 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1116 if (debugaddr.sin_addr.s_addr) {
1117 if (((ntohs(debugaddr.sin_port) != 0)
1118 && (debugaddr.sin_port != addr->sin_port))
1119 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1125 /* The real destination address for a write */
1126 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1128 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1131 static const char *sip_nat_mode(const struct sip_pvt *p)
1133 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1136 /*! \brief Test PVT for debugging output */
1137 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1141 return sip_debug_test_addr(sip_real_dst(p));
1144 /*! \brief Transmit SIP message */
1145 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1148 char iabuf[INET_ADDRSTRLEN];
1149 const struct sockaddr_in *dst = sip_real_dst(p);
1150 res=sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1153 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
1158 /*! \brief Build a Via header for a request */
1159 static void build_via(struct sip_pvt *p)
1161 char iabuf[INET_ADDRSTRLEN];
1162 /* Work around buggy UNIDEN UIP200 firmware */
1163 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1165 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1166 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1167 ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1170 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1171 * Only used for outbound registrations */
1172 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1175 * Using the localaddr structure built up with localnet statements
1176 * apply it to their address to see if we need to substitute our
1177 * externip or can get away with our internal bindaddr
1179 struct sockaddr_in theirs;
1180 theirs.sin_addr = *them;
1182 if (localaddr && externip.sin_addr.s_addr &&
1183 ast_apply_ha(localaddr, &theirs)) {
1184 if (externexpire && time(NULL) >= externexpire) {
1185 struct ast_hostent ahp;
1188 time(&externexpire);
1189 externexpire += externrefresh;
1190 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1191 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1193 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1195 *us = externip.sin_addr;
1197 char iabuf[INET_ADDRSTRLEN];
1198 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1200 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1202 } else if (bindaddr.sin_addr.s_addr)
1203 *us = bindaddr.sin_addr;
1205 return ast_ouraddrfor(them, us);
1209 /*! \brief Append to SIP dialog history
1210 \return Always returns 0 */
1211 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1213 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1214 __attribute__ ((format (printf, 2, 3)));
1216 /*! \brief Append to SIP dialog history with arg list */
1217 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1219 char buf[80], *c = buf; /* max history length */
1220 struct sip_history *hist;
1223 vsnprintf(buf, sizeof(buf), fmt, ap);
1224 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1225 l = strlen(buf) + 1;
1226 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1228 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1232 memcpy(hist->event, buf, l);
1233 AST_LIST_INSERT_TAIL(p->history, hist, list);
1236 /*! \brief Append to SIP dialog history with arg list */
1237 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1241 if (!recordhistory || !p)
1244 append_history_va(p, fmt, ap);
1250 /*! \brief Retransmit SIP message if no answer */
1251 static int retrans_pkt(void *data)
1253 struct sip_pkt *pkt=data, *prev, *cur = NULL;
1254 char iabuf[INET_ADDRSTRLEN];
1255 int reschedule = DEFAULT_RETRANS;
1258 ast_mutex_lock(&pkt->owner->lock);
1260 if (pkt->retrans < MAX_RETRANS) {
1262 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1263 if (sipdebug && option_debug > 3)
1264 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);
1268 if (sipdebug && option_debug > 3)
1269 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1273 pkt->timer_a = 2 * pkt->timer_a;
1275 /* For non-invites, a maximum of 4 secs */
1276 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1277 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1280 /* Reschedule re-transmit */
1281 reschedule = siptimer_a;
1282 if (option_debug > 3)
1283 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);
1286 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1287 if (ast_test_flag(&pkt->owner->flags[0], SIP_NAT_ROUTE))
1288 ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
1290 ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
1293 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1294 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1295 ast_mutex_unlock(&pkt->owner->lock);
1298 /* Too many retries */
1299 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1300 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1301 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");
1303 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1304 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1306 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1308 pkt->retransid = -1;
1310 if (ast_test_flag(pkt, FLAG_FATAL)) {
1311 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1312 ast_mutex_unlock(&pkt->owner->lock);
1314 ast_mutex_lock(&pkt->owner->lock);
1316 if (pkt->owner->owner) {
1317 ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1318 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1319 ast_queue_hangup(pkt->owner->owner);
1320 ast_mutex_unlock(&pkt->owner->owner->lock);
1322 /* If no channel owner, destroy now */
1323 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1326 /* In any case, go ahead and remove the packet */
1327 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1333 prev->next = cur->next;
1335 pkt->owner->packets = cur->next;
1336 ast_mutex_unlock(&pkt->owner->lock);
1340 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1342 ast_mutex_unlock(&pkt->owner->lock);
1346 /*! \brief Transmit packet with retransmits
1347 \return 0 on success, -1 on failure to allocate packet
1349 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1351 struct sip_pkt *pkt;
1352 int siptimer_a = DEFAULT_RETRANS;
1354 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1356 memcpy(pkt->data, data, len);
1357 pkt->method = sipmethod;
1358 pkt->packetlen = len;
1359 pkt->next = p->packets;
1363 pkt->data[len] = '\0';
1364 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1366 ast_set_flag(pkt, FLAG_FATAL);
1368 siptimer_a = pkt->timer_t1 * 2;
1370 /* Schedule retransmission */
1371 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1372 if (option_debug > 3 && sipdebug)
1373 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1374 pkt->next = p->packets;
1377 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1378 if (sipmethod == SIP_INVITE) {
1379 /* Note this is a pending invite */
1380 p->pendinginvite = seqno;
1385 /*! \brief Kill a SIP dialog (called by scheduler) */
1386 static int __sip_autodestruct(void *data)
1388 struct sip_pvt *p = data;
1390 /* If this is a subscription, tell the phone that we got a timeout */
1391 if (p->subscribed) {
1392 p->subscribed = TIMEOUT;
1393 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1394 p->subscribed = NONE;
1395 append_history(p, "Subscribestatus", "timeout");
1396 if (option_debug > 2)
1397 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1398 return 10000; /* Reschedule this destruction so that we know that it's gone */
1401 /* Reset schedule ID */
1405 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1406 append_history(p, "AutoDestroy", "");
1408 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1409 ast_queue_hangup(p->owner);
1416 /*! \brief Schedule destruction of SIP call */
1417 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1419 if (sip_debug_test_pvt(p))
1420 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1422 append_history(p, "SchedDestroy", "%d ms", ms);
1424 if (p->autokillid > -1)
1425 ast_sched_del(sched, p->autokillid);
1426 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1430 /*! \brief Cancel destruction of SIP dialog */
1431 static int sip_cancel_destroy(struct sip_pvt *p)
1433 if (p->autokillid > -1)
1434 ast_sched_del(sched, p->autokillid);
1435 append_history(p, "CancelDestroy", "");
1440 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1441 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
1443 struct sip_pkt *cur, *prev = NULL;
1446 /* Just in case... */
1449 msg = sip_methods[sipmethod].text;
1451 ast_mutex_lock(&p->lock);
1452 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
1453 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1454 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1455 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1456 if (!resp && (seqno == p->pendinginvite)) {
1457 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1458 p->pendinginvite = 0;
1460 /* this is our baby */
1462 prev->next = cur->next;
1464 p->packets = cur->next;
1465 if (cur->retransid > -1) {
1466 if (sipdebug && option_debug > 3)
1467 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1468 ast_sched_del(sched, cur->retransid);
1476 ast_mutex_unlock(&p->lock);
1478 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1482 /*! \brief Pretend to ack all packets */
1483 static int __sip_pretend_ack(struct sip_pvt *p)
1485 struct sip_pkt *cur = NULL;
1487 while (p->packets) {
1488 if (cur == p->packets) {
1489 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1494 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method, FALSE);
1495 else { /* Unknown packet type */
1499 ast_copy_string(method, p->packets->data, sizeof(method));
1500 c = ast_skip_blanks(method); /* XXX what ? */
1502 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method), FALSE);
1508 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
1509 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1511 struct sip_pkt *cur;
1514 for (cur = p->packets; cur; cur = cur->next) {
1515 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
1516 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
1517 /* this is our baby */
1518 if (cur->retransid > -1) {
1519 if (option_debug > 3 && sipdebug)
1520 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
1521 ast_sched_del(sched, cur->retransid);
1523 cur->retransid = -1;
1529 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");
1534 /*! \brief Copy SIP request, parse it */
1535 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1537 memset(dst, 0, sizeof(*dst));
1538 memcpy(dst->data, src->data, sizeof(dst->data));
1539 dst->len = src->len;
1543 /*! \brief Transmit response on SIP request*/
1544 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1548 if (sip_debug_test_pvt(p)) {
1549 char iabuf[INET_ADDRSTRLEN];
1550 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1551 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1553 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1555 if (recordhistory) {
1556 struct sip_request tmp;
1557 parse_copy(&tmp, req);
1558 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
1559 tmp.method == SIP_RESPONSE ? tmp.rlPart2 : sip_methods[tmp.method].text);
1562 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
1563 __sip_xmit(p, req->data, req->len);
1569 /*! \brief Send SIP Request to the other part of the dialogue */
1570 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1574 if (sip_debug_test_pvt(p)) {
1575 char iabuf[INET_ADDRSTRLEN];
1576 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1577 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1579 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1581 if (recordhistory) {
1582 struct sip_request tmp;
1583 parse_copy(&tmp, req);
1584 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
1587 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1588 __sip_xmit(p, req->data, req->len);
1592 /*! \brief Pick out text in brackets from character string
1593 \return pointer to terminated stripped string
1594 \param tmp input string that will be modified */
1595 static char *get_in_brackets(char *tmp)
1599 char *first_bracket;
1600 char *second_bracket;
1605 first_quote = strchr(parse, '"');
1606 first_bracket = strchr(parse, '<');
1607 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1609 for (parse = first_quote + 1; *parse; parse++) {
1610 if ((*parse == '"') && (last_char != '\\'))
1615 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1621 if (first_bracket) {
1622 second_bracket = strchr(first_bracket + 1, '>');
1623 if (second_bracket) {
1624 *second_bracket = '\0';
1625 return first_bracket + 1;
1627 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1635 /*! \brief Send SIP MESSAGE text within a call
1636 Called from PBX core sendtext() application */
1637 static int sip_sendtext(struct ast_channel *ast, const char *text)
1639 struct sip_pvt *p = ast->tech_pvt;
1640 int debug = sip_debug_test_pvt(p);
1643 ast_verbose("Sending text %s on %s\n", text, ast->name);
1646 if (ast_strlen_zero(text))
1649 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1650 transmit_message_with_text(p, text);
1654 /*! \brief Update peer object in realtime storage */
1655 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1659 char regseconds[20];
1661 const char *fc = fullcontact ? "fullcontact" : NULL;
1665 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
1666 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1667 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1669 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
1670 "port", port, "regseconds", regseconds,
1671 "username", username, fc, fullcontact, NULL); /* note fc _can_ be NULL */
1674 /*! \brief Automatically add peer extension to dial plan */
1675 static void register_peer_exten(struct sip_peer *peer, int onoff)
1678 char *stringp, *ext;
1679 if (!ast_strlen_zero(global_regcontext)) {
1681 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
1683 while((ext = strsep(&stringp, "&"))) {
1685 ast_add_extension(global_regcontext, 1, ext, 1, NULL, NULL, "Noop",
1686 ast_strdup(peer->name), free, "SIP");
1688 ast_context_remove_extension(global_regcontext, ext, 1, NULL);
1693 /*! \brief Destroy peer object from memory */
1694 static void sip_destroy_peer(struct sip_peer *peer)
1696 if (option_debug > 2)
1697 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
1699 /* Delete it, it needs to disappear */
1701 sip_destroy(peer->call);
1703 if (peer->mwipvt) { /* We have an active subscription, delete it */
1704 sip_destroy(peer->mwipvt);
1707 if (peer->chanvars) {
1708 ast_variables_destroy(peer->chanvars);
1709 peer->chanvars = NULL;
1711 if (peer->expire > -1)
1712 ast_sched_del(sched, peer->expire);
1713 if (peer->pokeexpire > -1)
1714 ast_sched_del(sched, peer->pokeexpire);
1715 register_peer_exten(peer, FALSE);
1716 ast_free_ha(peer->ha);
1717 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
1719 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
1723 clear_realm_authentication(peer->auth);
1726 ast_dnsmgr_release(peer->dnsmgr);
1730 /*! \brief Update peer data in database (if used) */
1731 static void update_peer(struct sip_peer *p, int expiry)
1733 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
1734 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
1735 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
1736 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
1741 /*! \brief realtime_peer: Get peer from realtime storage
1742 * Checks the "sippeers" realtime family from extconfig.conf
1743 * \todo Consider adding check of port address when matching here to follow the same
1744 * algorithm as for static peers. Will we break anything by adding that?
1746 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1748 struct sip_peer *peer = NULL;
1749 struct ast_variable *var;
1750 struct ast_variable *tmp;
1751 char *newpeername = (char *) peername;
1754 /* First check on peer name */
1756 var = ast_load_realtime("sippeers", "name", peername, NULL);
1757 else if (sin) { /* Then check on IP address for dynamic peers */
1758 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1759 var = ast_load_realtime("sippeers", "host", iabuf, NULL); /* First check for fixed IP hosts */
1761 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */
1769 for (tmp = var; tmp; tmp = tmp->next) {
1770 /* If this is type=user, then skip this object. */
1771 if (!strcasecmp(tmp->name, "type") &&
1772 !strcasecmp(tmp->value, "user")) {
1773 ast_variables_destroy(var);
1775 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1776 newpeername = tmp->value;
1780 if (!newpeername) { /* Did not find peer in realtime */
1781 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1782 ast_variables_destroy(var);
1786 /* Peer found in realtime, now build it in memory */
1787 peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
1789 ast_variables_destroy(var);
1793 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
1795 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1796 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
1797 if (peer->expire > -1) {
1798 ast_sched_del(sched, peer->expire);
1800 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1802 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1804 ast_set_flag(&peer->flags[0], SIP_REALTIME);
1806 ast_variables_destroy(var);
1811 /*! \brief Support routine for find_peer */
1812 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1814 /* We know name is the first field, so we can cast */
1815 struct sip_peer *p = (struct sip_peer *) name;
1816 return !(!inaddrcmp(&p->addr, sin) ||
1817 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
1818 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1821 /*! \brief Locate peer by name or ip address
1822 * This is used on incoming SIP message to find matching peer on ip
1823 or outgoing message to find matching peer on name */
1824 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1826 struct sip_peer *p = NULL;
1829 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1831 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
1833 if (!p && realtime) {
1834 p = realtime_peer(peer, sin);
1839 /*! \brief Remove user object from in-memory storage */
1840 static void sip_destroy_user(struct sip_user *user)
1842 if (option_debug > 2)
1843 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
1844 ast_free_ha(user->ha);
1845 if (user->chanvars) {
1846 ast_variables_destroy(user->chanvars);
1847 user->chanvars = NULL;
1849 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
1856 /*! \brief Load user from realtime storage
1857 * Loads user from "sipusers" category in realtime (extconfig.conf)
1858 * Users are matched on From: user name (the domain in skipped) */
1859 static struct sip_user *realtime_user(const char *username)
1861 struct ast_variable *var;
1862 struct ast_variable *tmp;
1863 struct sip_user *user = NULL;
1865 var = ast_load_realtime("sipusers", "name", username, NULL);
1870 for (tmp = var; tmp; tmp = tmp->next) {
1871 if (!strcasecmp(tmp->name, "type") &&
1872 !strcasecmp(tmp->value, "peer")) {
1873 ast_variables_destroy(var);
1878 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
1880 if (!user) { /* No user found */
1881 ast_variables_destroy(var);
1885 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
1886 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
1888 ASTOBJ_CONTAINER_LINK(&userl,user);
1890 /* Move counter from s to r... */
1893 ast_set_flag(&user->flags[0], SIP_REALTIME);
1895 ast_variables_destroy(var);
1899 /*! \brief Locate user by name
1900 * Locates user by name (From: sip uri user name part) first
1901 * from in-memory list (static configuration) then from
1902 * realtime storage (defined in extconfig.conf) */
1903 static struct sip_user *find_user(const char *name, int realtime)
1905 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
1907 u = realtime_user(name);
1911 /*! \brief Create address structure from peer reference */
1912 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1916 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1917 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
1918 r->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
1924 ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
1925 ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
1926 r->capability = peer->capability;
1927 if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
1928 ast_rtp_destroy(r->vrtp);
1931 r->prefs = peer->prefs;
1932 natflags = ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
1935 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", natflags);
1936 ast_rtp_setnat(r->rtp, natflags);
1940 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", natflags);
1941 ast_rtp_setnat(r->vrtp, natflags);
1943 ast_string_field_set(r, peername, peer->username);
1944 ast_string_field_set(r, authname, peer->username);
1945 ast_string_field_set(r, username, peer->username);
1946 ast_string_field_set(r, peersecret, peer->secret);
1947 ast_string_field_set(r, peermd5secret, peer->md5secret);
1948 ast_string_field_set(r, tohost, peer->tohost);
1949 ast_string_field_set(r, fullcontact, peer->fullcontact);
1950 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1953 tmpcall = ast_strdupa(r->callid);
1955 c = strchr(tmpcall, '@');
1958 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
1962 if (ast_strlen_zero(r->tohost)) {
1963 char iabuf[INET_ADDRSTRLEN];
1965 ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr.s_addr ? peer->addr.sin_addr : peer->defaddr.sin_addr);
1967 ast_string_field_set(r, tohost, iabuf);
1969 if (!ast_strlen_zero(peer->fromdomain))
1970 ast_string_field_set(r, fromdomain, peer->fromdomain);
1971 if (!ast_strlen_zero(peer->fromuser))
1972 ast_string_field_set(r, fromuser, peer->fromuser);
1973 r->maxtime = peer->maxms;
1974 r->callgroup = peer->callgroup;
1975 r->pickupgroup = peer->pickupgroup;
1976 /* Set timer T1 to RTT for this peer (if known by qualify=) */
1977 /* Minimum is settable or default to 100 ms */
1978 if (peer->maxms && peer->lastms)
1979 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
1980 if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
1981 (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
1982 r->noncodeccapability |= AST_RTP_DTMF;
1984 r->noncodeccapability &= ~AST_RTP_DTMF;
1985 ast_string_field_set(r, context, peer->context);
1986 r->rtptimeout = peer->rtptimeout;
1987 r->rtpholdtimeout = peer->rtpholdtimeout;
1988 r->rtpkeepalive = peer->rtpkeepalive;
1989 if (peer->call_limit)
1990 ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
1991 r->maxcallbitrate = peer->maxcallbitrate;
1996 /*! \brief create address structure from peer name
1997 * Or, if peer not found, find it in the global DNS
1998 * returns TRUE (-1) on failure, FALSE on success */
1999 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2002 struct ast_hostent ahp;
2007 char host[MAXHOSTNAMELEN], *hostn;
2010 ast_copy_string(peer, opeer, sizeof(peer));
2011 port = strchr(peer, ':');
2016 dialog->sa.sin_family = AF_INET;
2017 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2018 p = find_peer(peer, NULL, 1);
2022 if (create_addr_from_peer(dialog, p))
2023 ASTOBJ_UNREF(p, sip_destroy_peer);
2031 portno = atoi(port);
2033 portno = DEFAULT_SIP_PORT;
2035 char service[MAXHOSTNAMELEN];
2038 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2039 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2045 hp = ast_gethostbyname(hostn, &ahp);
2047 ast_string_field_set(dialog, tohost, peer);
2048 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2049 dialog->sa.sin_port = htons(portno);
2050 dialog->recv = dialog->sa;
2053 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2057 ASTOBJ_UNREF(p, sip_destroy_peer);
2062 /*! \brief Scheduled congestion on a call */
2063 static int auto_congest(void *nothing)
2065 struct sip_pvt *p = nothing;
2067 ast_mutex_lock(&p->lock);
2070 /* XXX fails on possible deadlock */
2071 if (!ast_mutex_trylock(&p->owner->lock)) {
2072 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2073 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2074 ast_mutex_unlock(&p->owner->lock);
2077 ast_mutex_unlock(&p->lock);
2084 /*! \brief Initiate SIP call from PBX
2085 * used from the dial() application */
2086 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2090 struct varshead *headp;
2091 struct ast_var_t *current;
2094 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2095 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2099 /* Check whether there is vxml_url, distinctive ring variables */
2100 headp=&ast->varshead;
2101 AST_LIST_TRAVERSE(headp,current,entries) {
2102 /* Check whether there is a VXML_URL variable */
2103 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2104 p->options->vxml_url = ast_var_value(current);
2105 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2106 p->options->uri_options = ast_var_value(current);
2107 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2108 /* Check whether there is a ALERT_INFO variable */
2109 p->options->distinctive_ring = ast_var_value(current);
2110 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2111 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2112 p->options->addsipheaders = 1;
2117 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2119 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2120 res = update_call_counter(p, INC_CALL_LIMIT);
2122 p->callingpres = ast->cid.cid_pres;
2123 p->jointcapability = p->capability;
2124 transmit_invite(p, SIP_INVITE, 1, 2);
2126 /* Initialize auto-congest time */
2127 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2133 /*! \brief Destroy registry object
2134 Objects created with the register= statement in static configuration */
2135 static void sip_registry_destroy(struct sip_registry *reg)
2138 if (option_debug > 2)
2139 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2142 /* Clear registry before destroying to ensure
2143 we don't get reentered trying to grab the registry lock */
2144 reg->call->registry = NULL;
2145 if (option_debug > 2)
2146 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2147 sip_destroy(reg->call);
2149 if (reg->expire > -1)
2150 ast_sched_del(sched, reg->expire);
2151 if (reg->timeout > -1)
2152 ast_sched_del(sched, reg->timeout);
2153 ast_string_field_free_all(reg);
2159 /*! \brief Execute destrucion of SIP dialog structure, release memory */
2160 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2162 struct sip_pvt *cur, *prev = NULL;
2165 if (sip_debug_test_pvt(p) || option_debug > 2)
2166 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2168 /* Remove link from peer to subscription of MWI */
2169 if (p->relatedpeer && p->relatedpeer->mwipvt)
2170 p->relatedpeer->mwipvt = NULL;
2173 sip_dump_history(p);
2178 if (p->stateid > -1)
2179 ast_extension_state_del(p->stateid, NULL);
2181 ast_sched_del(sched, p->initid);
2182 if (p->autokillid > -1)
2183 ast_sched_del(sched, p->autokillid);
2186 ast_rtp_destroy(p->rtp);
2188 ast_rtp_destroy(p->vrtp);
2190 free_old_route(p->route);
2194 if (p->registry->call == p)
2195 p->registry->call = NULL;
2196 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2199 /* Unlink us from the owner if we have one */
2202 ast_mutex_lock(&p->owner->lock);
2204 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2205 p->owner->tech_pvt = NULL;
2207 ast_mutex_unlock(&p->owner->lock);
2211 struct sip_history *hist;
2212 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2218 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2221 prev->next = cur->next;
2228 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2232 ast_sched_del(sched, p->initid);
2234 /* remove all current packets in this dialog */
2235 while((cp = p->packets)) {
2236 p->packets = p->packets->next;
2237 if (cp->retransid > -1)
2238 ast_sched_del(sched, cp->retransid);
2242 ast_variables_destroy(p->chanvars);
2245 ast_mutex_destroy(&p->lock);
2247 ast_string_field_free_all(p);
2252 /*! \brief update_call_counter: Handle call_limit for SIP users
2253 * Setting a call-limit will cause calls above the limit not to be accepted.
2255 * Remember that for a type=friend, there's one limit for the user and
2256 * another for the peer, not a combined call limit.
2257 * This will cause unexpected behaviour in subscriptions, since a "friend"
2258 * is *two* devices in Asterisk, not one.
2260 * Thought: For realtime, we should propably update storage with inuse counter...
2262 * \return 0 if call is ok (no call limit, below treshold)
2263 * -1 on rejection of call
2266 static int update_call_counter(struct sip_pvt *fup, int event)
2269 int *inuse, *call_limit;
2270 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2271 struct sip_user *u = NULL;
2272 struct sip_peer *p = NULL;
2274 if (option_debug > 2)
2275 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2276 /* Test if we need to check call limits, in order to avoid
2277 realtime lookups if we do not need it */
2278 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2281 ast_copy_string(name, fup->username, sizeof(name));
2283 /* Check the list of users */
2284 if (!outgoing) /* Only check users for incoming calls */
2285 u = find_user(name, 1);
2289 call_limit = &u->call_limit;
2292 /* Try to find peer */
2294 p = find_peer(fup->peername, NULL, 1);
2297 call_limit = &p->call_limit;
2298 ast_copy_string(name, fup->peername, sizeof(name));
2300 if (option_debug > 1)
2301 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2306 /* incoming and outgoing affects the inUse counter */
2307 case DEC_CALL_LIMIT:
2309 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2314 if (option_debug > 1 || sipdebug) {
2315 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2318 case INC_CALL_LIMIT:
2319 if (*call_limit > 0 ) {
2320 if (*inuse >= *call_limit) {
2321 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2323 ASTOBJ_UNREF(u, sip_destroy_user);
2325 ASTOBJ_UNREF(p, sip_destroy_peer);
2330 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2331 if (option_debug > 1 || sipdebug) {
2332 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2336 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2339 ASTOBJ_UNREF(u, sip_destroy_user);
2341 ASTOBJ_UNREF(p, sip_destroy_peer);
2345 /*! \brief Destroy SIP call structure */
2346 static void sip_destroy(struct sip_pvt *p)
2348 ast_mutex_lock(&iflock);
2349 if (option_debug > 2)
2350 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2351 __sip_destroy(p, 1);
2352 ast_mutex_unlock(&iflock);
2355 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2356 static int hangup_sip2cause(int cause)
2358 /* Possible values taken from causes.h */
2361 case 401: /* Unauthorized */
2362 return AST_CAUSE_CALL_REJECTED;
2363 case 403: /* Not found */
2364 return AST_CAUSE_CALL_REJECTED;
2365 case 404: /* Not found */
2366 return AST_CAUSE_UNALLOCATED;
2367 case 405: /* Method not allowed */
2368 return AST_CAUSE_INTERWORKING;
2369 case 407: /* Proxy authentication required */
2370 return AST_CAUSE_CALL_REJECTED;
2371 case 408: /* No reaction */
2372 return AST_CAUSE_NO_USER_RESPONSE;
2373 case 409: /* Conflict */
2374 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2375 case 410: /* Gone */
2376 return AST_CAUSE_UNALLOCATED;
2377 case 411: /* Length required */
2378 return AST_CAUSE_INTERWORKING;
2379 case 413: /* Request entity too large */
2380 return AST_CAUSE_INTERWORKING;
2381 case 414: /* Request URI too large */
2382 return AST_CAUSE_INTERWORKING;
2383 case 415: /* Unsupported media type */
2384 return AST_CAUSE_INTERWORKING;
2385 case 420: /* Bad extension */
2386 return AST_CAUSE_NO_ROUTE_DESTINATION;
2387 case 480: /* No answer */
2388 return AST_CAUSE_FAILURE;
2389 case 481: /* No answer */
2390 return AST_CAUSE_INTERWORKING;
2391 case 482: /* Loop detected */
2392 return AST_CAUSE_INTERWORKING;
2393 case 483: /* Too many hops */
2394 return AST_CAUSE_NO_ANSWER;
2395 case 484: /* Address incomplete */
2396 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2397 case 485: /* Ambigous */
2398 return AST_CAUSE_UNALLOCATED;
2399 case 486: /* Busy everywhere */
2400 return AST_CAUSE_BUSY;
2401 case 487: /* Request terminated */
2402 return AST_CAUSE_INTERWORKING;
2403 case 488: /* No codecs approved */
2404 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2405 case 491: /* Request pending */
2406 return AST_CAUSE_INTERWORKING;
2407 case 493: /* Undecipherable */
2408 return AST_CAUSE_INTERWORKING;
2409 case 500: /* Server internal failure */
2410 return AST_CAUSE_FAILURE;
2411 case 501: /* Call rejected */
2412 return AST_CAUSE_FACILITY_REJECTED;
2414 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2415 case 503: /* Service unavailable */
2416 return AST_CAUSE_CONGESTION;
2417 case 504: /* Gateway timeout */
2418 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2419 case 505: /* SIP version not supported */
2420 return AST_CAUSE_INTERWORKING;
2421 case 600: /* Busy everywhere */
2422 return AST_CAUSE_USER_BUSY;
2423 case 603: /* Decline */
2424 return AST_CAUSE_CALL_REJECTED;
2425 case 604: /* Does not exist anywhere */
2426 return AST_CAUSE_UNALLOCATED;
2427 case 606: /* Not acceptable */
2428 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2430 return AST_CAUSE_NORMAL;
2436 /*! \brief Convert Asterisk hangup causes to SIP codes
2438 Possible values from causes.h
2439 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
2440 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
2442 In addition to these, a lot of PRI codes is defined in causes.h
2443 ...should we take care of them too ?
2447 ISUP Cause value SIP response
2448 ---------------- ------------
2449 1 unallocated number 404 Not Found
2450 2 no route to network 404 Not found
2451 3 no route to destination 404 Not found
2452 16 normal call clearing --- (*)
2453 17 user busy 486 Busy here
2454 18 no user responding 408 Request Timeout
2455 19 no answer from the user 480 Temporarily unavailable
2456 20 subscriber absent 480 Temporarily unavailable
2457 21 call rejected 403 Forbidden (+)
2458 22 number changed (w/o diagnostic) 410 Gone
2459 22 number changed (w/ diagnostic) 301 Moved Permanently
2460 23 redirection to new destination 410 Gone
2461 26 non-selected user clearing 404 Not Found (=)
2462 27 destination out of order 502 Bad Gateway
2463 28 address incomplete 484 Address incomplete
2464 29 facility rejected 501 Not implemented
2465 31 normal unspecified 480 Temporarily unavailable
2468 static char *hangup_cause2sip(int cause)
2472 case AST_CAUSE_UNALLOCATED: /* 1 */
2473 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
2474 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
2475 return "404 Not Found";
2476 case AST_CAUSE_CONGESTION: /* 34 */
2477 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
2478 return "503 Service Unavailable";
2479 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
2480 return "408 Request Timeout";
2481 case AST_CAUSE_NO_ANSWER: /* 19 */
2482 return "480 Temporarily unavailable";
2483 case AST_CAUSE_CALL_REJECTED: /* 21 */
2484 return "403 Forbidden";
2485 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
2487 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
2488 return "480 Temporarily unavailable";
2489 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2490 return "484 Address incomplete";
2491 case AST_CAUSE_USER_BUSY:
2492 return "486 Busy here";
2493 case AST_CAUSE_FAILURE:
2494 return "500 Server internal failure";
2495 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
2496 return "501 Not Implemented";
2497 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2498 return "503 Service Unavailable";
2499 /* Used in chan_iax2 */
2500 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2501 return "502 Bad Gateway";
2502 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2503 return "488 Not Acceptable Here";
2505 case AST_CAUSE_NOTDEFINED:
2507 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2516 /*! \brief sip_hangup: Hangup SIP call
2517 * Part of PBX interface, called from ast_hangup */
2518 static int sip_hangup(struct ast_channel *ast)
2520 struct sip_pvt *p = ast->tech_pvt;
2521 int needcancel = FALSE;
2522 struct ast_flags locflags = {0};
2525 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
2528 if (option_debug && sipdebug)
2529 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2531 ast_mutex_lock(&p->lock);
2532 if (option_debug && sipdebug)
2533 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2534 update_call_counter(p, DEC_CALL_LIMIT);
2535 /* Determine how to disconnect */
2536 if (p->owner != ast) {
2537 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
2538 ast_mutex_unlock(&p->lock);
2541 /* If the call is not UP, we need to send CANCEL instead of BYE */
2542 if (ast->_state != AST_STATE_UP)
2548 ast_dsp_free(p->vad);
2551 ast->tech_pvt = NULL;
2553 ast_mutex_lock(&usecnt_lock);
2555 ast_mutex_unlock(&usecnt_lock);
2556 ast_update_use_count();
2558 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2560 /* Start the process if it's not already started */
2561 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2562 if (needcancel) { /* Outgoing call, not up */
2563 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2564 /* stop retransmitting an INVITE that has not received a response */
2565 __sip_pretend_ack(p);
2567 /* Send a new request: CANCEL */
2568 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, 0);
2569 /* Actually don't destroy us yet, wait for the 487 on our original
2570 INVITE, but do set an autodestruct just in case we never get it. */
2571 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2573 sip_scheddestroy(p, 32000);
2574 if ( p->initid != -1 ) {
2575 /* channel still up - reverse dec of inUse counter
2576 only if the channel is not auto-congested */
2577 update_call_counter(p, INC_CALL_LIMIT);
2579 } else { /* Incoming call, not up */
2581 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2582 transmit_response_reliable(p, res, &p->initreq);
2584 transmit_response_reliable(p, "603 Declined", &p->initreq);
2586 } else { /* Call is in UP state, send BYE */
2587 if (!p->pendinginvite) {
2589 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2591 /* Note we will need a BYE when this all settles out
2592 but we can't send one while we have "INVITE" outstanding. */
2593 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
2594 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
2598 ast_copy_flags(&p->flags[0], &locflags, SIP_NEEDDESTROY);
2599 ast_mutex_unlock(&p->lock);
2603 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
2604 static void try_suggested_sip_codec(struct sip_pvt *p)
2609 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
2613 fmt = ast_getformatbyname(codec);
2615 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n", codec);
2616 if (p->jointcapability & fmt) {
2617 p->jointcapability &= fmt;
2618 p->capability &= fmt;
2620 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2622 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
2626 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
2627 * Part of PBX interface */
2628 static int sip_answer(struct ast_channel *ast)
2631 struct sip_pvt *p = ast->tech_pvt;
2633 ast_mutex_lock(&p->lock);
2634 if (ast->_state != AST_STATE_UP) {
2635 try_suggested_sip_codec(p);
2637 ast_setstate(ast, AST_STATE_UP);
2639 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
2640 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_RELIABLE);
2642 ast_mutex_unlock(&p->lock);
2646 /*! \brief Send frame to media channel (rtp) */
2647 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2649 struct sip_pvt *p = ast->tech_pvt;
2652 switch (frame->frametype) {
2653 case AST_FRAME_VOICE:
2654 if (!(frame->subclass & ast->nativeformats)) {
2655 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2656 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2660 ast_mutex_lock(&p->lock);
2662 /* If channel is not up, activate early media session */
2663 if ((ast->_state != AST_STATE_UP) &&
2664 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2665 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2666 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2667 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
2669 time(&p->lastrtptx);
2670 res = ast_rtp_write(p->rtp, frame);
2672 ast_mutex_unlock(&p->lock);
2675 case AST_FRAME_VIDEO:
2677 ast_mutex_lock(&p->lock);
2679 /* Activate video early media */
2680 if ((ast->_state != AST_STATE_UP) &&
2681 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2682 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2683 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2684 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
2686 time(&p->lastrtptx);
2687 res = ast_rtp_write(p->vrtp, frame);
2689 ast_mutex_unlock(&p->lock);
2692 case AST_FRAME_IMAGE:
2696 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2703 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2704 Basically update any ->owner links */
2705 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2708 struct sip_pvt *p = newchan->tech_pvt;
2710 ast_mutex_lock(&p->lock);
2711 if (p->owner != oldchan)
2712 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2717 ast_mutex_unlock(&p->lock);
2721 /*! \brief Send DTMF character on SIP channel
2722 within one call, we're able to transmit in many methods simultaneously */
2723 static int sip_senddigit(struct ast_channel *ast, char digit)
2725 struct sip_pvt *p = ast->tech_pvt;
2728 ast_mutex_lock(&p->lock);
2729 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
2731 transmit_info_with_digit(p, digit);
2733 case SIP_DTMF_RFC2833:
2735 ast_rtp_senddigit(p->rtp, digit);
2737 case SIP_DTMF_INBAND:
2741 ast_mutex_unlock(&p->lock);
2745 /*! \brief Transfer SIP call */
2746 static int sip_transfer(struct ast_channel *ast, const char *dest)
2748 struct sip_pvt *p = ast->tech_pvt;
2751 ast_mutex_lock(&p->lock);
2752 if (ast->_state == AST_STATE_RING)
2753 res = sip_sipredirect(p, dest);
2755 res = transmit_refer(p, dest);
2756 ast_mutex_unlock(&p->lock);
2760 /*! \brief Play indication to user
2761 * With SIP a lot of indications is sent as messages, letting the device play
2762 the indication - busy signal, congestion etc
2763 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
2765 static int sip_indicate(struct ast_channel *ast, int condition)
2767 struct sip_pvt *p = ast->tech_pvt;
2770 ast_mutex_lock(&p->lock);
2772 case AST_CONTROL_RINGING:
2773 if (ast->_state == AST_STATE_RING) {
2774 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
2775 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2776 /* Send 180 ringing if out-of-band seems reasonable */
2777 transmit_response(p, "180 Ringing", &p->initreq);
2778 ast_set_flag(&p->flags[0], SIP_RINGING);
2779 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2782 /* Well, if it's not reasonable, just send in-band */
2787 case AST_CONTROL_BUSY:
2788 if (ast->_state != AST_STATE_UP) {
2789 transmit_response(p, "486 Busy Here", &p->initreq);
2790 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
2791 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2796 case AST_CONTROL_CONGESTION:
2797 if (ast->_state != AST_STATE_UP) {
2798 transmit_response(p, "503 Service Unavailable", &p->initreq);
2799 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
2800 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2805 case AST_CONTROL_PROCEEDING:
2806 if ((ast->_state != AST_STATE_UP) &&
2807 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2808 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2809 transmit_response(p, "100 Trying", &p->initreq);
2814 case AST_CONTROL_PROGRESS:
2815 if ((ast->_state != AST_STATE_UP) &&
2816 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2817 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2818 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2819 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
2824 case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
2826 ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
2829 case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
2831 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2834 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
2835 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
2836 transmit_info_with_vidupdate(p);
2837 /* ast_rtcp_send_h261fur(p->vrtp); */
2846 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2850 ast_mutex_unlock(&p->lock);
2856 /*! \brief Initiate a call in the SIP channel
2857 called from sip_request_call (calls from the pbx ) */
2858 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
2860 struct ast_channel *tmp;
2861 struct ast_variable *v = NULL;
2865 ast_mutex_unlock(&i->lock);
2866 /* Don't hold a sip pvt lock while we allocate a channel */
2867 tmp = ast_channel_alloc(1);
2868 ast_mutex_lock(&i->lock);
2870 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2873 tmp->tech = &sip_tech;
2874 /* Select our native format based on codec preference until we receive
2875 something from another device to the contrary. */
2876 if (i->jointcapability)
2877 what = i->jointcapability;
2878 else if (i->capability)
2879 what = i->capability;
2881 what = global_capability;
2882 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
2883 fmt = ast_best_codec(tmp->nativeformats);
2886 ast_string_field_build(tmp, name, "SIP/%s-%04lx", title, ast_random() & 0xffff);
2887 else if (strchr(i->fromdomain,':'))
2888 ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2890 ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2892 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
2893 i->vad = ast_dsp_new();
2894 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2895 if (global_relaxdtmf)
2896 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2899 tmp->fds[0] = ast_rtp_fd(i->rtp);
2900 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2903 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2904 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2906 if (state == AST_STATE_RING)
2908 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2909 tmp->writeformat = fmt;
2910 tmp->rawwriteformat = fmt;
2911 tmp->readformat = fmt;
2912 tmp->rawreadformat = fmt;
2915 tmp->callgroup = i->callgroup;
2916 tmp->pickupgroup = i->pickupgroup;
2917 tmp->cid.cid_pres = i->callingpres;
2918 if (!ast_strlen_zero(i->accountcode))
2919 ast_string_field_set(tmp, accountcode, i->accountcode);
2921 tmp->amaflags = i->amaflags;
2922 if (!ast_strlen_zero(i->language))
2923 ast_string_field_set(tmp, language, i->language);
2924 if (!ast_strlen_zero(i->musicclass))
2925 ast_string_field_set(tmp, musicclass, i->musicclass);
2927 ast_mutex_lock(&usecnt_lock);
2929 ast_mutex_unlock(&usecnt_lock);
2930 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2931 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2932 if (!ast_strlen_zero(i->cid_num))
2933 tmp->cid.cid_num = ast_strdup(i->cid_num);
2934 if (!ast_strlen_zero(i->cid_name))
2935 tmp->cid.cid_name = ast_strdup(i->cid_name);
2936 if (!ast_strlen_zero(i->rdnis))
2937 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
2938 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2939 tmp->cid.cid_dnid = ast_strdup(i->exten);
2941 if (!ast_strlen_zero(i->uri))
2942 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2943 if (!ast_strlen_zero(i->domain))
2944 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2945 if (!ast_strlen_zero(i->useragent))
2946 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2947 if (!ast_strlen_zero(i->callid))
2948 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2949 ast_setstate(tmp, state);
2950 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
2951 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2952 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
2956 /* Set channel variables for this call from configuration */
2957 for (v = i->chanvars ; v ; v = v->next)
2958 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2960 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
2965 /*! \brief Reads one line of SIP message body */
2966 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2968 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2969 return ast_skip_blanks(line + nameLen + 1);
2974 /*! \brief Gets all kind of SIP message bodies, including SDP,
2975 but the name wrongly applies _only_ sdp */
2976 static char *get_sdp(struct sip_request *req, char *name)
2979 int len = strlen(name);
2981 for (x = 0; x < req->lines; x++) {
2982 char *r = get_sdp_by_line(req->line[x], name, len);
2990 static void sdpLineNum_iterator_init(int* iterator)
2995 static char* get_sdp_iterate(int* iterator,
2996 struct sip_request *req, char *name)
2998 int len = strlen(name);
3000 while (*iterator < req->lines) {
3001 char *r = get_sdp_by_line(req->line[(*iterator)++], name, len);
3008 static char *find_alias(const char *name, char *_default)
3011 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
3012 if (!strcasecmp(aliases[x].fullname, name))
3013 return aliases[x].shortname;
3017 static const char *__get_header(struct sip_request *req, const char *name, int *start)
3022 * Technically you can place arbitrary whitespace both before and after the ':' in
3023 * a header, although RFC3261 clearly says you shouldn't before, and place just
3024 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
3025 * a good idea to say you can do it, and if you can do it, why in the hell would.
3026 * you say you shouldn't.
3027 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
3028 * and we always allow spaces after that for compatibility.
3030 for (pass = 0; name && pass < 2;pass++) {
3031 int x, len = strlen(name);
3032 for (x=*start; x<req->headers; x++) {
3033 if (!strncasecmp(req->header[x], name, len)) {
3034 char *r = req->header[x] + len; /* skip name */
3035 if (pedanticsipchecking)