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"
97 #include "asterisk/astosp.h"
109 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
110 #ifndef IPTOS_MINCOST
111 #define IPTOS_MINCOST 0x02
114 /* #define VOCAL_DATA_HACK */
116 #define DEFAULT_DEFAULT_EXPIRY 120
117 #define DEFAULT_MIN_EXPIRY 60
118 #define DEFAULT_MAX_EXPIRY 3600
119 #define DEFAULT_REGISTRATION_TIMEOUT 20
120 #define DEFAULT_MAX_FORWARDS "70"
122 /* guard limit must be larger than guard secs */
123 /* guard min must be < 1000, and should be >= 250 */
124 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
125 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
127 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
128 GUARD_PCT turns out to be lower than this, it
129 will use this time instead.
130 This is in milliseconds. */
131 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
132 below EXPIRY_GUARD_LIMIT */
133 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
135 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
136 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
137 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
138 static int expiry = DEFAULT_EXPIRY;
141 #define MAX(a,b) ((a) > (b) ? (a) : (b))
144 #define CALLERID_UNKNOWN "Unknown"
146 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
147 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
148 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
150 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
151 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
152 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
154 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
155 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
156 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
159 static const char desc[] = "Session Initiation Protocol (SIP)";
160 static const char config[] = "sip.conf";
161 static const char notify_config[] = "sip_notify.conf";
162 static int usecnt = 0;
168 /* Do _NOT_ make any changes to this enum, or the array following it;
169 if you think you are doing the right thing, you are probably
170 not doing the right thing. If you think there are changes
171 needed, get someone else to review them first _before_
172 submitting a patch. If these two lists do not match properly
173 bad things will happen.
177 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
178 If it fails, it's critical and will cause a teardown of the session */
179 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
180 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
183 enum subscriptiontype {
192 static const struct cfsubscription_types {
193 enum subscriptiontype type;
194 const char * const event;
195 const char * const mediatype;
196 const char * const text;
197 } subscription_types[] = {
198 { NONE, "-", "unknown", "unknown" },
199 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
200 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
201 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
202 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
203 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" } /* Pre-RFC 3863 with MS additions */
230 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
231 static const struct cfsip_methods {
233 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
236 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
237 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
238 { SIP_REGISTER, NO_RTP, "REGISTER" },
239 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
240 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
241 { SIP_INVITE, RTP, "INVITE" },
242 { SIP_ACK, NO_RTP, "ACK" },
243 { SIP_PRACK, NO_RTP, "PRACK" },
244 { SIP_BYE, NO_RTP, "BYE" },
245 { SIP_REFER, NO_RTP, "REFER" },
246 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
247 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
248 { SIP_UPDATE, NO_RTP, "UPDATE" },
249 { SIP_INFO, NO_RTP, "INFO" },
250 { SIP_CANCEL, NO_RTP, "CANCEL" },
251 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
254 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
255 static const struct cfalias {
256 char * const fullname;
257 char * const shortname;
259 { "Content-Type", "c" },
260 { "Content-Encoding", "e" },
264 { "Content-Length", "l" },
267 { "Supported", "k" },
269 { "Referred-By", "b" },
270 { "Allow-Events", "u" },
273 { "Accept-Contact", "a" },
274 { "Reject-Contact", "j" },
275 { "Request-Disposition", "d" },
276 { "Session-Expires", "x" },
279 /*! Define SIP option tags, used in Require: and Supported: headers
280 We need to be aware of these properties in the phones to use
281 the replace: header. We should not do that without knowing
282 that the other end supports it...
283 This is nothing we can configure, we learn by the dialog
284 Supported: header on the REGISTER (peer) or the INVITE
286 We are not using many of these today, but will in the future.
287 This is documented in RFC 3261
290 #define NOT_SUPPORTED 0
292 #define SIP_OPT_REPLACES (1 << 0)
293 #define SIP_OPT_100REL (1 << 1)
294 #define SIP_OPT_TIMER (1 << 2)
295 #define SIP_OPT_EARLY_SESSION (1 << 3)
296 #define SIP_OPT_JOIN (1 << 4)
297 #define SIP_OPT_PATH (1 << 5)
298 #define SIP_OPT_PREF (1 << 6)
299 #define SIP_OPT_PRECONDITION (1 << 7)
300 #define SIP_OPT_PRIVACY (1 << 8)
301 #define SIP_OPT_SDP_ANAT (1 << 9)
302 #define SIP_OPT_SEC_AGREE (1 << 10)
303 #define SIP_OPT_EVENTLIST (1 << 11)
304 #define SIP_OPT_GRUU (1 << 12)
305 #define SIP_OPT_TARGET_DIALOG (1 << 13)
307 /*! \brief List of well-known SIP options. If we get this in a require,
308 we should check the list and answer accordingly. */
309 static const struct cfsip_options {
310 int id; /*!< Bitmap ID */
311 int supported; /*!< Supported by Asterisk ? */
312 char * const text; /*!< Text id, as in standard */
314 /* Replaces: header for transfer */
315 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
316 /* RFC3262: PRACK 100% reliability */
317 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
318 /* SIP Session Timers */
319 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
320 /* RFC3959: SIP Early session support */
321 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
322 /* SIP Join header support */
323 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
324 /* RFC3327: Path support */
325 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
326 /* RFC3840: Callee preferences */
327 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
328 /* RFC3312: Precondition support */
329 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
330 /* RFC3323: Privacy with proxies*/
331 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
332 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
333 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
334 /* RFC3329: Security agreement mechanism */
335 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
336 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
337 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
338 /* GRUU: Globally Routable User Agent URI's */
339 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
340 /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
341 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
345 /*! \brief SIP Methods we support */
346 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
348 /*! \brief SIP Extensions we support */
349 #define SUPPORTED_EXTENSIONS "replaces"
352 /* Default values, set and reset in reload_config before reading configuration */
353 /* These are default values in the source. There are other recommended values in the
354 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
355 yet encouraging new behaviour on new installations
357 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
358 #define DEFAULT_CONTEXT "default"
359 #define DEFAULT_MUSICCLASS "default"
360 #define DEFAULT_VMEXTEN "asterisk"
361 #define DEFAULT_CALLERID "asterisk"
362 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
363 #define DEFAULT_MWITIME 10
364 #define DEFAULT_ALLOWGUEST TRUE
365 #define DEFAULT_VIDEOSUPPORT FALSE
366 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
367 #define DEFAULT_COMPACTHEADERS FALSE
368 #define DEFAULT_TOS FALSE
369 #define DEFAULT_ALLOW_EXT_DOM TRUE
370 #define DEFAULT_REALM "asterisk"
371 #define DEFAULT_NOTIFYRINGING TRUE
372 #define DEFAULT_PEDANTIC FALSE
373 #define DEFAULT_AUTOCREATEPEER FALSE
374 #define DEFAULT_QUALIFY FALSE
375 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
376 #ifndef DEFAULT_USERAGENT
377 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
380 /* Default setttings are used as a channel setting and as a default when
381 configuring devices */
382 static char default_context[AST_MAX_CONTEXT];
383 static char default_subscribecontext[AST_MAX_CONTEXT];
384 static char default_language[MAX_LANGUAGE];
385 static char default_callerid[AST_MAX_EXTENSION];
386 static char default_fromdomain[AST_MAX_EXTENSION];
387 static char default_notifymime[AST_MAX_EXTENSION];
388 static int default_qualify; /*!< Default Qualify= setting */
389 static char default_vmexten[AST_MAX_EXTENSION];
390 static char default_musicclass[MAX_MUSICCLASS]; /*!< Global music on hold class */
391 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
393 /* Global settings only apply to the channel */
394 static int global_rtautoclear = 120;
395 static int global_notifyringing; /*!< Send notifications on ringing */
396 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
397 static int pedanticsipchecking; /*!< Extra checking ? Default off */
398 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
399 static int global_relaxdtmf; /*!< Relax DTMF */
400 static int global_rtptimeout; /*!< Time out call if no RTP */
401 static int global_rtpholdtimeout;
402 static int global_rtpkeepalive; /*!< Send RTP keepalives */
403 static int global_reg_timeout;
404 static int global_regattempts_max; /*!< Registration attempts before giving up */
405 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
406 static int global_mwitime; /*!< Time between MWI checks for peers */
407 static int global_tos; /*!< IP Type of service */
408 static int global_videosupport; /*!< Videosupport on or off */
409 static int compactheaders; /*!< send compact sip headers */
410 static int recordhistory; /*!< Record SIP history. Off by default */
411 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
412 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
413 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
414 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
415 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
416 static int global_callevents; /*!< Whether we send manager events or not */
417 static int global_t1min; /*!< T1 roundtrip time minimum */
419 /*! \brief Codecs that we support by default: */
420 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
421 static int noncodeccapability = AST_RTP_DTMF;
423 /* Object counters */
424 static int suserobjs = 0; /*!< Static users */
425 static int ruserobjs = 0; /*!< Realtime users */
426 static int speerobjs = 0; /*!< Statis peers */
427 static int rpeerobjs = 0; /*!< Realtime peers */
428 static int apeerobjs = 0; /*!< Autocreated peer objects */
429 static int regobjs = 0; /*!< Registry objects */
431 static struct ast_flags global_flags = {0}; /*!< global SIP_ flags */
432 static struct ast_flags global_flags_page2 = {0}; /*!< more global SIP_ flags */
434 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
436 AST_MUTEX_DEFINE_STATIC(rand_lock); /*!< Lock for thread-safe random generator */
438 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
439 AST_MUTEX_DEFINE_STATIC(iflock);
441 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
442 when it's doing something critical. */
443 AST_MUTEX_DEFINE_STATIC(netlock);
445 AST_MUTEX_DEFINE_STATIC(monlock);
447 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
449 /*! \brief This is the thread for the monitor which checks for input on the channels
450 which are not currently in use. */
451 static pthread_t monitor_thread = AST_PTHREADT_NULL;
453 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
454 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
456 static struct sched_context *sched; /*!< The scheduling context */
457 static struct io_context *io; /*!< The IO context */
459 #define DEC_CALL_LIMIT 0
460 #define INC_CALL_LIMIT 1
463 /*! \brief sip_request: The data grabbed from the UDP socket */
465 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
466 char *rlPart2; /*!< The Request URI or Response Status */
467 int len; /*!< Length */
468 int headers; /*!< # of SIP Headers */
469 int method; /*!< Method of this request */
470 char *header[SIP_MAX_HEADERS];
471 int lines; /*!< SDP Content */
472 char *line[SIP_MAX_LINES];
473 char data[SIP_MAX_PACKET];
474 int debug; /*!< Debug flag for this packet */
475 unsigned int flags; /*!< SIP_PKT Flags for this packet */
478 /*! \brief structure used in transfers */
480 struct ast_channel *chan1;
481 struct ast_channel *chan2;
482 struct sip_request req;
487 /*! \brief Parameters to the transmit_invite function */
488 struct sip_invite_param {
489 const char *distinctive_ring; /*!< Distinctive ring header */
490 const char *osptoken; /*!< OSP token for this call */
491 int addsipheaders; /*!< Add extra SIP headers */
492 const char *uri_options; /*!< URI options to add to the URI */
493 const char *vxml_url; /*!< VXML url for Cisco phones */
494 char *auth; /*!< Authentication */
495 char *authheader; /*!< Auth header */
496 enum sip_auth_type auth_type; /*!< Authentication type */
499 /*! \brief Structure to save routing information for a SIP session */
501 struct sip_route *next;
505 /*! \brief Modes for SIP domain handling in the PBX */
507 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
508 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
512 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
513 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
514 enum domain_mode mode; /*!< How did we find this domain? */
515 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
518 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
521 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
523 AST_LIST_ENTRY(sip_history) list;
524 char event[0]; /* actually more, depending on needs */
527 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
529 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
531 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
532 char username[256]; /*!< Username */
533 char secret[256]; /*!< Secret */
534 char md5secret[256]; /*!< MD5Secret */
535 struct sip_auth *next; /*!< Next auth structure in list */
538 /*--- Various flags for the flags field in the pvt structure
539 Peer only flags should be set in PAGE2 below
541 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
542 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed */
543 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
544 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
545 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
546 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
547 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
548 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
549 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
550 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
551 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
552 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
553 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
554 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
555 #define SIP_FREEBIT (1 << 14) /*!< Free for session-related use */
556 #define SIP_FREEBIT3 (1 << 15) /*!< Free for session-related use */
557 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
558 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
559 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
560 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
561 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
563 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
564 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
565 #define SIP_NAT_RFC3581 (1 << 18)
566 #define SIP_NAT_ROUTE (2 << 18)
567 #define SIP_NAT_ALWAYS (3 << 18)
568 /* re-INVITE related settings */
569 #define SIP_REINVITE (3 << 20) /*!< two bits used */
570 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
571 #define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
572 /* "insecure" settings */
573 #define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */
574 #define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */
575 /* Sending PROGRESS in-band settings */
576 #define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */
577 #define SIP_PROG_INBAND_NEVER (0 << 24)
578 #define SIP_PROG_INBAND_NO (1 << 24)
579 #define SIP_PROG_INBAND_YES (2 << 24)
580 /* Open Settlement Protocol authentication */
581 #define SIP_OSPAUTH (3 << 26) /*!< four settings, uses two bits */
582 #define SIP_OSPAUTH_NO (0 << 26)
583 #define SIP_OSPAUTH_GATEWAY (1 << 26)
584 #define SIP_OSPAUTH_PROXY (2 << 26)
585 #define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
587 #define SIP_CALL_ONHOLD (1 << 28)
588 #define SIP_CALL_LIMIT (1 << 29)
589 /* Remote Party-ID Support */
590 #define SIP_SENDRPID (1 << 30)
591 /* Did this connection increment the counter of in-use calls? */
592 #define SIP_INC_COUNT (1 << 31)
594 #define SIP_FLAGS_TO_COPY \
595 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
596 SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
597 SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
599 /* a new page of flags for peers */
600 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
601 #define SIP_PAGE2_RTUPDATE (1 << 1)
602 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
603 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
604 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
605 #define SIP_PAGE2_DEBUG (3 << 5)
606 #define SIP_PAGE2_DEBUG_CONFIG (1 << 5)
607 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 6)
608 #define SIP_PAGE2_DYNAMIC (1 << 7) /*!< Dynamic Peers register with Asterisk */
609 #define SIP_PAGE2_SELFDESTRUCT (1 << 8) /*!< Automatic peers need to destruct themselves */
611 /* SIP packet flags */
612 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
613 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
615 #define sipdebug ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG)
616 #define sipdebug_config ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG_CONFIG)
617 #define sipdebug_console ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG_CONSOLE)
620 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
621 static struct sip_pvt {
622 ast_mutex_t lock; /*!< Dialog private lock */
623 int method; /*!< SIP method that opened this dialog */
624 AST_DECLARE_STRING_FIELDS(
625 AST_STRING_FIELD(callid); /*!< Global CallID */
626 AST_STRING_FIELD(randdata); /*!< Random data */
627 AST_STRING_FIELD(accountcode); /*!< Account code */
628 AST_STRING_FIELD(realm); /*!< Authorization realm */
629 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
630 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
631 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
632 AST_STRING_FIELD(domain); /*!< Authorization domain */
633 AST_STRING_FIELD(refer_to); /*!< Place to store REFER-TO extension */
634 AST_STRING_FIELD(referred_by); /*!< Place to store REFERRED-BY extension */
635 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
636 AST_STRING_FIELD(from); /*!< The From: header */
637 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
638 AST_STRING_FIELD(exten); /*!< Extension where to start */
639 AST_STRING_FIELD(context); /*!< Context for this call */
640 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
641 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
642 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
643 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
644 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
645 AST_STRING_FIELD(language); /*!< Default language for this call */
646 AST_STRING_FIELD(musicclass); /*!< Music on Hold class */
647 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
648 AST_STRING_FIELD(theirtag); /*!< Their tag */
649 AST_STRING_FIELD(username); /*!< [user] name */
650 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
651 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
652 AST_STRING_FIELD(uri); /*!< Original requested URI */
653 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
654 AST_STRING_FIELD(peersecret); /*!< Password */
655 AST_STRING_FIELD(peermd5secret);
656 AST_STRING_FIELD(cid_num); /*!< Caller*ID */
657 AST_STRING_FIELD(cid_name); /*!< Caller*ID */
658 AST_STRING_FIELD(via); /*!< Via: header */
659 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
660 AST_STRING_FIELD(our_contact); /*!< Our contact header */
661 AST_STRING_FIELD(rpid); /*!< Our RPID header */
662 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
664 struct ast_codec_pref prefs; /*!< codec prefs */
665 unsigned int ocseq; /*!< Current outgoing seqno */
666 unsigned int icseq; /*!< Current incoming seqno */
667 ast_group_t callgroup; /*!< Call group */
668 ast_group_t pickupgroup; /*!< Pickup group */
669 int lastinvite; /*!< Last Cseq of invite */
670 unsigned int flags; /*!< SIP_ flags */
671 int timer_t1; /*!< SIP timer T1, ms rtt */
672 unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */
673 int capability; /*!< Special capability (codec) */
674 int jointcapability; /*!< Supported capability at both ends (codecs ) */
675 int peercapability; /*!< Supported peer capability */
676 int prefcodec; /*!< Preferred codec (outbound only) */
677 int noncodeccapability;
678 int callingpres; /*!< Calling presentation */
679 int authtries; /*!< Times we've tried to authenticate */
680 int expiry; /*!< How long we take to expire */
681 int branch; /*!< One random number */
682 char tag[11]; /*!< Another random number */
683 int sessionid; /*!< SDP Session ID */
684 int sessionversion; /*!< SDP Session Version */
685 struct sockaddr_in sa; /*!< Our peer */
686 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
687 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
688 int redircodecs; /*!< Redirect codecs */
689 struct sockaddr_in recv; /*!< Received as */
690 struct in_addr ourip; /*!< Our IP */
691 struct ast_channel *owner; /*!< Who owns us */
692 struct sip_pvt *refer_call; /*!< Call we are referring */
693 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
694 int route_persistant; /*!< Is this the "real" route? */
695 struct sip_auth *peerauth; /*!< Realm authentication */
696 int noncecount; /*!< Nonce-count */
697 char lastmsg[256]; /*!< Last Message sent/received */
698 int amaflags; /*!< AMA Flags */
699 int pendinginvite; /*!< Any pending invite */
701 int osphandle; /*!< OSP Handle for call */
702 time_t ospstart; /*!< OSP Start time */
703 unsigned int osptimelimit; /*!< OSP call duration limit */
705 struct sip_request initreq; /*!< Initial request that opened the SIP dialog */
707 int maxtime; /*!< Max time for first response */
708 int initid; /*!< Auto-congest ID if appropriate */
709 int autokillid; /*!< Auto-kill ID */
710 time_t lastrtprx; /*!< Last RTP received */
711 time_t lastrtptx; /*!< Last RTP sent */
712 int rtptimeout; /*!< RTP timeout time */
713 int rtpholdtimeout; /*!< RTP timeout when on hold */
714 int rtpkeepalive; /*!< Send RTP packets for keepalive */
715 enum subscriptiontype subscribed; /*!< Is this dialog a subscription? */
717 int laststate; /*!< Last known extension state */
720 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
722 struct sip_peer *peerpoke; /*!< If this dialog is to poke a peer, which one */
723 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
724 struct ast_rtp *rtp; /*!< RTP Session */
725 struct ast_rtp *vrtp; /*!< Video RTP session */
726 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
727 struct sip_history_head *history; /*!< History of this SIP dialog */
728 struct ast_variable *chanvars; /*!< Channel variables to set for call */
729 struct sip_pvt *next; /*!< Next dialog in chain */
730 struct sip_invite_param *options; /*!< Options for INVITE */
733 #define FLAG_RESPONSE (1 << 0)
734 #define FLAG_FATAL (1 << 1)
736 /*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
738 struct sip_pkt *next; /*!< Next packet */
739 int retrans; /*!< Retransmission number */
740 int method; /*!< SIP method for this packet */
741 int seqno; /*!< Sequence number */
742 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
743 struct sip_pvt *owner; /*!< Owner AST call */
744 int retransid; /*!< Retransmission ID */
745 int timer_a; /*!< SIP timer A, retransmission timer */
746 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
747 int packetlen; /*!< Length of packet */
751 /*! \brief Structure for SIP user data. User's place calls to us */
753 /* Users who can access various contexts */
754 ASTOBJ_COMPONENTS(struct sip_user);
755 char secret[80]; /*!< Password */
756 char md5secret[80]; /*!< Password in md5 */
757 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
758 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
759 char cid_num[80]; /*!< Caller ID num */
760 char cid_name[80]; /*!< Caller ID name */
761 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
762 char language[MAX_LANGUAGE]; /*!< Default language for this user */
763 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
764 char useragent[256]; /*!< User agent in SIP request */
765 struct ast_codec_pref prefs; /*!< codec prefs */
766 ast_group_t callgroup; /*!< Call group */
767 ast_group_t pickupgroup; /*!< Pickup Group */
768 unsigned int flags; /*!< SIP flags */
769 unsigned int sipoptions; /*!< Supported SIP options */
770 struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
771 int amaflags; /*!< AMA flags for billing */
772 int callingpres; /*!< Calling id presentation */
773 int capability; /*!< Codec capability */
774 int inUse; /*!< Number of calls in use */
775 int call_limit; /*!< Limit of concurrent calls */
776 struct ast_ha *ha; /*!< ACL setting */
777 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
780 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
782 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
783 /*!< peer->name is the unique name of this object */
784 char secret[80]; /*!< Password */
785 char md5secret[80]; /*!< Password in MD5 */
786 struct sip_auth *auth; /*!< Realm authentication list */
787 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
788 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
789 char username[80]; /*!< Temporary username until registration */
790 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
791 int amaflags; /*!< AMA Flags (for billing) */
792 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
793 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
794 char fromuser[80]; /*!< From: user when calling this peer */
795 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
796 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
797 char cid_num[80]; /*!< Caller ID num */
798 char cid_name[80]; /*!< Caller ID name */
799 int callingpres; /*!< Calling id presentation */
800 int inUse; /*!< Number of calls in use */
801 int call_limit; /*!< Limit of concurrent calls */
802 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
803 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
804 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
805 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
806 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
807 struct ast_codec_pref prefs; /*!< codec prefs */
809 time_t lastmsgcheck; /*!< Last time we checked for MWI */
810 unsigned int flags; /*!< SIP flags */
811 unsigned int sipoptions; /*!< Supported SIP options */
812 struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
813 int expire; /*!< When to expire this peer registration */
814 int capability; /*!< Codec capability */
815 int rtptimeout; /*!< RTP timeout */
816 int rtpholdtimeout; /*!< RTP Hold Timeout */
817 int rtpkeepalive; /*!< Send RTP packets for keepalive */
818 ast_group_t callgroup; /*!< Call group */
819 ast_group_t pickupgroup; /*!< Pickup group */
820 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
821 struct sockaddr_in addr; /*!< IP address of peer */
824 struct sip_pvt *call; /*!< Call pointer */
825 int pokeexpire; /*!< When to expire poke (qualify= checking) */
826 int lastms; /*!< How long last response took (in ms), or -1 for no response */
827 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
828 struct timeval ps; /*!< Ping send time */
830 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
831 struct ast_ha *ha; /*!< Access control list */
832 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
837 /* States for outbound registrations (with register= lines in sip.conf */
838 #define REG_STATE_UNREGISTERED 0 /*!< We are not registred */
839 #define REG_STATE_REGSENT 1 /*!< Registration request sent */
840 #define REG_STATE_AUTHSENT 2 /*!< We have tried to authenticate */
841 #define REG_STATE_REGISTERED 3 /*!< Registred and done */
842 #define REG_STATE_REJECTED 4 /*!< Registration rejected */
843 #define REG_STATE_TIMEOUT 5 /*!< Registration timed out */
844 #define REG_STATE_NOAUTH 6 /*!< We have no accepted credentials */
845 #define REG_STATE_FAILED 7 /*!< Registration failed after several tries */
848 /*! \brief Registrations with other SIP proxies */
849 struct sip_registry {
850 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
851 AST_DECLARE_STRING_FIELDS(
852 AST_STRING_FIELD(callid); /*!< Global Call-ID */
853 AST_STRING_FIELD(realm); /*!< Authorization realm */
854 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
855 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
856 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
857 AST_STRING_FIELD(domain); /*!< Authorization domain */
858 AST_STRING_FIELD(username); /*!< Who we are registering as */
859 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
860 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
861 AST_STRING_FIELD(secret); /*!< Password in clear text */
862 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
863 AST_STRING_FIELD(contact); /*!< Contact extension */
864 AST_STRING_FIELD(random);
866 int portno; /*!< Optional port override */
867 int expire; /*!< Sched ID of expiration */
868 int regattempts; /*!< Number of attempts (since the last success) */
869 int timeout; /*!< sched id of sip_reg_timeout */
870 int refresh; /*!< How often to refresh */
871 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
872 int regstate; /*!< Registration state (see above) */
873 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
874 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
875 struct sockaddr_in us; /*!< Who the server thinks we are */
876 int noncecount; /*!< Nonce-count */
877 char lastmsg[256]; /*!< Last Message sent/received */
880 /* --- Linked lists of various objects --------*/
882 /*! \brief The user list: Users and friends */
883 static struct ast_user_list {
884 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
887 /*! \brief The peer list: Peers and Friends */
888 static struct ast_peer_list {
889 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
892 /*! \brief The register list: Other SIP proxys we register with and place calls to */
893 static struct ast_register_list {
894 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
898 /*! \todo Move the sip_auth list to AST_LIST */
899 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
902 /* --- Sockets and networking --------------*/
903 static int sipsock = -1; /*!< Main socket for SIP network communication */
904 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
905 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
906 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
907 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
908 static int externrefresh = 10;
909 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
910 static struct in_addr __ourip;
911 static struct sockaddr_in outboundproxyip;
913 static struct sockaddr_in debugaddr;
915 struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
919 /*---------------------------- Forward declarations of functions in chan_sip.c */
920 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
921 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, enum xmittype reliable);
922 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
923 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);
924 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
925 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
926 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
927 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
928 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
929 static int transmit_info_with_vidupdate(struct sip_pvt *p);
930 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
931 static int transmit_refer(struct sip_pvt *p, const char *dest);
932 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
933 static struct sip_peer *temp_peer(const char *name);
934 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
935 static void free_old_route(struct sip_route *route);
936 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
937 static int update_call_counter(struct sip_pvt *fup, int event);
938 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
939 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
940 static int sip_do_reload(enum channelreloadreason reason);
941 static int expire_register(void *data);
942 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
943 static int sip_devicestate(void *data);
944 static int sip_sendtext(struct ast_channel *ast, const char *text);
945 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
946 static int sip_hangup(struct ast_channel *ast);
947 static int sip_answer(struct ast_channel *ast);
948 static struct ast_frame *sip_read(struct ast_channel *ast);
949 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
950 static int sip_indicate(struct ast_channel *ast, int condition);
951 static int sip_transfer(struct ast_channel *ast, const char *dest);
952 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
953 static int sip_senddigit(struct ast_channel *ast, char digit);
954 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
955 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
956 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
957 static int check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
958 const char *secret, const char *md5secret, int sipmethod,
959 char *uri, enum xmittype reliable, int ignore);
960 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
961 static void append_date(struct sip_request *req); /* Append date to SIP packet */
962 static int determine_firstline_parts(struct sip_request *req);
963 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
964 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
965 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
966 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
967 static int find_sip_method(char *msg);
968 static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported);
969 static void sip_destroy(struct sip_pvt *p);
970 static void parse_request(struct sip_request *req);
971 static char *get_header(struct sip_request *req, const char *name);
972 static void copy_request(struct sip_request *dst,struct sip_request *src);
973 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
974 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
975 static int sip_poke_peer(struct sip_peer *peer);
976 static int __sip_do_register(struct sip_registry *r);
977 static int restart_monitor(void);
978 static void set_peer_defaults(struct sip_peer *peer);
979 static struct sip_peer *temp_peer(const char *name);
982 /*----- RTP interface functions */
983 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
984 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
985 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
986 static int sip_get_codec(struct ast_channel *chan);
988 /*! \brief Definition of this channel for PBX channel registration */
989 static const struct ast_channel_tech sip_tech = {
991 .description = "Session Initiation Protocol (SIP)",
992 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
993 .properties = AST_CHAN_TP_WANTSJITTER,
994 .requester = sip_request_call,
995 .devicestate = sip_devicestate,
997 .hangup = sip_hangup,
998 .answer = sip_answer,
1001 .write_video = sip_write,
1002 .indicate = sip_indicate,
1003 .transfer = sip_transfer,
1005 .send_digit = sip_senddigit,
1006 .bridge = ast_rtp_bridge,
1007 .send_text = sip_sendtext,
1010 /*! \brief Interface structure with callbacks used to connect to RTP module */
1011 static struct ast_rtp_protocol sip_rtp = {
1013 get_rtp_info: sip_get_rtp_peer,
1014 get_vrtp_info: sip_get_vrtp_peer,
1015 set_rtp_peer: sip_set_rtp_peer,
1016 get_codec: sip_get_codec,
1021 \brief Thread-safe random number generator
1022 \return a random number
1024 This function uses a mutex lock to guarantee that no
1025 two threads will receive the same random number.
1027 static force_inline int thread_safe_rand(void)
1031 ast_mutex_lock(&rand_lock);
1033 ast_mutex_unlock(&rand_lock);
1038 /*! \brief Find SIP method from header
1039 * Strictly speaking, SIP methods are case SENSITIVE, but we don't check
1040 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
1041 static int find_sip_method(char *msg)
1045 if (ast_strlen_zero(msg))
1048 for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
1049 if (!strcasecmp(sip_methods[i].text, msg))
1050 res = sip_methods[i].id;
1055 /*! \brief Parse supported header in incoming packet */
1056 static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
1060 char *temp = ast_strdupa(supported);
1062 unsigned int profile = 0;
1064 if (ast_strlen_zero(supported) )
1067 if (option_debug > 2 && sipdebug)
1068 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1073 if ( (sep = strchr(next, ',')) != NULL) {
1077 while (*next == ' ') /* Skip spaces */
1079 if (option_debug > 2 && sipdebug)
1080 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1081 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
1082 if (!strcasecmp(next, sip_options[i].text)) {
1083 profile |= sip_options[i].id;
1085 if (option_debug > 2 && sipdebug)
1086 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1090 if (option_debug > 2 && sipdebug)
1091 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1095 pvt->sipoptions = profile;
1097 ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
1102 /*! \brief See if we pass debug IP filter */
1103 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
1107 if (debugaddr.sin_addr.s_addr) {
1108 if (((ntohs(debugaddr.sin_port) != 0)
1109 && (debugaddr.sin_port != addr->sin_port))
1110 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1116 /*! \brief Test PVT for debugging output */
1117 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1121 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
1125 /*! \brief Transmit SIP message */
1126 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1129 char iabuf[INET_ADDRSTRLEN];
1131 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1132 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
1134 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
1137 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), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno));
1143 /*! \brief Build a Via header for a request */
1144 static void build_via(struct sip_pvt *p)
1146 char iabuf[INET_ADDRSTRLEN];
1147 /* Work around buggy UNIDEN UIP200 firmware */
1148 const char *rport = ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1150 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1151 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1152 ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1155 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1156 * Only used for outbound registrations */
1157 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1160 * Using the localaddr structure built up with localnet statements
1161 * apply it to their address to see if we need to substitute our
1162 * externip or can get away with our internal bindaddr
1164 struct sockaddr_in theirs;
1165 theirs.sin_addr = *them;
1167 if (localaddr && externip.sin_addr.s_addr &&
1168 ast_apply_ha(localaddr, &theirs)) {
1169 if (externexpire && (time(NULL) >= externexpire)) {
1170 struct ast_hostent ahp;
1173 time(&externexpire);
1174 externexpire += externrefresh;
1175 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1176 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1178 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1180 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
1182 char iabuf[INET_ADDRSTRLEN];
1183 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1185 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1187 } else if (bindaddr.sin_addr.s_addr)
1188 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
1190 return ast_ouraddrfor(them, us);
1194 /*! \brief Append to SIP dialog history
1195 \return Always returns 0 */
1196 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1198 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1199 __attribute__ ((format (printf, 2, 3)));
1201 /*! \brief Append to SIP dialog history with arg list */
1202 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1204 char buf[80], *c = buf; /* max history length */
1205 struct sip_history *hist;
1208 vsnprintf(buf, sizeof(buf), fmt, ap);
1209 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1210 l = strlen(buf) + 1;
1211 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1213 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1217 memcpy(hist->event, buf, l);
1218 AST_LIST_INSERT_TAIL(p->history, hist, list);
1221 /*! \brief Append to SIP dialog history with arg list */
1222 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1226 if (!recordhistory || !p)
1229 append_history_va(p, fmt, ap);
1235 /*! \brief Retransmit SIP message if no answer */
1236 static int retrans_pkt(void *data)
1238 struct sip_pkt *pkt=data, *prev, *cur = NULL;
1239 char iabuf[INET_ADDRSTRLEN];
1240 int reschedule = DEFAULT_RETRANS;
1243 ast_mutex_lock(&pkt->owner->lock);
1245 if (pkt->retrans < MAX_RETRANS) {
1247 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1248 if (sipdebug && option_debug > 3)
1249 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);
1253 if (sipdebug && option_debug > 3)
1254 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1258 pkt->timer_a = 2 * pkt->timer_a;
1260 /* For non-invites, a maximum of 4 secs */
1261 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1262 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1265 /* Reschedule re-transmit */
1266 reschedule = siptimer_a;
1267 if (option_debug > 3)
1268 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);
1271 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1272 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
1273 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);
1275 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);
1278 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1279 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1280 ast_mutex_unlock(&pkt->owner->lock);
1283 /* Too many retries */
1284 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1285 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1286 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");
1288 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1289 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1291 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1293 pkt->retransid = -1;
1295 if (ast_test_flag(pkt, FLAG_FATAL)) {
1296 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1297 ast_mutex_unlock(&pkt->owner->lock);
1299 ast_mutex_lock(&pkt->owner->lock);
1301 if (pkt->owner->owner) {
1302 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
1303 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1304 ast_queue_hangup(pkt->owner->owner);
1305 ast_mutex_unlock(&pkt->owner->owner->lock);
1307 /* If no channel owner, destroy now */
1308 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
1311 /* In any case, go ahead and remove the packet */
1313 cur = pkt->owner->packets;
1322 prev->next = cur->next;
1324 pkt->owner->packets = cur->next;
1325 ast_mutex_unlock(&pkt->owner->lock);
1329 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1331 ast_mutex_unlock(&pkt->owner->lock);
1335 /*! \brief Transmit packet with retransmits
1336 \return 0 on success, -1 on failure to allocate packet
1338 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1340 struct sip_pkt *pkt;
1341 int siptimer_a = DEFAULT_RETRANS;
1343 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1345 memcpy(pkt->data, data, len);
1346 pkt->method = sipmethod;
1347 pkt->packetlen = len;
1348 pkt->next = p->packets;
1352 pkt->data[len] = '\0';
1353 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1355 ast_set_flag(pkt, FLAG_FATAL);
1358 siptimer_a = pkt->timer_t1 * 2;
1360 /* Schedule retransmission */
1361 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1362 if (option_debug > 3 && sipdebug)
1363 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1364 pkt->next = p->packets;
1367 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1368 if (sipmethod == SIP_INVITE) {
1369 /* Note this is a pending invite */
1370 p->pendinginvite = seqno;
1375 /*! \brief Kill a SIP dialog (called by scheduler) */
1376 static int __sip_autodestruct(void *data)
1378 struct sip_pvt *p = data;
1380 /* If this is a subscription, tell the phone that we got a timeout */
1381 if (p->subscribed) {
1382 p->subscribed = TIMEOUT;
1383 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1384 p->subscribed = NONE;
1385 append_history(p, "Subscribestatus", "timeout");
1386 if (option_debug > 2)
1387 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1388 return 10000; /* Reschedule this destruction so that we know that it's gone */
1391 /* Reset schedule ID */
1395 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1396 append_history(p, "AutoDestroy", "");
1398 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1399 ast_queue_hangup(p->owner);
1406 /*! \brief Schedule destruction of SIP call */
1407 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1409 if (sip_debug_test_pvt(p))
1410 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1412 append_history(p, "SchedDestroy", "%d ms", ms);
1414 if (p->autokillid > -1)
1415 ast_sched_del(sched, p->autokillid);
1416 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1420 /*! \brief Cancel destruction of SIP dialog */
1421 static int sip_cancel_destroy(struct sip_pvt *p)
1423 if (p->autokillid > -1)
1424 ast_sched_del(sched, p->autokillid);
1425 append_history(p, "CancelDestroy", "");
1430 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1431 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1433 struct sip_pkt *cur, *prev = NULL;
1436 /* Just in case... */
1439 msg = sip_methods[sipmethod].text;
1441 ast_mutex_lock(&p->lock);
1444 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1445 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1446 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1447 if (!resp && (seqno == p->pendinginvite)) {
1448 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1449 p->pendinginvite = 0;
1451 /* this is our baby */
1453 prev->next = cur->next;
1455 p->packets = cur->next;
1456 if (cur->retransid > -1) {
1457 if (sipdebug && option_debug > 3)
1458 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1459 ast_sched_del(sched, cur->retransid);
1468 ast_mutex_unlock(&p->lock);
1470 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1474 /*! \brief Pretend to ack all packets */
1475 static int __sip_pretend_ack(struct sip_pvt *p)
1477 struct sip_pkt *cur=NULL;
1480 if (cur == p->packets) {
1481 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1486 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
1487 else { /* Unknown packet type */
1491 ast_copy_string(method, p->packets->data, sizeof(method));
1492 c = ast_skip_blanks(method); /* XXX what ? */
1494 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1500 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
1501 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1503 struct sip_pkt *cur;
1505 char *msg = sip_methods[sipmethod].text;
1509 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1510 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1511 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1512 /* this is our baby */
1513 if (cur->retransid > -1) {
1514 if (option_debug > 3 && sipdebug)
1515 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
1516 ast_sched_del(sched, cur->retransid);
1518 cur->retransid = -1;
1525 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");
1530 /*! \brief Copy SIP request, parse it */
1531 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1533 memset(dst, 0, sizeof(*dst));
1534 memcpy(dst->data, src->data, sizeof(dst->data));
1535 dst->len = src->len;
1539 /*! \brief Transmit response on SIP request*/
1540 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1544 if (sip_debug_test_pvt(p)) {
1545 char iabuf[INET_ADDRSTRLEN];
1546 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1547 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);
1549 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);
1551 if (recordhistory) {
1552 struct sip_request tmp;
1553 parse_copy(&tmp, req);
1554 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1557 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
1558 __sip_xmit(p, req->data, req->len);
1564 /*! \brief Send SIP Request to the other part of the dialogue */
1565 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1569 if (sip_debug_test_pvt(p)) {
1570 char iabuf[INET_ADDRSTRLEN];
1571 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1572 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);
1574 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);
1576 if (recordhistory) {
1577 struct sip_request tmp;
1578 parse_copy(&tmp, req);
1579 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1582 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1583 __sip_xmit(p, req->data, req->len);
1587 /*! \brief Pick out text in brackets from character string
1588 \return pointer to terminated stripped string
1589 \param tmp input string that will be modified */
1590 static char *get_in_brackets(char *tmp)
1594 char *first_bracket;
1595 char *second_bracket;
1600 first_quote = strchr(parse, '"');
1601 first_bracket = strchr(parse, '<');
1602 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1604 for (parse = first_quote + 1; *parse; parse++) {
1605 if ((*parse == '"') && (last_char != '\\'))
1610 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1616 if (first_bracket) {
1617 second_bracket = strchr(first_bracket + 1, '>');
1618 if (second_bracket) {
1619 *second_bracket = '\0';
1620 return first_bracket + 1;
1622 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1630 /*! \brief Send SIP MESSAGE text within a call
1631 Called from PBX core sendtext() application */
1632 static int sip_sendtext(struct ast_channel *ast, const char *text)
1634 struct sip_pvt *p = ast->tech_pvt;
1635 int debug = sip_debug_test_pvt(p);
1638 ast_verbose("Sending text %s on %s\n", text, ast->name);
1641 if (ast_strlen_zero(text))
1644 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1645 transmit_message_with_text(p, text);
1649 /*! \brief Update peer object in realtime storage */
1650 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1654 char regseconds[20];
1659 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
1660 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1661 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1664 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
1666 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1669 /*! \brief Automatically add peer extension to dial plan */
1670 static void register_peer_exten(struct sip_peer *peer, int onoff)
1673 char *stringp, *ext;
1674 if (!ast_strlen_zero(global_regcontext)) {
1675 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
1677 while((ext = strsep(&stringp, "&"))) {
1679 ast_add_extension(global_regcontext, 1, ext, 1, NULL, NULL, "Noop",
1680 ast_strdup(peer->name), free, "SIP");
1682 ast_context_remove_extension(global_regcontext, ext, 1, NULL);
1687 /*! \brief Destroy peer object from memory */
1688 static void sip_destroy_peer(struct sip_peer *peer)
1690 if (option_debug > 2)
1691 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
1693 /* Delete it, it needs to disappear */
1695 sip_destroy(peer->call);
1696 if (peer->chanvars) {
1697 ast_variables_destroy(peer->chanvars);
1698 peer->chanvars = NULL;
1700 if (peer->expire > -1)
1701 ast_sched_del(sched, peer->expire);
1702 if (peer->pokeexpire > -1)
1703 ast_sched_del(sched, peer->pokeexpire);
1704 register_peer_exten(peer, FALSE);
1705 ast_free_ha(peer->ha);
1706 if (ast_test_flag((&peer->flags_page2), SIP_PAGE2_SELFDESTRUCT))
1708 else if (ast_test_flag(peer, SIP_REALTIME))
1712 clear_realm_authentication(peer->auth);
1713 peer->auth = (struct sip_auth *) NULL;
1715 ast_dnsmgr_release(peer->dnsmgr);
1719 /*! \brief Update peer data in database (if used) */
1720 static void update_peer(struct sip_peer *p, int expiry)
1722 int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1723 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
1724 (ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) {
1725 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
1730 /*! \brief realtime_peer: Get peer from realtime storage
1731 * Checks the "sippeers" realtime family from extconfig.conf
1732 * \todo Consider adding check of port address when matching here to follow the same
1733 * algorithm as for static peers. Will we break anything by adding that?
1735 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1737 struct sip_peer *peer = NULL;
1738 struct ast_variable *var;
1739 struct ast_variable *tmp;
1740 char *newpeername = (char *) peername;
1743 /* First check on peer name */
1745 var = ast_load_realtime("sippeers", "name", peername, NULL);
1746 else if (sin) { /* Then check on IP address for dynamic peers */
1747 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1748 var = ast_load_realtime("sippeers", "host", iabuf, NULL); /* First check for fixed IP hosts */
1750 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */
1758 for (tmp = var; tmp; tmp = tmp->next) {
1759 /* If this is type=user, then skip this object. */
1760 if (!strcasecmp(tmp->name, "type") &&
1761 !strcasecmp(tmp->value, "user")) {
1762 ast_variables_destroy(var);
1764 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1765 newpeername = tmp->value;
1769 if (!newpeername) { /* Did not find peer in realtime */
1770 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1771 ast_variables_destroy(var);
1772 return (struct sip_peer *) NULL;
1775 /* Peer found in realtime, now build it in memory */
1776 peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1778 ast_variables_destroy(var);
1779 return (struct sip_peer *) NULL;
1782 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1784 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1785 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1786 if (peer->expire > -1) {
1787 ast_sched_del(sched, peer->expire);
1789 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1791 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1793 ast_set_flag(peer, SIP_REALTIME);
1795 ast_variables_destroy(var);
1800 /*! \brief Support routine for find_peer */
1801 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1803 /* We know name is the first field, so we can cast */
1804 struct sip_peer *p = (struct sip_peer *) name;
1805 return !(!inaddrcmp(&p->addr, sin) ||
1806 (ast_test_flag(p, SIP_INSECURE_PORT) &&
1807 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1810 /*! \brief Locate peer by name or ip address
1811 * This is used on incoming SIP message to find matching peer on ip
1812 or outgoing message to find matching peer on name */
1813 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1815 struct sip_peer *p = NULL;
1818 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1820 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
1822 if (!p && realtime) {
1823 p = realtime_peer(peer, sin);
1828 /*! \brief Remove user object from in-memory storage */
1829 static void sip_destroy_user(struct sip_user *user)
1831 if (option_debug > 2)
1832 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
1833 ast_free_ha(user->ha);
1834 if (user->chanvars) {
1835 ast_variables_destroy(user->chanvars);
1836 user->chanvars = NULL;
1838 if (ast_test_flag(user, SIP_REALTIME))
1845 /*! \brief Load user from realtime storage
1846 * Loads user from "sipusers" category in realtime (extconfig.conf)
1847 * Users are matched on From: user name (the domain in skipped) */
1848 static struct sip_user *realtime_user(const char *username)
1850 struct ast_variable *var;
1851 struct ast_variable *tmp;
1852 struct sip_user *user = NULL;
1854 var = ast_load_realtime("sipusers", "name", username, NULL);
1859 for (tmp = var; tmp; tmp = tmp->next) {
1860 if (!strcasecmp(tmp->name, "type") &&
1861 !strcasecmp(tmp->value, "peer")) {
1862 ast_variables_destroy(var);
1867 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1869 if (!user) { /* No user found */
1870 ast_variables_destroy(var);
1874 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1875 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1877 ASTOBJ_CONTAINER_LINK(&userl,user);
1879 /* Move counter from s to r... */
1882 ast_set_flag(user, SIP_REALTIME);
1884 ast_variables_destroy(var);
1888 /*! \brief Locate user by name
1889 * Locates user by name (From: sip uri user name part) first
1890 * from in-memory list (static configuration) then from
1891 * realtime storage (defined in extconfig.conf) */
1892 static struct sip_user *find_user(const char *name, int realtime)
1894 struct sip_user *u = NULL;
1895 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1896 if (!u && realtime) {
1897 u = realtime_user(name);
1902 /*! \brief Create address structure from peer reference */
1903 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1905 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1906 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
1907 if (peer->addr.sin_addr.s_addr) {
1908 r->sa.sin_family = peer->addr.sin_family;
1909 r->sa.sin_addr = peer->addr.sin_addr;
1910 r->sa.sin_port = peer->addr.sin_port;
1912 r->sa.sin_family = peer->defaddr.sin_family;
1913 r->sa.sin_addr = peer->defaddr.sin_addr;
1914 r->sa.sin_port = peer->defaddr.sin_port;
1916 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1921 ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
1922 r->capability = peer->capability;
1923 r->prefs = peer->prefs;
1926 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1927 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1931 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1932 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1934 ast_string_field_set(r, peername, peer->username);
1935 ast_string_field_set(r, authname, peer->username);
1936 ast_string_field_set(r, username, peer->username);
1937 ast_string_field_set(r, peersecret, peer->secret);
1938 ast_string_field_set(r, peermd5secret, peer->md5secret);
1939 ast_string_field_set(r, tohost, peer->tohost);
1940 ast_string_field_set(r, fullcontact, peer->fullcontact);
1941 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1944 tmpcall = ast_strdupa(r->callid);
1946 c = strchr(tmpcall, '@');
1949 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
1953 if (ast_strlen_zero(r->tohost)) {
1954 char iabuf[INET_ADDRSTRLEN];
1956 ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr.s_addr ? peer->addr.sin_addr : peer->defaddr.sin_addr);
1958 ast_string_field_set(r, tohost, iabuf);
1960 if (!ast_strlen_zero(peer->fromdomain))
1961 ast_string_field_set(r, fromdomain, peer->fromdomain);
1962 if (!ast_strlen_zero(peer->fromuser))
1963 ast_string_field_set(r, fromuser, peer->fromuser);
1964 r->maxtime = peer->maxms;
1965 r->callgroup = peer->callgroup;
1966 r->pickupgroup = peer->pickupgroup;
1967 /* Set timer T1 to RTT for this peer (if known by qualify=) */
1968 /* Minimum is settable or default to 100 ms */
1969 if (peer->maxms && peer->lastms)
1970 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
1971 if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
1972 r->noncodeccapability |= AST_RTP_DTMF;
1974 r->noncodeccapability &= ~AST_RTP_DTMF;
1975 ast_string_field_set(r, context, peer->context);
1976 r->rtptimeout = peer->rtptimeout;
1977 r->rtpholdtimeout = peer->rtpholdtimeout;
1978 r->rtpkeepalive = peer->rtpkeepalive;
1979 if (peer->call_limit)
1980 ast_set_flag(r, SIP_CALL_LIMIT);
1985 /*! \brief create address structure from peer name
1986 * Or, if peer not found, find it in the global DNS
1987 * returns TRUE (-1) on failure, FALSE on success */
1988 static int create_addr(struct sip_pvt *dialog, const char *opeer)
1991 struct ast_hostent ahp;
1996 char host[MAXHOSTNAMELEN], *hostn;
1999 ast_copy_string(peer, opeer, sizeof(peer));
2000 port = strchr(peer, ':');
2005 dialog->sa.sin_family = AF_INET;
2006 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2007 p = find_peer(peer, NULL, 1);
2011 if (create_addr_from_peer(dialog, p))
2012 ASTOBJ_UNREF(p, sip_destroy_peer);
2020 portno = atoi(port);
2022 portno = DEFAULT_SIP_PORT;
2024 char service[MAXHOSTNAMELEN];
2027 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2028 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2034 hp = ast_gethostbyname(hostn, &ahp);
2036 ast_string_field_set(dialog, tohost, peer);
2037 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2038 dialog->sa.sin_port = htons(portno);
2039 memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
2042 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2046 ASTOBJ_UNREF(p, sip_destroy_peer);
2051 /*! \brief Scheduled congestion on a call */
2052 static int auto_congest(void *nothing)
2054 struct sip_pvt *p = nothing;
2056 ast_mutex_lock(&p->lock);
2059 if (!ast_mutex_trylock(&p->owner->lock)) {
2060 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2061 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2062 ast_mutex_unlock(&p->owner->lock);
2065 ast_mutex_unlock(&p->lock);
2072 /*! \brief Initiate SIP call from PBX
2073 * used from the dial() application */
2074 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2079 const char *osphandle = NULL;
2081 struct varshead *headp;
2082 struct ast_var_t *current;
2085 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2086 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2090 /* Check whether there is vxml_url, distinctive ring variables */
2091 headp=&ast->varshead;
2092 AST_LIST_TRAVERSE(headp,current,entries) {
2093 /* Check whether there is a VXML_URL variable */
2094 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2095 p->options->vxml_url = ast_var_value(current);
2096 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2097 p->options->uri_options = ast_var_value(current);
2098 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2099 /* Check whether there is a ALERT_INFO variable */
2100 p->options->distinctive_ring = ast_var_value(current);
2101 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2102 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2103 p->options->addsipheaders = 1;
2108 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
2109 p->options->osptoken = ast_var_value(current);
2110 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
2111 osphandle = ast_var_value(current);
2117 ast_set_flag(p, SIP_OUTGOING);
2119 if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
2120 /* Force Disable OSP support */
2122 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
2123 p->options->osptoken = NULL;
2128 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2129 res = update_call_counter(p, INC_CALL_LIMIT);
2131 p->callingpres = ast->cid.cid_pres;
2132 p->jointcapability = p->capability;
2133 transmit_invite(p, SIP_INVITE, 1, 2);
2135 /* Initialize auto-congest time */
2136 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2142 /*! \brief Destroy registry object
2143 Objects created with the register= statement in static configuration */
2144 static void sip_registry_destroy(struct sip_registry *reg)
2147 if (option_debug > 2)
2148 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2151 /* Clear registry before destroying to ensure
2152 we don't get reentered trying to grab the registry lock */
2153 reg->call->registry = NULL;
2154 if (option_debug > 2)
2155 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2156 sip_destroy(reg->call);
2158 if (reg->expire > -1)
2159 ast_sched_del(sched, reg->expire);
2160 if (reg->timeout > -1)
2161 ast_sched_del(sched, reg->timeout);
2162 ast_string_field_free_all(reg);
2168 /*! \brief Execute destrucion of SIP dialog structure, release memory */
2169 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2171 struct sip_pvt *cur, *prev = NULL;
2174 if (sip_debug_test_pvt(p) || option_debug > 2)
2175 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2178 sip_dump_history(p);
2183 if (p->stateid > -1)
2184 ast_extension_state_del(p->stateid, NULL);
2186 ast_sched_del(sched, p->initid);
2187 if (p->autokillid > -1)
2188 ast_sched_del(sched, p->autokillid);
2191 ast_rtp_destroy(p->rtp);
2194 ast_rtp_destroy(p->vrtp);
2197 free_old_route(p->route);
2201 if (p->registry->call == p)
2202 p->registry->call = NULL;
2203 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2206 /* Unlink us from the owner if we have one */
2209 ast_mutex_lock(&p->owner->lock);
2211 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2212 p->owner->tech_pvt = NULL;
2214 ast_mutex_unlock(&p->owner->lock);
2218 while(!AST_LIST_EMPTY(p->history)) {
2219 struct sip_history *hist = AST_LIST_FIRST(p->history);
2220 AST_LIST_REMOVE_HEAD(p->history, list);
2231 prev->next = cur->next;
2240 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2244 ast_sched_del(sched, p->initid);
2246 /* remove all current packets in this dialog */
2247 while((cp = p->packets)) {
2248 p->packets = p->packets->next;
2249 if (cp->retransid > -1) {
2250 ast_sched_del(sched, cp->retransid);
2255 ast_variables_destroy(p->chanvars);
2258 ast_mutex_destroy(&p->lock);
2260 ast_string_field_free_all(p);
2265 /*! \brief update_call_counter: Handle call_limit for SIP users
2266 * Setting a call-limit will cause calls above the limit not to be accepted.
2268 * Remember that for a type=friend, there's one limit for the user and
2269 * another for the peer, not a combined call limit.
2270 * This will cause unexpected behaviour in subscriptions, since a "friend"
2271 * is *two* devices in Asterisk, not one.
2273 * Thought: For realtime, we should propably update storage with inuse counter...
2275 * \return 0 if call is ok (no call limit, below treshold)
2276 * -1 on rejection of call
2279 static int update_call_counter(struct sip_pvt *fup, int event)
2282 int *inuse, *call_limit;
2283 int outgoing = ast_test_flag(fup, SIP_OUTGOING);
2284 struct sip_user *u = NULL;
2285 struct sip_peer *p = NULL;
2287 if (option_debug > 2)
2288 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2289 /* Test if we need to check call limits, in order to avoid
2290 realtime lookups if we do not need it */
2291 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
2294 ast_copy_string(name, fup->username, sizeof(name));
2296 /* Check the list of users */
2297 if (!outgoing) /* Only check users for incoming calls */
2298 u = find_user(name, 1);
2302 call_limit = &u->call_limit;
2305 /* Try to find peer */
2307 p = find_peer(fup->peername, NULL, 1);
2310 call_limit = &p->call_limit;
2311 ast_copy_string(name, fup->peername, sizeof(name));
2313 if (option_debug > 1)
2314 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2319 /* incoming and outgoing affects the inUse counter */
2320 case DEC_CALL_LIMIT:
2322 if (ast_test_flag(fup, SIP_INC_COUNT))
2327 if (option_debug > 1 || sipdebug) {
2328 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2331 case INC_CALL_LIMIT:
2332 if (*call_limit > 0 ) {
2333 if (*inuse >= *call_limit) {
2334 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);
2336 ASTOBJ_UNREF(u, sip_destroy_user);
2338 ASTOBJ_UNREF(p, sip_destroy_peer);
2343 ast_set_flag(fup, SIP_INC_COUNT);
2344 if (option_debug > 1 || sipdebug) {
2345 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2349 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2352 ASTOBJ_UNREF(u, sip_destroy_user);
2354 ASTOBJ_UNREF(p, sip_destroy_peer);
2358 /*! \brief Destroy SIP call structure */
2359 static void sip_destroy(struct sip_pvt *p)
2361 ast_mutex_lock(&iflock);
2362 if (option_debug > 2)
2363 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2364 __sip_destroy(p, 1);
2365 ast_mutex_unlock(&iflock);
2368 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2369 static int hangup_sip2cause(int cause)
2371 /* Possible values taken from causes.h */
2374 case 401: /* Unauthorized */
2375 return AST_CAUSE_CALL_REJECTED;
2376 case 403: /* Not found */
2377 return AST_CAUSE_CALL_REJECTED;
2378 case 404: /* Not found */
2379 return AST_CAUSE_UNALLOCATED;
2380 case 405: /* Method not allowed */
2381 return AST_CAUSE_INTERWORKING;
2382 case 407: /* Proxy authentication required */
2383 return AST_CAUSE_CALL_REJECTED;
2384 case 408: /* No reaction */
2385 return AST_CAUSE_NO_USER_RESPONSE;
2386 case 409: /* Conflict */
2387 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2388 case 410: /* Gone */
2389 return AST_CAUSE_UNALLOCATED;
2390 case 411: /* Length required */
2391 return AST_CAUSE_INTERWORKING;
2392 case 413: /* Request entity too large */
2393 return AST_CAUSE_INTERWORKING;
2394 case 414: /* Request URI too large */
2395 return AST_CAUSE_INTERWORKING;
2396 case 415: /* Unsupported media type */
2397 return AST_CAUSE_INTERWORKING;
2398 case 420: /* Bad extension */
2399 return AST_CAUSE_NO_ROUTE_DESTINATION;
2400 case 480: /* No answer */
2401 return AST_CAUSE_FAILURE;
2402 case 481: /* No answer */
2403 return AST_CAUSE_INTERWORKING;
2404 case 482: /* Loop detected */
2405 return AST_CAUSE_INTERWORKING;
2406 case 483: /* Too many hops */
2407 return AST_CAUSE_NO_ANSWER;
2408 case 484: /* Address incomplete */
2409 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2410 case 485: /* Ambigous */
2411 return AST_CAUSE_UNALLOCATED;
2412 case 486: /* Busy everywhere */
2413 return AST_CAUSE_BUSY;
2414 case 487: /* Request terminated */
2415 return AST_CAUSE_INTERWORKING;
2416 case 488: /* No codecs approved */
2417 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2418 case 491: /* Request pending */
2419 return AST_CAUSE_INTERWORKING;
2420 case 493: /* Undecipherable */
2421 return AST_CAUSE_INTERWORKING;
2422 case 500: /* Server internal failure */
2423 return AST_CAUSE_FAILURE;
2424 case 501: /* Call rejected */
2425 return AST_CAUSE_FACILITY_REJECTED;
2427 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2428 case 503: /* Service unavailable */
2429 return AST_CAUSE_CONGESTION;
2430 case 504: /* Gateway timeout */
2431 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2432 case 505: /* SIP version not supported */
2433 return AST_CAUSE_INTERWORKING;
2434 case 600: /* Busy everywhere */
2435 return AST_CAUSE_USER_BUSY;
2436 case 603: /* Decline */
2437 return AST_CAUSE_CALL_REJECTED;
2438 case 604: /* Does not exist anywhere */
2439 return AST_CAUSE_UNALLOCATED;
2440 case 606: /* Not acceptable */
2441 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2443 return AST_CAUSE_NORMAL;
2449 /*! \brief Convert Asterisk hangup causes to SIP codes
2451 Possible values from causes.h
2452 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
2453 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
2455 In addition to these, a lot of PRI codes is defined in causes.h
2456 ...should we take care of them too ?
2460 ISUP Cause value SIP response
2461 ---------------- ------------
2462 1 unallocated number 404 Not Found
2463 2 no route to network 404 Not found
2464 3 no route to destination 404 Not found
2465 16 normal call clearing --- (*)
2466 17 user busy 486 Busy here
2467 18 no user responding 408 Request Timeout
2468 19 no answer from the user 480 Temporarily unavailable
2469 20 subscriber absent 480 Temporarily unavailable
2470 21 call rejected 403 Forbidden (+)
2471 22 number changed (w/o diagnostic) 410 Gone
2472 22 number changed (w/ diagnostic) 301 Moved Permanently
2473 23 redirection to new destination 410 Gone
2474 26 non-selected user clearing 404 Not Found (=)
2475 27 destination out of order 502 Bad Gateway
2476 28 address incomplete 484 Address incomplete
2477 29 facility rejected 501 Not implemented
2478 31 normal unspecified 480 Temporarily unavailable
2481 static char *hangup_cause2sip(int cause)
2485 case AST_CAUSE_UNALLOCATED: /* 1 */
2486 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
2487 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
2488 return "404 Not Found";
2489 case AST_CAUSE_CONGESTION: /* 34 */
2490 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
2491 return "503 Service Unavailable";
2492 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
2493 return "408 Request Timeout";
2494 case AST_CAUSE_NO_ANSWER: /* 19 */
2495 return "480 Temporarily unavailable";
2496 case AST_CAUSE_CALL_REJECTED: /* 21 */
2497 return "403 Forbidden";
2498 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
2500 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
2501 return "480 Temporarily unavailable";
2502 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2503 return "484 Address incomplete";
2504 case AST_CAUSE_USER_BUSY:
2505 return "486 Busy here";
2506 case AST_CAUSE_FAILURE:
2507 return "500 Server internal failure";
2508 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
2509 return "501 Not Implemented";
2510 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2511 return "503 Service Unavailable";
2512 /* Used in chan_iax2 */
2513 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2514 return "502 Bad Gateway";
2515 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2516 return "488 Not Acceptable Here";
2518 case AST_CAUSE_NOTDEFINED:
2520 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2529 /*! \brief sip_hangup: Hangup SIP call
2530 * Part of PBX interface, called from ast_hangup */
2531 static int sip_hangup(struct ast_channel *ast)
2533 struct sip_pvt *p = ast->tech_pvt;
2534 int needcancel = FALSE;
2535 struct ast_flags locflags = {0};
2538 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
2541 if (option_debug && sipdebug)
2542 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2544 ast_mutex_lock(&p->lock);
2546 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2547 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2550 if (option_debug && sipdebug)
2551 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2552 update_call_counter(p, DEC_CALL_LIMIT);
2553 /* Determine how to disconnect */
2554 if (p->owner != ast) {
2555 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
2556 ast_mutex_unlock(&p->lock);
2559 /* If the call is not UP, we need to send CANCEL instead of BYE */
2560 if (ast->_state != AST_STATE_UP)
2566 ast_dsp_free(p->vad);
2569 ast->tech_pvt = NULL;
2571 ast_mutex_lock(&usecnt_lock);
2573 ast_mutex_unlock(&usecnt_lock);
2574 ast_update_use_count();
2576 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2578 /* Start the process if it's not already started */
2579 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2580 if (needcancel) { /* Outgoing call, not up */
2581 if (ast_test_flag(p, SIP_OUTGOING)) {
2582 /* stop retransmitting an INVITE that has not received a response */
2583 __sip_pretend_ack(p);
2585 /* Send a new request: CANCEL */
2586 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, 0);
2587 /* Actually don't destroy us yet, wait for the 487 on our original
2588 INVITE, but do set an autodestruct just in case we never get it. */
2589 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2591 sip_scheddestroy(p, 32000);
2592 if ( p->initid != -1 ) {
2593 /* channel still up - reverse dec of inUse counter
2594 only if the channel is not auto-congested */
2595 update_call_counter(p, INC_CALL_LIMIT);
2597 } else { /* Incoming call, not up */
2599 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2600 transmit_response_reliable(p, res, &p->initreq);
2602 transmit_response_reliable(p, "603 Declined", &p->initreq);
2604 } else { /* Call is in UP state, send BYE */
2605 if (!p->pendinginvite) {
2607 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2609 /* Note we will need a BYE when this all settles out
2610 but we can't send one while we have "INVITE" outstanding. */
2611 ast_set_flag(p, SIP_PENDINGBYE);
2612 ast_clear_flag(p, SIP_NEEDREINVITE);
2616 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
2617 ast_mutex_unlock(&p->lock);
2621 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
2622 static void try_suggested_sip_codec(struct sip_pvt *p)
2627 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
2631 fmt = ast_getformatbyname(codec);
2633 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n", codec);
2634 if (p->jointcapability & fmt) {
2635 p->jointcapability &= fmt;
2636 p->capability &= fmt;
2638 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2640 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
2644 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
2645 * Part of PBX interface */
2646 static int sip_answer(struct ast_channel *ast)
2649 struct sip_pvt *p = ast->tech_pvt;
2651 ast_mutex_lock(&p->lock);
2652 if (ast->_state != AST_STATE_UP) {
2656 try_suggested_sip_codec(p);
2658 ast_setstate(ast, AST_STATE_UP);
2660 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
2661 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_RELIABLE);
2663 ast_mutex_unlock(&p->lock);
2667 /*! \brief Send frame to media channel (rtp) */
2668 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2670 struct sip_pvt *p = ast->tech_pvt;
2673 switch (frame->frametype) {
2674 case AST_FRAME_VOICE:
2675 if (!(frame->subclass & ast->nativeformats)) {
2676 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2677 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2681 ast_mutex_lock(&p->lock);
2683 /* If channel is not up, activate early media session */
2684 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2685 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2686 ast_set_flag(p, SIP_PROGRESS_SENT);
2688 time(&p->lastrtptx);
2689 res = ast_rtp_write(p->rtp, frame);
2691 ast_mutex_unlock(&p->lock);
2694 case AST_FRAME_VIDEO:
2696 ast_mutex_lock(&p->lock);
2698 /* Activate video early media */
2699 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2700 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2701 ast_set_flag(p, SIP_PROGRESS_SENT);
2703 time(&p->lastrtptx);
2704 res = ast_rtp_write(p->vrtp, frame);
2706 ast_mutex_unlock(&p->lock);
2709 case AST_FRAME_IMAGE:
2713 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2720 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2721 Basically update any ->owner links */
2722 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2724 struct sip_pvt *p = newchan->tech_pvt;
2725 ast_mutex_lock(&p->lock);
2726 if (p->owner != oldchan) {
2727 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2728 ast_mutex_unlock(&p->lock);
2732 ast_mutex_unlock(&p->lock);
2736 /*! \brief Send DTMF character on SIP channel
2737 within one call, we're able to transmit in many methods simultaneously */
2738 static int sip_senddigit(struct ast_channel *ast, char digit)
2740 struct sip_pvt *p = ast->tech_pvt;
2743 ast_mutex_lock(&p->lock);
2744 switch (ast_test_flag(p, SIP_DTMF)) {
2746 transmit_info_with_digit(p, digit);
2748 case SIP_DTMF_RFC2833:
2750 ast_rtp_senddigit(p->rtp, digit);
2752 case SIP_DTMF_INBAND:
2756 ast_mutex_unlock(&p->lock);
2760 /*! \brief Transfer SIP call */
2761 static int sip_transfer(struct ast_channel *ast, const char *dest)
2763 struct sip_pvt *p = ast->tech_pvt;
2766 ast_mutex_lock(&p->lock);
2767 if (ast->_state == AST_STATE_RING)
2768 res = sip_sipredirect(p, dest);
2770 res = transmit_refer(p, dest);
2771 ast_mutex_unlock(&p->lock);
2775 /*! \brief Play indication to user
2776 * With SIP a lot of indications is sent as messages, letting the device play
2777 the indication - busy signal, congestion etc
2778 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
2780 static int sip_indicate(struct ast_channel *ast, int condition)
2782 struct sip_pvt *p = ast->tech_pvt;
2785 ast_mutex_lock(&p->lock);
2787 case AST_CONTROL_RINGING:
2788 if (ast->_state == AST_STATE_RING) {
2789 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
2790 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2791 /* Send 180 ringing if out-of-band seems reasonable */
2792 transmit_response(p, "180 Ringing", &p->initreq);
2793 ast_set_flag(p, SIP_RINGING);
2794 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2797 /* Well, if it's not reasonable, just send in-band */
2802 case AST_CONTROL_BUSY:
2803 if (ast->_state != AST_STATE_UP) {
2804 transmit_response(p, "486 Busy Here", &p->initreq);
2805 ast_set_flag(p, SIP_ALREADYGONE);
2806 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2811 case AST_CONTROL_CONGESTION:
2812 if (ast->_state != AST_STATE_UP) {
2813 transmit_response(p, "503 Service Unavailable", &p->initreq);
2814 ast_set_flag(p, SIP_ALREADYGONE);
2815 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2820 case AST_CONTROL_PROCEEDING:
2821 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2822 transmit_response(p, "100 Trying", &p->initreq);
2827 case AST_CONTROL_PROGRESS:
2828 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2829 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2830 ast_set_flag(p, SIP_PROGRESS_SENT);
2835 case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
2837 ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
2840 case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
2842 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2845 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
2846 if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
2847 transmit_info_with_vidupdate(p);
2856 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2860 ast_mutex_unlock(&p->lock);
2866 /*! \brief Initiate a call in the SIP channel
2867 called from sip_request_call (calls from the pbx ) */
2868 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
2870 struct ast_channel *tmp;
2871 struct ast_variable *v = NULL;
2875 char iabuf[INET_ADDRSTRLEN];
2876 char peer[MAXHOSTNAMELEN];
2879 ast_mutex_unlock(&i->lock);
2880 /* Don't hold a sip pvt lock while we allocate a channel */
2881 tmp = ast_channel_alloc(1);
2882 ast_mutex_lock(&i->lock);
2884 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2887 tmp->tech = &sip_tech;
2888 /* Select our native format based on codec preference until we receive
2889 something from another device to the contrary. */
2890 if (i->jointcapability)
2891 what = i->jointcapability;
2892 else if (i->capability)
2893 what = i->capability;
2895 what = global_capability;
2896 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
2897 fmt = ast_best_codec(tmp->nativeformats);
2900 ast_string_field_build(tmp, name, "SIP/%s-%04x", title, thread_safe_rand() & 0xffff);
2901 else if (strchr(i->fromdomain,':'))
2902 ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2904 ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2906 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2907 i->vad = ast_dsp_new();
2908 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2909 if (global_relaxdtmf)
2910 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2913 tmp->fds[0] = ast_rtp_fd(i->rtp);
2914 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2917 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2918 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2920 if (state == AST_STATE_RING)
2922 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2923 tmp->writeformat = fmt;
2924 tmp->rawwriteformat = fmt;
2925 tmp->readformat = fmt;
2926 tmp->rawreadformat = fmt;
2929 tmp->callgroup = i->callgroup;
2930 tmp->pickupgroup = i->pickupgroup;
2931 tmp->cid.cid_pres = i->callingpres;
2932 if (!ast_strlen_zero(i->accountcode))
2933 ast_string_field_set(tmp, accountcode, i->accountcode);
2935 tmp->amaflags = i->amaflags;
2936 if (!ast_strlen_zero(i->language))
2937 ast_string_field_set(tmp, language, i->language);
2938 if (!ast_strlen_zero(i->musicclass))
2939 ast_string_field_set(tmp, musicclass, i->musicclass);
2941 ast_mutex_lock(&usecnt_lock);
2943 ast_mutex_unlock(&usecnt_lock);
2944 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2945 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2946 if (!ast_strlen_zero(i->cid_num))
2947 tmp->cid.cid_num = ast_strdup(i->cid_num);
2948 if (!ast_strlen_zero(i->cid_name))
2949 tmp->cid.cid_name = ast_strdup(i->cid_name);
2950 if (!ast_strlen_zero(i->rdnis))
2951 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
2952 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2953 tmp->cid.cid_dnid = ast_strdup(i->exten);
2955 if (!ast_strlen_zero(i->uri)) {
2956 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2958 if (!ast_strlen_zero(i->domain)) {
2959 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2961 if (!ast_strlen_zero(i->useragent)) {
2962 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2964 if (!ast_strlen_zero(i->callid)) {
2965 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2968 snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
2969 pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
2971 ast_setstate(tmp, state);
2972 if (state != AST_STATE_DOWN) {
2973 if (ast_pbx_start(tmp)) {
2974 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2975 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
2980 /* Set channel variables for this call from configuration */
2981 for (v = i->chanvars ; v ; v = v->next)
2982 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2987 /*! \brief Reads one line of SIP message body */
2988 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2990 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2991 return ast_skip_blanks(line + nameLen + 1);
2996 /*! \brief Gets all kind of SIP message bodies, including SDP,
2997 but the name wrongly applies _only_ sdp */
2998 static char *get_sdp(struct sip_request *req, char *name)
3001 int len = strlen(name);
3004 for (x = 0; x < req->lines; x++) {
3005 r = get_sdp_by_line(req->line[x], name, len);
3013 static void sdpLineNum_iterator_init(int* iterator)
3018 static char* get_sdp_iterate(int* iterator,
3019 struct sip_request *req, char *name)
3021 int len = strlen(name);
3024 while (*iterator < req->lines) {
3025 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
3032 static char *find_alias(const char *name, char *_default)
3035 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
3036 if (!strcasecmp(aliases[x].fullname, name))
3037 return aliases[x].shortname;
3041 static char *__get_header(struct sip_request *req, const char *name, int *start)
3046 * Technically you can place arbitrary whitespace both before and after the ':' in
3047 * a header, although RFC3261 clearly says you shouldn't before, and place just
3048 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
3049 * a good idea to say you can do it, and if you can do it, why in the hell would.
3050 * you say you shouldn't.
3051 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
3052 * and we always allow spaces after that for compatibility.
3054 for (pass = 0; name && pass < 2;pass++) {
3055 int x, len = strlen(name);
3056 for (x=*start; x<req->headers; x++) {
3057 if (!strncasecmp(req->header[x], name, len)) {
3058 char *r = req->header[x] + len; /* skip name */
3059 if (pedanticsipchecking)
3060 r = ast_skip_blanks(r);
3064 return ast_skip_blanks(r+1);
3068 if (pass == 0) /* Try aliases */
3069 name = find_alias(name, NULL);
3072 /* Don't return NULL, so get_header is always a valid pointer */
3076 /*! \brief Get header from SIP request */
3077 static char *get_header(struct sip_request *req, const char *name)
3080 return __get_header(req, name, &start);
3083 /*! \brief Read RTP from network */
3084 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
3086 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
3087 struct ast_frame *f;
3090 /* We have no RTP allocated for this channel */
3091 return &ast_null_frame;
3096 f = ast_rtp_read(p->rtp); /* RTP Audio */
3099 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
3102 f = ast_rtp_read(p->vrtp); /* RTP Video */
3105 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
3108 f = &ast_null_frame;
3110 /* Don't forward RFC2833 if we're not supposed to */
3111 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
3112 return &ast_null_frame;
3115 /* We already hold the channel lock */
3116 if (f->frametype == AST_FRAME_VOICE) {
3117 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
3119 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
3120 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
3121 ast_set_read_format(p->owner, p->owner->readformat);
3122 ast_set_write_format(p->owner, p->owner->writeformat);
3124 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
3125 f = ast_dsp_process(p->owner, p->vad, f);
3126 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
3127 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
3134 /*! \brief Read SIP RTP from channel */
3135 static struct ast_frame *sip_read(struct ast_channel *ast)
3137 struct ast_frame *fr;
3138 struct sip_pvt *p = ast->tech_pvt;
3140 ast_mutex_lock(&p->lock);
3141 fr = sip_rtp_read(ast, p);
3142 time(&p->lastrtprx);
3143 ast_mutex_unlock(&p->lock);
3148 /*! \brief Generate 32 byte random string for callid's etc */
3149 static char *generate_random_string(char *buf, size_t size)
3155 val[x] = thread_safe_rand();
3156 snprintf(buf, size, "%08x%08x%08x%08x", val[0], val[1], val[2], val[3]);
3161 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
3162 static void build_callid_pvt(struct sip_pvt *pvt)
3164 char iabuf[INET_ADDRSTRLEN];
3167 const char *host = ast_strlen_zero(pvt->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), pvt->ourip) : pvt->fromdomain;
3169 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
3173 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
3174 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
3176 char iabuf[INET_ADDRSTRLEN];
3179 const char *host = ast_strlen_zero(fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), ourip) : fromdomain;
3181 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
3184 /*! \brief Make our SIP dialog tag */
3185 static void make_our_tag(char *tagbuf, size_t len)
3187 snprintf(tagbuf, len, "as%08x", thread_safe_rand());
3190 /*! \brief Allocate SIP_PVT structure and set defaults */
3191 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
3192 int useglobal_nat, const int intended_method)
3196 if (!(p = ast_calloc(1, sizeof(*p))))
3199 if (ast_string_field_init(p, 512)) {
3204 ast_mutex_init(&p->lock);
3206 p->method = intended_method;
3209 p->subscribed = NONE;
3211 p->prefs = default_prefs; /* Set default codecs for this call */
3213 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
3214 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
3217 p->osptimelimit = 0;
3220 memcpy(&p->sa, sin, sizeof(p->sa));
3221 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
3222 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3224 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3227 p->branch = thread_safe_rand();
3228 make_our_tag(p->tag, sizeof(p->tag));
3229 /* Start with 101 instead of 1 */
3232 if (sip_methods[intended_method].need_rtp) {
3233 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3234 if (global_videosupport)
3235 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3236 if (!p->rtp || (global_videosupport && !p->vrtp)) {
3237 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", global_videosupport ? "and video" : "", strerror(errno));
3238 ast_mutex_destroy(&p->lock);
3240 ast_variables_destroy(p->chanvars);
3246 ast_rtp_settos(p->rtp, global_tos);
3248 ast_rtp_settos(p->vrtp, global_tos);
3249 p->rtptimeout = global_rtptimeout;
3250 p->rtpholdtimeout = global_rtpholdtimeout;
3251 p->rtpkeepalive = global_rtpkeepalive;
3254 if (useglobal_nat && sin) {
3255 /* Setup NAT structure according to global settings if we have an address */
3256 ast_copy_flags(p, &global_flags, SIP_NAT);
3257 memcpy(&p->recv, sin, sizeof(p->recv));
3259 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3261 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3264 if (p->method != SIP_REGISTER)
3265 ast_string_field_set(p, fromdomain, default_fromdomain);
3268 build_callid_pvt(p);
3270 ast_string_field_set(p, callid, callid);
3271 ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
3272 /* Assign default music on hold class */
3273 ast_string_field_set(p, musicclass, default_musicclass);
3274 p->capability = global_capability;
3275 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
3276 p->noncodeccapability |= AST_RTP_DTMF;
3277 ast_string_field_set(p, context, default_context);
3279 /* Add to active dialog list */
3280 ast_mutex_lock(&iflock);
3283 ast_mutex_unlock(&iflock);
3285 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
3289 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
3290 Called by handle_request, sipsock_read */
3291 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
3299 callid = get_header(req, "Call-ID");
3301 if (pedanticsipchecking) {
3302 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
3303 we need more to identify a branch - so we have to check branch, from
3304 and to tags to identify a call leg.
3305 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
3308 if (gettag(req, "To", totag, sizeof(totag)))
3309 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
3310 gettag(req, "From", fromtag, sizeof(fromtag));
3312 if (req->method == SIP_RESPONSE)
3318 if (option_debug > 4 )
3319 ast_log(LOG_DEBUG, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
3322 ast_mutex_lock(&iflock);
3324 while(p) { /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
3326 if (req->method == SIP_REGISTER)
3327 found = (!strcmp(p->callid, callid));
3329 found = (!strcmp(p->callid, callid) &&
3330 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
3332 if (option_debug > 4)
3333 ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
3335 /* If we get a new request within an existing to-tag - check the to tag as well */
3336 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
3337 if (p->tag[0] == '\0' && totag[0]) {
3338 /* We have no to tag, but they have. Wrong dialog */
3340 } else if (totag[0]) { /* Both have tags, compare them */
3341 if (strcmp(totag, p->tag)) {
3342 found = FALSE; /* This is not our packet */
3345 if (!found && option_debug > 4)
3346 ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
3351 /* Found the call */
3352 ast_mutex_lock(&p->lock);
3353 ast_mutex_unlock(&iflock);
3358 ast_mutex_unlock(&iflock);
3359 p = sip_alloc(callid, sin, 1, intended_method);
3361 ast_mutex_lock(&p->lock);
3365 /*! \brief Parse register=> line in sip.conf and add to registry */
3366 static int sip_register(char *value, int lineno)
3368 struct sip_registry *reg;
3370 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
3377 ast_copy_string(copy, value, sizeof(copy));
3380 hostname = strrchr(stringp, '@');
3385 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
3386 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
3390 username = strsep(&stringp, ":");
3392 secret = strsep(&stringp, ":");
3394 authuser = strsep(&stringp, ":");
3397 hostname = strsep(&stringp, "/");
3399 contact = strsep(&stringp, "/");
3400 if (ast_strlen_zero(contact))
3403 hostname = strsep(&stringp, ":");
3404 porta = strsep(&stringp, ":");
3406 if (porta && !atoi(porta)) {
3407 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3410 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
3411 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
3415 if (ast_string_field_init(reg, 256)) {
3416 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
3423 ast_string_field_set(reg, contact, contact);
3425 ast_string_field_set(reg, username, username);
3427 ast_string_field_set(reg, hostname, hostname);
3429 ast_string_field_set(reg, authuser, authuser);
3431 ast_string_field_set(reg, secret, secret);
3434 reg->refresh = default_expiry;
3435 reg->portno = porta ? atoi(porta) : 0;
3436 reg->callid_valid = FALSE;
3438 ASTOBJ_CONTAINER_LINK(®l, reg); /* Add the new registry entry to the list */
3439 ASTOBJ_UNREF(reg,sip_registry_destroy);
3443 /*! \brief Parse multiline SIP headers into one header
3444 This is enabled if pedanticsipchecking is enabled */
3445 static int lws2sws(char *msgbuf, int len)
3451 /* Eliminate all CRs */
3452 if (msgbuf[h] == '\r') {
3456 /* Check for end-of-line */
3457 if (msgbuf[h] == '\n') {
3458 /* Check for end-of-message */
3461 /* Check for a continuation line */
3462 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
3463 /* Merge continuation line */
3467 /* Propagate LF and start new line */
3468 msgbuf[t++] = msgbuf[h++];
3472 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
3477 msgbuf[t++] = msgbuf[h++];
3481 msgbuf[t++] = msgbuf[h++];
3489 /*! \brief Parse a SIP message */
3490 static void parse_request(struct sip_request *req)
3492 /* Divide fields by NULL's */
3498 /* First header starts immediately */
3502 /* We've got a new header */
3505 if (sipdebug && option_debug > 3)