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
33 * \todo Better support of forking
41 #include <sys/socket.h>
42 #include <sys/ioctl.h>
49 #include <sys/signal.h>
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <arpa/inet.h>
53 #include <netinet/ip.h>
58 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
60 #include "asterisk/lock.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/config.h"
63 #include "asterisk/logger.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/options.h"
67 #include "asterisk/lock.h"
68 #include "asterisk/sched.h"
69 #include "asterisk/io.h"
70 #include "asterisk/rtp.h"
71 #include "asterisk/acl.h"
72 #include "asterisk/manager.h"
73 #include "asterisk/callerid.h"
74 #include "asterisk/cli.h"
75 #include "asterisk/app.h"
76 #include "asterisk/musiconhold.h"
77 #include "asterisk/dsp.h"
78 #include "asterisk/features.h"
79 #include "asterisk/acl.h"
80 #include "asterisk/srv.h"
81 #include "asterisk/astdb.h"
82 #include "asterisk/causes.h"
83 #include "asterisk/utils.h"
84 #include "asterisk/file.h"
85 #include "asterisk/astobj.h"
86 #include "asterisk/dnsmgr.h"
87 #include "asterisk/devicestate.h"
88 #include "asterisk/linkedlists.h"
89 #include "asterisk/stringfields.h"
92 #include "asterisk/astosp.h"
103 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
104 #ifndef IPTOS_MINCOST
105 #define IPTOS_MINCOST 0x02
108 /* #define VOCAL_DATA_HACK */
110 #define DEFAULT_DEFAULT_EXPIRY 120
111 #define DEFAULT_MIN_EXPIRY 60
112 #define DEFAULT_MAX_EXPIRY 3600
113 #define DEFAULT_REGISTRATION_TIMEOUT 20
114 #define DEFAULT_MAX_FORWARDS "70"
116 /* guard limit must be larger than guard secs */
117 /* guard min must be < 1000, and should be >= 250 */
118 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
119 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
121 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
122 GUARD_PCT turns out to be lower than this, it
123 will use this time instead.
124 This is in milliseconds. */
125 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
126 below EXPIRY_GUARD_LIMIT */
127 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
129 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
130 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
131 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
132 static int expiry = DEFAULT_EXPIRY;
135 #define MAX(a,b) ((a) > (b) ? (a) : (b))
138 #define CALLERID_UNKNOWN "Unknown"
142 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
143 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
144 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
146 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
147 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
148 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
150 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
151 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
154 static const char desc[] = "Session Initiation Protocol (SIP)";
155 static const char channeltype[] = "SIP";
156 static const char config[] = "sip.conf";
157 static const char notify_config[] = "sip_notify.conf";
162 /* Do _NOT_ make any changes to this enum, or the array following it;
163 if you think you are doing the right thing, you are probably
164 not doing the right thing. If you think there are changes
165 needed, get someone else to review them first _before_
166 submitting a patch. If these two lists do not match properly
167 bad things will happen.
170 enum subscriptiontype {
179 static const struct cfsubscription_types {
180 enum subscriptiontype type;
181 const char * const event;
182 const char * const mediatype;
183 const char * const text;
184 } subscription_types[] = {
185 { NONE, "-", "unknown", "unknown" },
186 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
187 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
188 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
189 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
190 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" } /* Pre-RFC 3863 with MS additions */
217 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
218 static const struct cfsip_methods {
220 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
223 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
224 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
225 { SIP_REGISTER, NO_RTP, "REGISTER" },
226 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
227 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
228 { SIP_INVITE, RTP, "INVITE" },
229 { SIP_ACK, NO_RTP, "ACK" },
230 { SIP_PRACK, NO_RTP, "PRACK" },
231 { SIP_BYE, NO_RTP, "BYE" },
232 { SIP_REFER, NO_RTP, "REFER" },
233 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
234 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
235 { SIP_UPDATE, NO_RTP, "UPDATE" },
236 { SIP_INFO, NO_RTP, "INFO" },
237 { SIP_CANCEL, NO_RTP, "CANCEL" },
238 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
241 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
242 static const struct cfalias {
243 char * const fullname;
244 char * const shortname;
246 { "Content-Type", "c" },
247 { "Content-Encoding", "e" },
251 { "Content-Length", "l" },
254 { "Supported", "k" },
256 { "Referred-By", "b" },
257 { "Allow-Events", "u" },
260 { "Accept-Contact", "a" },
261 { "Reject-Contact", "j" },
262 { "Request-Disposition", "d" },
263 { "Session-Expires", "x" },
266 /*! Define SIP option tags, used in Require: and Supported: headers
267 We need to be aware of these properties in the phones to use
268 the replace: header. We should not do that without knowing
269 that the other end supports it...
270 This is nothing we can configure, we learn by the dialog
271 Supported: header on the REGISTER (peer) or the INVITE
273 We are not using many of these today, but will in the future.
274 This is documented in RFC 3261
277 #define NOT_SUPPORTED 0
279 #define SIP_OPT_REPLACES (1 << 0)
280 #define SIP_OPT_100REL (1 << 1)
281 #define SIP_OPT_TIMER (1 << 2)
282 #define SIP_OPT_EARLY_SESSION (1 << 3)
283 #define SIP_OPT_JOIN (1 << 4)
284 #define SIP_OPT_PATH (1 << 5)
285 #define SIP_OPT_PREF (1 << 6)
286 #define SIP_OPT_PRECONDITION (1 << 7)
287 #define SIP_OPT_PRIVACY (1 << 8)
288 #define SIP_OPT_SDP_ANAT (1 << 9)
289 #define SIP_OPT_SEC_AGREE (1 << 10)
290 #define SIP_OPT_EVENTLIST (1 << 11)
291 #define SIP_OPT_GRUU (1 << 12)
292 #define SIP_OPT_TARGET_DIALOG (1 << 13)
294 /*! \brief List of well-known SIP options. If we get this in a require,
295 we should check the list and answer accordingly. */
296 static const struct cfsip_options {
297 int id; /*!< Bitmap ID */
298 int supported; /*!< Supported by Asterisk ? */
299 char * const text; /*!< Text id, as in standard */
301 /* Replaces: header for transfer */
302 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
303 /* RFC3262: PRACK 100% reliability */
304 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
305 /* SIP Session Timers */
306 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
307 /* RFC3959: SIP Early session support */
308 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
309 /* SIP Join header support */
310 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
311 /* RFC3327: Path support */
312 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
313 /* RFC3840: Callee preferences */
314 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
315 /* RFC3312: Precondition support */
316 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
317 /* RFC3323: Privacy with proxies*/
318 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
319 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
320 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
321 /* RFC3329: Security agreement mechanism */
322 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
323 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
324 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
325 /* GRUU: Globally Routable User Agent URI's */
326 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
327 /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
328 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
332 /*! \brief SIP Methods we support */
333 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
335 /*! \brief SIP Extensions we support */
336 #define SUPPORTED_EXTENSIONS "replaces"
338 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
340 /* Default values, set and reset in reload_config before reading configuration */
341 /* These are default values in the source. There are other recommended values in the
342 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
343 yet encouraging new behaviour on new installations
345 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
346 #define DEFAULT_CONTEXT "default"
347 #define DEFAULT_MUSICCLASS "default"
348 #define DEFAULT_VMEXTEN "asterisk"
349 #define DEFAULT_CALLERID "asterisk"
350 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
351 #define DEFAULT_MWITIME 10
352 #define DEFAULT_ALLOWGUEST TRUE
353 #define DEFAULT_VIDEOSUPPORT FALSE
354 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
355 #define DEFAULT_COMPACTHEADERS FALSE
356 #define DEFAULT_TOS FALSE
357 #define DEFAULT_ALLOW_EXT_DOM TRUE
358 #define DEFAULT_REALM "asterisk"
359 #define DEFAULT_NOTIFYRINGING TRUE
360 #define DEFAULT_PEDANTIC FALSE
361 #define DEFAULT_AUTOCREATEPEER FALSE
362 #define DEFAULT_QUALIFY FALSE
363 #ifndef DEFAULT_USERAGENT
364 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
367 /* Default setttings are used as a channel setting and as a default when
368 configuring devices */
369 static char default_context[AST_MAX_CONTEXT];
370 static char default_subscribecontext[AST_MAX_CONTEXT];
371 static char default_language[MAX_LANGUAGE];
372 static char default_callerid[AST_MAX_EXTENSION];
373 static char default_fromdomain[AST_MAX_EXTENSION];
374 static char default_notifymime[AST_MAX_EXTENSION];
375 static int default_qualify; /*!< Default Qualify= setting */
376 static char default_vmexten[AST_MAX_EXTENSION];
377 static char default_musicclass[MAX_MUSICCLASS]; /*!< Global music on hold class */
379 /* Global settings only apply to the channel */
380 static int global_notifyringing; /*!< Send notifications on ringing */
381 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
382 static int pedanticsipchecking; /*!< Extra checking ? Default off */
383 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
384 static int relaxdtmf; /*!< Relax DTMF */
385 static int global_rtptimeout; /*!< Time out call if no RTP */
386 static int global_rtpholdtimeout;
387 static int global_rtpkeepalive; /*!< Send RTP keepalives */
388 static int global_reg_timeout;
389 static int global_regattempts_max; /*!< Registration attempts before giving up */
390 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
391 static int global_mwitime; /*!< Time between MWI checks for peers */
392 static int global_tos; /*!< IP Type of service */
393 static int global_videosupport; /*!< Videosupport on or off */
394 static int compactheaders; /*!< send compact sip headers */
395 static int recordhistory; /*!< Record SIP history. Off by default */
396 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
397 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
398 static char regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
399 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
400 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
402 /*! \brief Codecs that we support by default: */
403 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
404 static int noncodeccapability = AST_RTP_DTMF;
406 /* Object counters */
407 static int suserobjs = 0; /*!< Static users */
408 static int ruserobjs = 0; /*!< Realtime users */
409 static int speerobjs = 0; /*!< Statis peers */
410 static int rpeerobjs = 0; /*!< Realtime peers */
411 static int apeerobjs = 0; /*!< Autocreated peer objects */
412 static int regobjs = 0; /*!< Registry objects */
414 static struct ast_flags global_flags = {0}; /*!< global SIP_ flags */
415 static struct ast_flags global_flags_page2 = {0}; /*!< more global SIP_ flags */
417 static int usecnt =0;
419 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
421 AST_MUTEX_DEFINE_STATIC(rand_lock); /*!< Lock for thread-safe random generator */
423 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
424 AST_MUTEX_DEFINE_STATIC(iflock);
426 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
427 when it's doing something critical. */
428 AST_MUTEX_DEFINE_STATIC(netlock);
430 AST_MUTEX_DEFINE_STATIC(monlock);
432 /*! \brief This is the thread for the monitor which checks for input on the channels
433 which are not currently in use. */
434 static pthread_t monitor_thread = AST_PTHREADT_NULL;
436 static int restart_monitor(void);
439 static struct in_addr __ourip;
440 static struct sockaddr_in outboundproxyip;
442 static struct sockaddr_in debugaddr;
445 static struct sched_context *sched;
446 static struct io_context *io;
449 #define DEC_CALL_LIMIT 0
450 #define INC_CALL_LIMIT 1
452 static struct ast_codec_pref prefs;
455 /*! \brief sip_request: The data grabbed from the UDP socket */
457 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
458 char *rlPart2; /*!< The Request URI or Response Status */
459 int len; /*!< Length */
460 int headers; /*!< # of SIP Headers */
461 int method; /*!< Method of this request */
462 char *header[SIP_MAX_HEADERS];
463 int lines; /*!< SDP Content */
464 char *line[SIP_MAX_LINES];
465 char data[SIP_MAX_PACKET];
466 int debug; /*!< Debug flag for this packet */
467 unsigned int flags; /*!< SIP_PKT Flags for this packet */
472 /*! \brief Parameters to the transmit_invite function */
473 struct sip_invite_param {
474 const char *distinctive_ring; /*!< Distinctive ring header */
475 const char *osptoken; /*!< OSP token for this call */
476 int addsipheaders; /*!< Add extra SIP headers */
477 const char *uri_options; /*!< URI options to add to the URI */
478 const char *vxml_url; /*!< VXML url for Cisco phones */
479 char *auth; /*!< Authentication */
480 char *authheader; /*!< Auth header */
481 enum sip_auth_type auth_type; /*!< Authentication type */
485 struct sip_route *next;
490 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
491 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
495 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
496 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
497 enum domain_mode mode; /*!< How did we find this domain? */
498 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
501 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
504 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
506 AST_LIST_ENTRY(sip_history) list;
507 char event[0]; /* actually more, depending on needs */
510 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
512 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
514 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
515 char username[256]; /*!< Username */
516 char secret[256]; /*!< Secret */
517 char md5secret[256]; /*!< MD5Secret */
518 struct sip_auth *next; /*!< Next auth structure in list */
521 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
522 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed */
523 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
524 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
525 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
526 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
527 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
528 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
529 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
530 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
531 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
532 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
533 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
534 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
535 #define SIP_SELFDESTRUCT (1 << 14)
536 #define SIP_DYNAMIC (1 << 15) /*!< Is this a dynamic peer? */
537 /* --- Choices for DTMF support in SIP channel */
538 #define SIP_DTMF (3 << 16) /*!< three settings, uses two bits */
539 #define SIP_DTMF_RFC2833 (0 << 16) /*!< RTP DTMF */
540 #define SIP_DTMF_INBAND (1 << 16) /*!< Inband audio, only for ULAW/ALAW */
541 #define SIP_DTMF_INFO (2 << 16) /*!< SIP Info messages */
542 #define SIP_DTMF_AUTO (3 << 16) /*!< AUTO switch between rfc2833 and in-band DTMF */
544 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
545 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
546 #define SIP_NAT_RFC3581 (1 << 18)
547 #define SIP_NAT_ROUTE (2 << 18)
548 #define SIP_NAT_ALWAYS (3 << 18)
549 /* re-INVITE related settings */
550 #define SIP_REINVITE (3 << 20) /*!< two bits used */
551 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
552 #define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
553 /* "insecure" settings */
554 #define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */
555 #define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */
556 /* Sending PROGRESS in-band settings */
557 #define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */
558 #define SIP_PROG_INBAND_NEVER (0 << 24)
559 #define SIP_PROG_INBAND_NO (1 << 24)
560 #define SIP_PROG_INBAND_YES (2 << 24)
561 /* Open Settlement Protocol authentication */
562 #define SIP_OSPAUTH (3 << 26) /*!< four settings, uses two bits */
563 #define SIP_OSPAUTH_NO (0 << 26)
564 #define SIP_OSPAUTH_GATEWAY (1 << 26)
565 #define SIP_OSPAUTH_PROXY (2 << 26)
566 #define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
568 #define SIP_CALL_ONHOLD (1 << 28)
569 #define SIP_CALL_LIMIT (1 << 29)
570 /* Remote Party-ID Support */
571 #define SIP_SENDRPID (1 << 30)
572 /* Did this connection increment the counter of in-use calls? */
573 #define SIP_INC_COUNT (1 << 31)
575 #define SIP_FLAGS_TO_COPY \
576 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
577 SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
578 SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
580 /* a new page of flags for peer */
581 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
582 #define SIP_PAGE2_RTUPDATE (1 << 1)
583 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
584 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
585 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
586 #define SIP_PAGE2_DEBUG (3 << 5)
587 #define SIP_PAGE2_DEBUG_CONFIG (1 << 5)
588 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 6)
590 /* SIP packet flags */
591 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
592 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
594 #define sipdebug ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG)
595 #define sipdebug_config ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG_CONFIG)
596 #define sipdebug_console ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG_CONSOLE)
598 static int global_rtautoclear = 120;
600 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
601 static struct sip_pvt {
602 ast_mutex_t lock; /*!< Dialog private lock */
603 int method; /*!< SIP method that opened this dialog */
604 AST_DECLARE_STRING_FIELDS(
605 AST_STRING_FIELD(callid); /*!< Global CallID */
606 AST_STRING_FIELD(randdata); /*!< Random data */
607 AST_STRING_FIELD(accountcode); /*!< Account code */
608 AST_STRING_FIELD(realm); /*!< Authorization realm */
609 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
610 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
611 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
612 AST_STRING_FIELD(domain); /*!< Authorization domain */
613 AST_STRING_FIELD(refer_to); /*!< Place to store REFER-TO extension */
614 AST_STRING_FIELD(referred_by); /*!< Place to store REFERRED-BY extension */
615 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
616 AST_STRING_FIELD(from); /*!< The From: header */
617 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
618 AST_STRING_FIELD(exten); /*!< Extension where to start */
619 AST_STRING_FIELD(context); /*!< Context for this call */
620 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
621 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
622 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
623 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
624 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
625 AST_STRING_FIELD(language); /*!< Default language for this call */
626 AST_STRING_FIELD(musicclass); /*!< Music on Hold class */
627 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
628 AST_STRING_FIELD(theirtag); /*!< Their tag */
629 AST_STRING_FIELD(username); /*!< [user] name */
630 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
631 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
632 AST_STRING_FIELD(uri); /*!< Original requested URI */
633 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
634 AST_STRING_FIELD(peersecret); /*!< Password */
635 AST_STRING_FIELD(peermd5secret);
636 AST_STRING_FIELD(cid_num); /*!< Caller*ID */
637 AST_STRING_FIELD(cid_name); /*!< Caller*ID */
638 AST_STRING_FIELD(via); /*!< Via: header */
639 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
640 AST_STRING_FIELD(our_contact); /*!< Our contact header */
641 AST_STRING_FIELD(rpid); /*!< Our RPID header */
642 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
644 struct ast_codec_pref prefs; /*!< codec prefs */
645 unsigned int ocseq; /*!< Current outgoing seqno */
646 unsigned int icseq; /*!< Current incoming seqno */
647 ast_group_t callgroup; /*!< Call group */
648 ast_group_t pickupgroup; /*!< Pickup group */
649 int lastinvite; /*!< Last Cseq of invite */
650 unsigned int flags; /*!< SIP_ flags */
651 int timer_t1; /*!< SIP timer T1, ms rtt */
652 unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */
653 int capability; /*!< Special capability (codec) */
654 int jointcapability; /*!< Supported capability at both ends (codecs ) */
655 int peercapability; /*!< Supported peer capability */
656 int prefcodec; /*!< Preferred codec (outbound only) */
657 int noncodeccapability;
658 int callingpres; /*!< Calling presentation */
659 int authtries; /*!< Times we've tried to authenticate */
660 int expiry; /*!< How long we take to expire */
661 int branch; /*!< One random number */
662 char tag[11]; /*!< Another random number */
663 int sessionid; /*!< SDP Session ID */
664 int sessionversion; /*!< SDP Session Version */
665 struct sockaddr_in sa; /*!< Our peer */
666 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
667 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
668 int redircodecs; /*!< Redirect codecs */
669 struct sockaddr_in recv; /*!< Received as */
670 struct in_addr ourip; /*!< Our IP */
671 struct ast_channel *owner; /*!< Who owns us */
672 struct sip_pvt *refer_call; /*!< Call we are referring */
673 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
674 int route_persistant; /*!< Is this the "real" route? */
675 struct sip_auth *peerauth; /*!< Realm authentication */
676 int noncecount; /*!< Nonce-count */
677 char lastmsg[256]; /*!< Last Message sent/received */
678 int amaflags; /*!< AMA Flags */
679 int pendinginvite; /*!< Any pending invite */
681 int osphandle; /*!< OSP Handle for call */
682 time_t ospstart; /*!< OSP Start time */
683 unsigned int osptimelimit; /*!< OSP call duration limit */
685 struct sip_request initreq; /*!< Initial request */
687 int maxtime; /*!< Max time for first response */
688 int initid; /*!< Auto-congest ID if appropriate */
689 int autokillid; /*!< Auto-kill ID */
690 time_t lastrtprx; /*!< Last RTP received */
691 time_t lastrtptx; /*!< Last RTP sent */
692 int rtptimeout; /*!< RTP timeout time */
693 int rtpholdtimeout; /*!< RTP timeout when on hold */
694 int rtpkeepalive; /*!< Send RTP packets for keepalive */
695 enum subscriptiontype subscribed; /*!< Is this dialog a subscription? */
697 int laststate; /*!< Last known extension state */
700 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
702 struct sip_peer *peerpoke; /*!< If this dialog is to poke a peer, which one */
703 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
704 struct ast_rtp *rtp; /*!< RTP Session */
705 struct ast_rtp *vrtp; /*!< Video RTP session */
706 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
707 struct sip_history_head *history; /*!< History of this SIP dialog */
708 struct ast_variable *chanvars; /*!< Channel variables to set for call */
709 struct sip_pvt *next; /*!< Next dialog in chain */
710 struct sip_invite_param *options; /*!< Options for INVITE */
713 #define FLAG_RESPONSE (1 << 0)
714 #define FLAG_FATAL (1 << 1)
716 /*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
718 struct sip_pkt *next; /*!< Next packet */
719 int retrans; /*!< Retransmission number */
720 int method; /*!< SIP method for this packet */
721 int seqno; /*!< Sequence number */
722 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
723 struct sip_pvt *owner; /*!< Owner AST call */
724 int retransid; /*!< Retransmission ID */
725 int timer_a; /*!< SIP timer A, retransmission timer */
726 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
727 int packetlen; /*!< Length of packet */
731 /*! \brief Structure for SIP user data. User's place calls to us */
733 /* Users who can access various contexts */
734 ASTOBJ_COMPONENTS(struct sip_user);
735 char secret[80]; /*!< Password */
736 char md5secret[80]; /*!< Password in md5 */
737 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
738 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
739 char cid_num[80]; /*!< Caller ID num */
740 char cid_name[80]; /*!< Caller ID name */
741 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
742 char language[MAX_LANGUAGE]; /*!< Default language for this user */
743 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
744 char useragent[256]; /*!< User agent in SIP request */
745 struct ast_codec_pref prefs; /*!< codec prefs */
746 ast_group_t callgroup; /*!< Call group */
747 ast_group_t pickupgroup; /*!< Pickup Group */
748 unsigned int flags; /*!< SIP flags */
749 unsigned int sipoptions; /*!< Supported SIP options */
750 struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
751 int amaflags; /*!< AMA flags for billing */
752 int callingpres; /*!< Calling id presentation */
753 int capability; /*!< Codec capability */
754 int inUse; /*!< Number of calls in use */
755 int call_limit; /*!< Limit of concurrent calls */
756 struct ast_ha *ha; /*!< ACL setting */
757 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
760 /* Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
762 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
763 /*!< peer->name is the unique name of this object */
764 char secret[80]; /*!< Password */
765 char md5secret[80]; /*!< Password in MD5 */
766 struct sip_auth *auth; /*!< Realm authentication list */
767 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
768 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
769 char username[80]; /*!< Temporary username until registration */
770 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
771 int amaflags; /*!< AMA Flags (for billing) */
772 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
773 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
774 char fromuser[80]; /*!< From: user when calling this peer */
775 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
776 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
777 char cid_num[80]; /*!< Caller ID num */
778 char cid_name[80]; /*!< Caller ID name */
779 int callingpres; /*!< Calling id presentation */
780 int inUse; /*!< Number of calls in use */
781 int call_limit; /*!< Limit of concurrent calls */
782 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
783 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
784 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
785 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
786 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
787 struct ast_codec_pref prefs; /*!< codec prefs */
789 time_t lastmsgcheck; /*!< Last time we checked for MWI */
790 unsigned int flags; /*!< SIP flags */
791 unsigned int sipoptions; /*!< Supported SIP options */
792 struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
793 int expire; /*!< When to expire this peer registration */
794 int capability; /*!< Codec capability */
795 int rtptimeout; /*!< RTP timeout */
796 int rtpholdtimeout; /*!< RTP Hold Timeout */
797 int rtpkeepalive; /*!< Send RTP packets for keepalive */
798 ast_group_t callgroup; /*!< Call group */
799 ast_group_t pickupgroup; /*!< Pickup group */
800 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
801 struct sockaddr_in addr; /*!< IP address of peer */
804 struct sip_pvt *call; /*!< Call pointer */
805 int pokeexpire; /*!< When to expire poke (qualify= checking) */
806 int lastms; /*!< How long last response took (in ms), or -1 for no response */
807 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
808 struct timeval ps; /*!< Ping send time */
810 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
811 struct ast_ha *ha; /*!< Access control list */
812 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
816 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
817 static int sip_reloading = 0;
819 /* States for outbound registrations (with register= lines in sip.conf */
820 #define REG_STATE_UNREGISTERED 0
821 #define REG_STATE_REGSENT 1
822 #define REG_STATE_AUTHSENT 2
823 #define REG_STATE_REGISTERED 3
824 #define REG_STATE_REJECTED 4
825 #define REG_STATE_TIMEOUT 5
826 #define REG_STATE_NOAUTH 6
827 #define REG_STATE_FAILED 7
830 /*! \brief sip_registry: Registrations with other SIP proxies */
831 struct sip_registry {
832 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
833 AST_DECLARE_STRING_FIELDS(
834 AST_STRING_FIELD(callid); /*!< Global Call-ID */
835 AST_STRING_FIELD(realm); /*!< Authorization realm */
836 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
837 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
838 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
839 AST_STRING_FIELD(domain); /*!< Authorization domain */
840 AST_STRING_FIELD(username); /*!< Who we are registering as */
841 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
842 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
843 AST_STRING_FIELD(secret); /*!< Password in clear text */
844 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
845 AST_STRING_FIELD(contact); /*!< Contact extension */
846 AST_STRING_FIELD(random);
848 int portno; /*!< Optional port override */
849 int expire; /*!< Sched ID of expiration */
850 int regattempts; /*!< Number of attempts (since the last success) */
851 int timeout; /*!< sched id of sip_reg_timeout */
852 int refresh; /*!< How often to refresh */
853 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
854 int regstate; /*!< Registration state (see above) */
855 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
856 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
857 struct sockaddr_in us; /*!< Who the server thinks we are */
858 int noncecount; /*!< Nonce-count */
859 char lastmsg[256]; /*!< Last Message sent/received */
862 /*! \brief The user list: Users and friends */
863 static struct ast_user_list {
864 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
867 /*! \brief The peer list: Peers and Friends */
868 static struct ast_peer_list {
869 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
872 /*! \brief The register list: Other SIP proxys we register with and place calls to */
873 static struct ast_register_list {
874 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
879 static int __sip_do_register(struct sip_registry *r);
881 static int sipsock = -1;
884 static struct sockaddr_in bindaddr = { 0, };
885 static struct sockaddr_in externip;
886 static char externhost[MAXHOSTNAMELEN] = "";
887 static time_t externexpire = 0;
888 static int externrefresh = 10;
889 static struct ast_ha *localaddr;
890 static int callevents; /*!< Whether we send manager events or not */
892 /* The list of manual NOTIFY types we know how to send */
893 struct ast_config *notify_types;
895 static struct sip_auth *authl = NULL; /*!< Authentication list */
898 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
899 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
900 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
901 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, const char *rand, int reliable, char *header, int stale);
902 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
903 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
904 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
905 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
906 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
907 static int transmit_info_with_vidupdate(struct sip_pvt *p);
908 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
909 static int transmit_refer(struct sip_pvt *p, const char *dest);
910 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
911 static struct sip_peer *temp_peer(const char *name);
912 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
913 static void free_old_route(struct sip_route *route);
914 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
915 static int update_call_counter(struct sip_pvt *fup, int event);
916 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
917 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
918 static int sip_do_reload(void);
919 static int expire_register(void *data);
921 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
922 static int sip_devicestate(void *data);
923 static int sip_sendtext(struct ast_channel *ast, const char *text);
924 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
925 static int sip_hangup(struct ast_channel *ast);
926 static int sip_answer(struct ast_channel *ast);
927 static struct ast_frame *sip_read(struct ast_channel *ast);
928 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
929 static int sip_indicate(struct ast_channel *ast, int condition);
930 static int sip_transfer(struct ast_channel *ast, const char *dest);
931 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
932 static int sip_senddigit(struct ast_channel *ast, char digit);
933 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
934 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
935 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
936 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
937 static void append_date(struct sip_request *req); /* Append date to SIP packet */
938 static int determine_firstline_parts(struct sip_request *req);
939 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
940 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
941 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate);
942 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
943 int find_sip_method(char *msg);
944 unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported);
946 /*! \brief Definition of this channel for PBX channel registration */
947 static const struct ast_channel_tech sip_tech = {
949 .description = "Session Initiation Protocol (SIP)",
950 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
951 .properties = AST_CHAN_TP_WANTSJITTER,
952 .requester = sip_request_call,
953 .devicestate = sip_devicestate,
955 .hangup = sip_hangup,
956 .answer = sip_answer,
959 .write_video = sip_write,
960 .indicate = sip_indicate,
961 .transfer = sip_transfer,
963 .send_digit = sip_senddigit,
964 .bridge = ast_rtp_bridge,
965 .send_text = sip_sendtext,
969 \brief Thread-safe random number generator
970 \return a random number
972 This function uses a mutex lock to guarantee that no
973 two threads will receive the same random number.
975 static force_inline int thread_safe_rand(void)
979 ast_mutex_lock(&rand_lock);
981 ast_mutex_unlock(&rand_lock);
986 /*! \brief find_sip_method: Find SIP method from header
987 * Strictly speaking, SIP methods are case SENSITIVE, but we don't check
988 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
989 int find_sip_method(char *msg)
993 if (ast_strlen_zero(msg))
996 for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
997 if (!strcasecmp(sip_methods[i].text, msg))
998 res = sip_methods[i].id;
1003 /*! \brief parse_sip_options: Parse supported header in incoming packet */
1004 unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
1008 char *temp = ast_strdupa(supported);
1010 unsigned int profile = 0;
1012 if (ast_strlen_zero(supported) )
1015 if (option_debug > 2 && sipdebug)
1016 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1021 if ( (sep = strchr(next, ',')) != NULL) {
1025 while (*next == ' ') /* Skip spaces */
1027 if (option_debug > 2 && sipdebug)
1028 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1029 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
1030 if (!strcasecmp(next, sip_options[i].text)) {
1031 profile |= sip_options[i].id;
1033 if (option_debug > 2 && sipdebug)
1034 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1038 if (option_debug > 2 && sipdebug)
1039 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1043 pvt->sipoptions = profile;
1045 ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
1050 /*! \brief sip_debug_test_addr: See if we pass debug IP filter */
1051 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
1055 if (debugaddr.sin_addr.s_addr) {
1056 if (((ntohs(debugaddr.sin_port) != 0)
1057 && (debugaddr.sin_port != addr->sin_port))
1058 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1064 /*! \brief sip_debug_test_pvt: Test PVT for debugging output */
1065 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1069 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
1073 /*! \brief __sip_xmit: Transmit SIP message */
1074 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1077 char iabuf[INET_ADDRSTRLEN];
1079 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1080 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
1082 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
1085 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));
1090 static void sip_destroy(struct sip_pvt *p);
1092 /*! \brief build_via: Build a Via header for a request */
1093 static void build_via(struct sip_pvt *p)
1095 char iabuf[INET_ADDRSTRLEN];
1096 /* Work around buggy UNIDEN UIP200 firmware */
1097 const char *rport = ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1099 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1100 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1101 ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1104 /*! \brief ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? */
1105 /* Only used for outbound registrations */
1106 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1109 * Using the localaddr structure built up with localnet statements
1110 * apply it to their address to see if we need to substitute our
1111 * externip or can get away with our internal bindaddr
1113 struct sockaddr_in theirs;
1114 theirs.sin_addr = *them;
1115 if (localaddr && externip.sin_addr.s_addr &&
1116 ast_apply_ha(localaddr, &theirs)) {
1117 char iabuf[INET_ADDRSTRLEN];
1118 if (externexpire && (time(NULL) >= externexpire)) {
1119 struct ast_hostent ahp;
1121 time(&externexpire);
1122 externexpire += externrefresh;
1123 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1124 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1126 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1128 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
1129 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1130 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1132 else if (bindaddr.sin_addr.s_addr)
1133 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
1135 return ast_ouraddrfor(them, us);
1139 /*! \brief append_history: Append to SIP dialog history
1140 \return Always returns 0 */
1141 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1143 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1144 __attribute__ ((format (printf, 2, 3)));
1146 /*! \brief Append to SIP dialog history with arg list */
1147 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1149 char buf[80], *c = buf; /* max history length */
1150 struct sip_history *hist;
1153 vsnprintf(buf, sizeof(buf), fmt, ap);
1154 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1155 l = strlen(buf) + 1;
1156 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1158 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1162 memcpy(hist->event, buf, l);
1163 AST_LIST_INSERT_TAIL(p->history, hist, list);
1166 /*! \brief Append to SIP dialog history with arg list */
1167 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1171 if (!recordhistory || !p)
1174 append_history_va(p, fmt, ap);
1180 /*! \brief retrans_pkt: Retransmit SIP message if no answer */
1181 static int retrans_pkt(void *data)
1183 struct sip_pkt *pkt=data, *prev, *cur = NULL;
1184 char iabuf[INET_ADDRSTRLEN];
1185 int reschedule = DEFAULT_RETRANS;
1188 ast_mutex_lock(&pkt->owner->lock);
1190 if (pkt->retrans < MAX_RETRANS) {
1192 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1193 if (sipdebug && option_debug > 3)
1194 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);
1198 if (sipdebug && option_debug > 3)
1199 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1203 pkt->timer_a = 2 * pkt->timer_a;
1205 /* For non-invites, a maximum of 4 secs */
1206 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1207 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1210 /* Reschedule re-transmit */
1211 reschedule = siptimer_a;
1212 if (option_debug > 3)
1213 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);
1216 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1217 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
1218 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);
1220 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);
1223 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1224 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1225 ast_mutex_unlock(&pkt->owner->lock);
1228 /* Too many retries */
1229 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1230 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */ 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"); } else {
1231 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1232 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1234 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1236 pkt->retransid = -1;
1238 if (ast_test_flag(pkt, FLAG_FATAL)) {
1239 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1240 ast_mutex_unlock(&pkt->owner->lock);
1242 ast_mutex_lock(&pkt->owner->lock);
1244 if (pkt->owner->owner) {
1245 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
1246 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1247 ast_queue_hangup(pkt->owner->owner);
1248 ast_mutex_unlock(&pkt->owner->owner->lock);
1250 /* If no channel owner, destroy now */
1251 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
1254 /* In any case, go ahead and remove the packet */
1256 cur = pkt->owner->packets;
1265 prev->next = cur->next;
1267 pkt->owner->packets = cur->next;
1268 ast_mutex_unlock(&pkt->owner->lock);
1272 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1274 ast_mutex_unlock(&pkt->owner->lock);
1278 /*! \brief __sip_reliable_xmit: transmit packet with retransmits */
1279 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1281 struct sip_pkt *pkt;
1282 int siptimer_a = DEFAULT_RETRANS;
1284 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1286 memcpy(pkt->data, data, len);
1287 pkt->method = sipmethod;
1288 pkt->packetlen = len;
1289 pkt->next = p->packets;
1293 pkt->data[len] = '\0';
1294 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1296 ast_set_flag(pkt, FLAG_FATAL);
1298 siptimer_a = pkt->timer_t1 * 2;
1300 /* Schedule retransmission */
1301 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1302 if (option_debug > 3 && sipdebug)
1303 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1304 pkt->next = p->packets;
1307 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1308 if (sipmethod == SIP_INVITE) {
1309 /* Note this is a pending invite */
1310 p->pendinginvite = seqno;
1315 /*! \brief __sip_autodestruct: Kill a SIP dialog (called by scheduler) */
1316 static int __sip_autodestruct(void *data)
1318 struct sip_pvt *p = data;
1322 /* If this is a subscription, tell the phone that we got a timeout */
1323 if (p->subscribed) {
1324 p->subscribed = TIMEOUT;
1325 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1); /* Send first notification */
1326 p->subscribed = NONE;
1327 append_history(p, "Subscribestatus", "timeout");
1328 return 10000; /* Reschedule this destruction so that we know that it's gone */
1330 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1331 append_history(p, "AutoDestroy", "");
1333 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1334 ast_queue_hangup(p->owner);
1341 /*! \brief sip_scheddestroy: Schedule destruction of SIP call */
1342 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1344 if (sip_debug_test_pvt(p))
1345 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1347 append_history(p, "SchedDestroy", "%d ms", ms);
1349 if (p->autokillid > -1)
1350 ast_sched_del(sched, p->autokillid);
1351 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1355 /*! \brief sip_cancel_destroy: Cancel destruction of SIP dialog */
1356 static int sip_cancel_destroy(struct sip_pvt *p)
1358 if (p->autokillid > -1)
1359 ast_sched_del(sched, p->autokillid);
1360 append_history(p, "CancelDestroy", "");
1365 /*! \brief __sip_ack: Acknowledges receipt of a packet and stops retransmission */
1366 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1368 struct sip_pkt *cur, *prev = NULL;
1370 int resetinvite = 0;
1371 /* Just in case... */
1374 msg = sip_methods[sipmethod].text;
1378 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1379 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1380 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1381 ast_mutex_lock(&p->lock);
1382 if (!resp && (seqno == p->pendinginvite)) {
1383 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1384 p->pendinginvite = 0;
1387 /* this is our baby */
1389 prev->next = cur->next;
1391 p->packets = cur->next;
1392 if (cur->retransid > -1) {
1393 if (sipdebug && option_debug > 3)
1394 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1395 ast_sched_del(sched, cur->retransid);
1398 ast_mutex_unlock(&p->lock);
1405 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1409 /* Pretend to ack all packets */
1410 static int __sip_pretend_ack(struct sip_pvt *p)
1412 struct sip_pkt *cur=NULL;
1415 if (cur == p->packets) {
1416 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1421 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
1422 else { /* Unknown packet type */
1425 ast_copy_string(method, p->packets->data, sizeof(method));
1426 c = ast_skip_blanks(method); /* XXX what ? */
1428 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1434 /*! \brief __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) */
1435 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1437 struct sip_pkt *cur;
1439 char *msg = sip_methods[sipmethod].text;
1443 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1444 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1445 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1446 /* this is our baby */
1447 if (cur->retransid > -1) {
1448 if (option_debug > 3 && sipdebug)
1449 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
1450 ast_sched_del(sched, cur->retransid);
1452 cur->retransid = -1;
1458 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");
1462 static void parse_request(struct sip_request *req);
1463 static char *get_header(struct sip_request *req, char *name);
1464 static void copy_request(struct sip_request *dst,struct sip_request *src);
1466 /*! \brief parse_copy: Copy SIP request, parse it */
1467 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1469 memset(dst, 0, sizeof(*dst));
1470 memcpy(dst->data, src->data, sizeof(dst->data));
1471 dst->len = src->len;
1475 /*! \brief send_response: Transmit response on SIP request*/
1476 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1480 if (sip_debug_test_pvt(p)) {
1481 char iabuf[INET_ADDRSTRLEN];
1482 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1483 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);
1485 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);
1487 if (recordhistory) {
1488 struct sip_request tmp;
1489 parse_copy(&tmp, req);
1490 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1493 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method) :
1494 __sip_xmit(p, req->data, req->len);
1500 /*! \brief send_request: Send SIP Request to the other part of the dialogue */
1501 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1505 if (sip_debug_test_pvt(p)) {
1506 char iabuf[INET_ADDRSTRLEN];
1507 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1508 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);
1510 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);
1512 if (recordhistory) {
1513 struct sip_request tmp;
1514 parse_copy(&tmp, req);
1515 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1518 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1519 __sip_xmit(p, req->data, req->len);
1523 /*! \brief get_in_brackets: Pick out text in brackets from character string */
1524 /* returns pointer to terminated stripped string. modifies input string. */
1525 static char *get_in_brackets(char *tmp)
1529 char *first_bracket;
1530 char *second_bracket;
1535 first_quote = strchr(parse, '"');
1536 first_bracket = strchr(parse, '<');
1537 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1539 for (parse = first_quote + 1; *parse; parse++) {
1540 if ((*parse == '"') && (last_char != '\\'))
1545 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1551 if (first_bracket) {
1552 second_bracket = strchr(first_bracket + 1, '>');
1553 if (second_bracket) {
1554 *second_bracket = '\0';
1555 return first_bracket + 1;
1557 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1565 /*! \brief sip_sendtext: Send SIP MESSAGE text within a call */
1566 /* Called from PBX core text message functions */
1567 static int sip_sendtext(struct ast_channel *ast, const char *text)
1569 struct sip_pvt *p = ast->tech_pvt;
1570 int debug=sip_debug_test_pvt(p);
1573 ast_verbose("Sending text %s on %s\n", text, ast->name);
1576 if (ast_strlen_zero(text))
1579 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1580 transmit_message_with_text(p, text);
1584 /*! \brief realtime_update_peer: Update peer object in realtime storage */
1585 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1589 char regseconds[20] = "0";
1591 if (expirey) { /* Registration */
1595 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
1596 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1597 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1600 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
1602 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1605 /*! \brief register_peer_exten: Automatically add peer extension to dial plan */
1606 static void register_peer_exten(struct sip_peer *peer, int onoff)
1609 char *stringp, *ext;
1610 if (!ast_strlen_zero(regcontext)) {
1611 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
1613 while((ext = strsep(&stringp, "&"))) {
1615 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", ast_strdup(peer->name), free, channeltype);
1617 ast_context_remove_extension(regcontext, ext, 1, NULL);
1622 /*! \brief sip_destroy_peer: Destroy peer object from memory */
1623 static void sip_destroy_peer(struct sip_peer *peer)
1625 /* Delete it, it needs to disappear */
1627 sip_destroy(peer->call);
1628 if (peer->chanvars) {
1629 ast_variables_destroy(peer->chanvars);
1630 peer->chanvars = NULL;
1632 if (peer->expire > -1)
1633 ast_sched_del(sched, peer->expire);
1634 if (peer->pokeexpire > -1)
1635 ast_sched_del(sched, peer->pokeexpire);
1636 register_peer_exten(peer, 0);
1637 ast_free_ha(peer->ha);
1638 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1640 else if (ast_test_flag(peer, SIP_REALTIME))
1644 clear_realm_authentication(peer->auth);
1645 peer->auth = (struct sip_auth *) NULL;
1647 ast_dnsmgr_release(peer->dnsmgr);
1651 /*! \brief update_peer: Update peer data in database (if used) */
1652 static void update_peer(struct sip_peer *p, int expiry)
1654 int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1655 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
1656 (ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) {
1657 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
1662 /*! \brief realtime_peer: Get peer from realtime storage
1663 * Checks the "sippeers" realtime family from extconfig.conf */
1664 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1666 struct sip_peer *peer=NULL;
1667 struct ast_variable *var;
1668 struct ast_variable *tmp;
1669 char *newpeername = (char *) peername;
1672 /* First check on peer name */
1674 var = ast_load_realtime("sippeers", "name", peername, NULL);
1675 else if (sin) { /* Then check on IP address */
1676 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1677 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
1684 for (tmp = var; tmp; tmp = tmp->next) {
1685 /* If this is type=user, then skip this object. */
1686 if (!strcasecmp(tmp->name, "type") &&
1687 !strcasecmp(tmp->value, "user")) {
1688 ast_variables_destroy(var);
1690 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1691 newpeername = tmp->value;
1695 if (!newpeername) { /* Did not find peer in realtime */
1696 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1697 ast_variables_destroy(var);
1698 return (struct sip_peer *) NULL;
1701 /* Peer found in realtime, now build it in memory */
1702 peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1704 ast_variables_destroy(var);
1705 return (struct sip_peer *) NULL;
1708 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1710 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1711 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1712 if (peer->expire > -1) {
1713 ast_sched_del(sched, peer->expire);
1715 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1717 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1719 ast_set_flag(peer, SIP_REALTIME);
1721 ast_variables_destroy(var);
1726 /*! \brief sip_addrcmp: Support routine for find_peer */
1727 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1729 /* We know name is the first field, so we can cast */
1730 struct sip_peer *p = (struct sip_peer *)name;
1731 return !(!inaddrcmp(&p->addr, sin) ||
1732 (ast_test_flag(p, SIP_INSECURE_PORT) &&
1733 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1736 /*! \brief find_peer: Locate peer by name or ip address
1737 * This is used on incoming SIP message to find matching peer on ip
1738 or outgoing message to find matching peer on name */
1739 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1741 struct sip_peer *p = NULL;
1744 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1746 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1748 if (!p && realtime) {
1749 p = realtime_peer(peer, sin);
1754 /*! \brief sip_destroy_user: Remove user object from in-memory storage */
1755 static void sip_destroy_user(struct sip_user *user)
1757 ast_free_ha(user->ha);
1758 if (user->chanvars) {
1759 ast_variables_destroy(user->chanvars);
1760 user->chanvars = NULL;
1762 if (ast_test_flag(user, SIP_REALTIME))
1769 /*! \brief realtime_user: Load user from realtime storage
1770 * Loads user from "sipusers" category in realtime (extconfig.conf)
1771 * Users are matched on From: user name (the domain in skipped) */
1772 static struct sip_user *realtime_user(const char *username)
1774 struct ast_variable *var;
1775 struct ast_variable *tmp;
1776 struct sip_user *user = NULL;
1778 var = ast_load_realtime("sipusers", "name", username, NULL);
1783 for (tmp = var; tmp; tmp = tmp->next) {
1784 if (!strcasecmp(tmp->name, "type") &&
1785 !strcasecmp(tmp->value, "peer")) {
1786 ast_variables_destroy(var);
1791 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1793 if (!user) { /* No user found */
1794 ast_variables_destroy(var);
1798 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1799 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1801 ASTOBJ_CONTAINER_LINK(&userl,user);
1803 /* Move counter from s to r... */
1806 ast_set_flag(user, SIP_REALTIME);
1808 ast_variables_destroy(var);
1812 /*! \brief find_user: Locate user by name
1813 * Locates user by name (From: sip uri user name part) first
1814 * from in-memory list (static configuration) then from
1815 * realtime storage (defined in extconfig.conf) */
1816 static struct sip_user *find_user(const char *name, int realtime)
1818 struct sip_user *u = NULL;
1819 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1820 if (!u && realtime) {
1821 u = realtime_user(name);
1826 /*! \brief create_addr_from_peer: create address structure from peer reference */
1827 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1829 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1830 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
1831 if (peer->addr.sin_addr.s_addr) {
1832 r->sa.sin_family = peer->addr.sin_family;
1833 r->sa.sin_addr = peer->addr.sin_addr;
1834 r->sa.sin_port = peer->addr.sin_port;
1836 r->sa.sin_family = peer->defaddr.sin_family;
1837 r->sa.sin_addr = peer->defaddr.sin_addr;
1838 r->sa.sin_port = peer->defaddr.sin_port;
1840 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1845 ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
1846 r->capability = peer->capability;
1847 r->prefs = peer->prefs;
1849 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1850 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1853 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1854 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1856 ast_string_field_set(r, peername, peer->username);
1857 ast_string_field_set(r, authname, peer->username);
1858 ast_string_field_set(r, username, peer->username);
1859 ast_string_field_set(r, peersecret, peer->secret);
1860 ast_string_field_set(r, peermd5secret, peer->md5secret);
1861 ast_string_field_set(r, tohost, peer->tohost);
1862 ast_string_field_set(r, fullcontact, peer->fullcontact);
1863 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1866 tmpcall = ast_strdupa(r->callid);
1868 c = strchr(tmpcall, '@');
1871 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
1875 if (ast_strlen_zero(r->tohost)) {
1876 char iabuf[INET_ADDRSTRLEN];
1878 if (peer->addr.sin_addr.s_addr)
1879 ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr);
1881 ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr);
1882 ast_string_field_set(r, tohost, iabuf);
1884 if (!ast_strlen_zero(peer->fromdomain))
1885 ast_string_field_set(r, fromdomain, peer->fromdomain);
1886 if (!ast_strlen_zero(peer->fromuser))
1887 ast_string_field_set(r, fromuser, peer->fromuser);
1888 r->maxtime = peer->maxms;
1889 r->callgroup = peer->callgroup;
1890 r->pickupgroup = peer->pickupgroup;
1891 /* Set timer T1 to RTT for this peer (if known by qualify=) */
1892 if (peer->maxms && peer->lastms)
1893 r->timer_t1 = peer->lastms;
1894 if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
1895 r->noncodeccapability |= AST_RTP_DTMF;
1897 r->noncodeccapability &= ~AST_RTP_DTMF;
1898 ast_string_field_set(r, context, peer->context);
1899 r->rtptimeout = peer->rtptimeout;
1900 r->rtpholdtimeout = peer->rtpholdtimeout;
1901 r->rtpkeepalive = peer->rtpkeepalive;
1902 if (peer->call_limit)
1903 ast_set_flag(r, SIP_CALL_LIMIT);
1908 /*! \brief create_addr: create address structure from peer name
1909 * Or, if peer not found, find it in the global DNS
1910 * returns TRUE (-1) on failure, FALSE on success */
1911 static int create_addr(struct sip_pvt *dialog, const char *opeer)
1914 struct ast_hostent ahp;
1919 char host[MAXHOSTNAMELEN], *hostn;
1922 ast_copy_string(peer, opeer, sizeof(peer));
1923 port = strchr(peer, ':');
1928 dialog->sa.sin_family = AF_INET;
1929 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
1930 p = find_peer(peer, NULL, 1);
1934 if (create_addr_from_peer(dialog, p))
1935 ASTOBJ_UNREF(p, sip_destroy_peer);
1943 portno = atoi(port);
1945 portno = DEFAULT_SIP_PORT;
1947 char service[MAXHOSTNAMELEN];
1950 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1951 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1957 hp = ast_gethostbyname(hostn, &ahp);
1959 ast_string_field_set(dialog, tohost, peer);
1960 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
1961 dialog->sa.sin_port = htons(portno);
1962 memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
1965 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1969 ASTOBJ_UNREF(p, sip_destroy_peer);
1974 /*! \brief auto_congest: Scheduled congestion on a call */
1975 static int auto_congest(void *nothing)
1977 struct sip_pvt *p = nothing;
1978 ast_mutex_lock(&p->lock);
1981 if (!ast_mutex_trylock(&p->owner->lock)) {
1982 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1983 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1984 ast_mutex_unlock(&p->owner->lock);
1987 ast_mutex_unlock(&p->lock);
1994 /*! \brief sip_call: Initiate SIP call from PBX
1995 * used from the dial() application */
1996 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2001 const char *osphandle = NULL;
2003 struct varshead *headp;
2004 struct ast_var_t *current;
2009 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2010 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2015 /* Check whether there is vxml_url, distinctive ring variables */
2017 headp=&ast->varshead;
2018 AST_LIST_TRAVERSE(headp,current,entries) {
2019 /* Check whether there is a VXML_URL variable */
2020 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2021 p->options->vxml_url = ast_var_value(current);
2022 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2023 p->options->uri_options = ast_var_value(current);
2024 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2025 /* Check whether there is a ALERT_INFO variable */
2026 p->options->distinctive_ring = ast_var_value(current);
2027 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2028 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2029 p->options->addsipheaders = 1;
2034 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
2035 p->options->osptoken = ast_var_value(current);
2036 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
2037 osphandle = ast_var_value(current);
2043 ast_set_flag(p, SIP_OUTGOING);
2045 if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
2046 /* Force Disable OSP support */
2048 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
2049 p->options->osptoken = NULL;
2054 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2055 res = update_call_counter(p, INC_CALL_LIMIT);
2057 p->callingpres = ast->cid.cid_pres;
2058 p->jointcapability = p->capability;
2059 transmit_invite(p, SIP_INVITE, 1, 2);
2061 /* Initialize auto-congest time */
2062 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2068 /*! \brief sip_registry_destroy: Destroy registry object */
2069 /* Objects created with the register= statement in static configuration */
2070 static void sip_registry_destroy(struct sip_registry *reg)
2074 /* Clear registry before destroying to ensure
2075 we don't get reentered trying to grab the registry lock */
2076 reg->call->registry = NULL;
2077 sip_destroy(reg->call);
2079 if (reg->expire > -1)
2080 ast_sched_del(sched, reg->expire);
2081 if (reg->timeout > -1)
2082 ast_sched_del(sched, reg->timeout);
2083 ast_string_field_free_all(reg);
2089 /*! \brief __sip_destroy: Execute destrucion of SIP dialog structure, release memory */
2090 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2092 struct sip_pvt *cur, *prev = NULL;
2095 if (sip_debug_test_pvt(p))
2096 ast_verbose("Destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2099 sip_dump_history(p);
2104 if (p->stateid > -1)
2105 ast_extension_state_del(p->stateid, NULL);
2107 ast_sched_del(sched, p->initid);
2108 if (p->autokillid > -1)
2109 ast_sched_del(sched, p->autokillid);
2112 ast_rtp_destroy(p->rtp);
2115 ast_rtp_destroy(p->vrtp);
2118 free_old_route(p->route);
2122 if (p->registry->call == p)
2123 p->registry->call = NULL;
2124 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2127 /* Unlink us from the owner if we have one */
2130 ast_mutex_lock(&p->owner->lock);
2132 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2133 p->owner->tech_pvt = NULL;
2135 ast_mutex_unlock(&p->owner->lock);
2139 while(!AST_LIST_EMPTY(p->history)) {
2140 struct sip_history *hist = AST_LIST_FIRST(p->history);
2141 AST_LIST_REMOVE_HEAD(p->history, list);
2152 prev->next = cur->next;
2161 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2165 ast_sched_del(sched, p->initid);
2167 while((cp = p->packets)) {
2168 p->packets = p->packets->next;
2169 if (cp->retransid > -1) {
2170 ast_sched_del(sched, cp->retransid);
2175 ast_variables_destroy(p->chanvars);
2178 ast_mutex_destroy(&p->lock);
2180 ast_string_field_free_all(p);
2185 /*! \brief update_call_counter: Handle call_limit for SIP users
2186 * Setting a call-limit will cause calls above the limit not to be accepted.
2188 * Remember that for a type=friend, there's one limit for the user and
2189 * another for the peer, not a combined call limit.
2190 * This will cause unexpected behaviour in subscriptions, since a "friend"
2191 * is *two* devices in Asterisk, not one.
2193 * Thought: For realtime, we should propably update storage with inuse counter...
2195 static int update_call_counter(struct sip_pvt *fup, int event)
2198 int *inuse, *call_limit;
2199 int outgoing = ast_test_flag(fup, SIP_OUTGOING);
2200 struct sip_user *u = NULL;
2201 struct sip_peer *p = NULL;
2203 if (option_debug > 2)
2204 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2205 /* Test if we need to check call limits, in order to avoid
2206 realtime lookups if we do not need it */
2207 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
2210 ast_copy_string(name, fup->username, sizeof(name));
2212 /* Check the list of users */
2213 if (!outgoing) /* Only check users for incoming calls */
2214 u = find_user(name, 1);
2218 call_limit = &u->call_limit;
2221 /* Try to find peer */
2223 p = find_peer(fup->peername, NULL, 1);
2226 call_limit = &p->call_limit;
2227 ast_copy_string(name, fup->peername, sizeof(name));
2229 if (option_debug > 1)
2230 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2235 /* incoming and outgoing affects the inUse counter */
2236 case DEC_CALL_LIMIT:
2238 if (ast_test_flag(fup, SIP_INC_COUNT))
2243 if (option_debug > 1 || sipdebug) {
2244 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2247 case INC_CALL_LIMIT:
2248 if (*call_limit > 0 ) {
2249 if (*inuse >= *call_limit) {
2250 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);
2252 ASTOBJ_UNREF(u, sip_destroy_user);
2254 ASTOBJ_UNREF(p, sip_destroy_peer);
2259 ast_set_flag(fup, SIP_INC_COUNT);
2260 if (option_debug > 1 || sipdebug) {
2261 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2265 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2268 ASTOBJ_UNREF(u, sip_destroy_user);
2270 ASTOBJ_UNREF(p, sip_destroy_peer);
2274 /*! \brief sip_destroy: Destroy SIP call structure */
2275 static void sip_destroy(struct sip_pvt *p)
2277 ast_mutex_lock(&iflock);
2278 __sip_destroy(p, 1);
2279 ast_mutex_unlock(&iflock);
2283 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
2285 /*! \brief hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes */
2286 static int hangup_sip2cause(int cause)
2288 /* Possible values taken from causes.h */
2291 case 401: /* Unauthorized */
2292 return AST_CAUSE_CALL_REJECTED;
2293 case 403: /* Not found */
2294 return AST_CAUSE_CALL_REJECTED;
2295 case 404: /* Not found */
2296 return AST_CAUSE_UNALLOCATED;
2297 case 405: /* Method not allowed */
2298 return AST_CAUSE_INTERWORKING;
2299 case 407: /* Proxy authentication required */
2300 return AST_CAUSE_CALL_REJECTED;
2301 case 408: /* No reaction */
2302 return AST_CAUSE_NO_USER_RESPONSE;
2303 case 409: /* Conflict */
2304 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2305 case 410: /* Gone */
2306 return AST_CAUSE_UNALLOCATED;
2307 case 411: /* Length required */
2308 return AST_CAUSE_INTERWORKING;
2309 case 413: /* Request entity too large */
2310 return AST_CAUSE_INTERWORKING;
2311 case 414: /* Request URI too large */
2312 return AST_CAUSE_INTERWORKING;
2313 case 415: /* Unsupported media type */
2314 return AST_CAUSE_INTERWORKING;
2315 case 420: /* Bad extension */
2316 return AST_CAUSE_NO_ROUTE_DESTINATION;
2317 case 480: /* No answer */
2318 return AST_CAUSE_FAILURE;
2319 case 481: /* No answer */
2320 return AST_CAUSE_INTERWORKING;
2321 case 482: /* Loop detected */
2322 return AST_CAUSE_INTERWORKING;
2323 case 483: /* Too many hops */
2324 return AST_CAUSE_NO_ANSWER;
2325 case 484: /* Address incomplete */
2326 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2327 case 485: /* Ambigous */
2328 return AST_CAUSE_UNALLOCATED;
2329 case 486: /* Busy everywhere */
2330 return AST_CAUSE_BUSY;
2331 case 487: /* Request terminated */
2332 return AST_CAUSE_INTERWORKING;
2333 case 488: /* No codecs approved */
2334 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2335 case 491: /* Request pending */
2336 return AST_CAUSE_INTERWORKING;
2337 case 493: /* Undecipherable */
2338 return AST_CAUSE_INTERWORKING;
2339 case 500: /* Server internal failure */
2340 return AST_CAUSE_FAILURE;
2341 case 501: /* Call rejected */
2342 return AST_CAUSE_FACILITY_REJECTED;
2344 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2345 case 503: /* Service unavailable */
2346 return AST_CAUSE_CONGESTION;
2347 case 504: /* Gateway timeout */
2348 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2349 case 505: /* SIP version not supported */
2350 return AST_CAUSE_INTERWORKING;
2351 case 600: /* Busy everywhere */
2352 return AST_CAUSE_USER_BUSY;
2353 case 603: /* Decline */
2354 return AST_CAUSE_CALL_REJECTED;
2355 case 604: /* Does not exist anywhere */
2356 return AST_CAUSE_UNALLOCATED;
2357 case 606: /* Not acceptable */
2358 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2360 return AST_CAUSE_NORMAL;
2367 /*! \brief hangup_cause2sip: Convert Asterisk hangup causes to SIP codes
2369 Possible values from causes.h
2370 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
2371 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
2373 In addition to these, a lot of PRI codes is defined in causes.h
2374 ...should we take care of them too ?
2378 ISUP Cause value SIP response
2379 ---------------- ------------
2380 1 unallocated number 404 Not Found
2381 2 no route to network 404 Not found
2382 3 no route to destination 404 Not found
2383 16 normal call clearing --- (*)
2384 17 user busy 486 Busy here
2385 18 no user responding 408 Request Timeout
2386 19 no answer from the user 480 Temporarily unavailable
2387 20 subscriber absent 480 Temporarily unavailable
2388 21 call rejected 403 Forbidden (+)
2389 22 number changed (w/o diagnostic) 410 Gone
2390 22 number changed (w/ diagnostic) 301 Moved Permanently
2391 23 redirection to new destination 410 Gone
2392 26 non-selected user clearing 404 Not Found (=)
2393 27 destination out of order 502 Bad Gateway
2394 28 address incomplete 484 Address incomplete
2395 29 facility rejected 501 Not implemented
2396 31 normal unspecified 480 Temporarily unavailable
2399 static char *hangup_cause2sip(int cause)
2403 case AST_CAUSE_UNALLOCATED: /* 1 */
2404 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
2405 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
2406 return "404 Not Found";
2407 case AST_CAUSE_CONGESTION: /* 34 */
2408 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
2409 return "503 Service Unavailable";
2410 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
2411 return "408 Request Timeout";
2412 case AST_CAUSE_NO_ANSWER: /* 19 */
2413 return "480 Temporarily unavailable";
2414 case AST_CAUSE_CALL_REJECTED: /* 21 */
2415 return "403 Forbidden";
2416 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
2418 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
2419 return "480 Temporarily unavailable";
2420 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2421 return "484 Address incomplete";
2422 case AST_CAUSE_USER_BUSY:
2423 return "486 Busy here";
2424 case AST_CAUSE_FAILURE:
2425 return "500 Server internal failure";
2426 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
2427 return "501 Not Implemented";
2428 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2429 return "503 Service Unavailable";
2430 /* Used in chan_iax2 */
2431 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2432 return "502 Bad Gateway";
2433 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2434 return "488 Not Acceptable Here";
2436 case AST_CAUSE_NOTDEFINED:
2438 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2447 /*! \brief sip_hangup: Hangup SIP call
2448 * Part of PBX interface, called from ast_hangup */
2449 static int sip_hangup(struct ast_channel *ast)
2451 struct sip_pvt *p = ast->tech_pvt;
2453 struct ast_flags locflags = {0};
2456 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2459 if (option_debug && sipdebug)
2460 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2462 ast_mutex_lock(&p->lock);
2464 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2465 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2468 if (option_debug && sipdebug)
2469 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2470 update_call_counter(p, DEC_CALL_LIMIT);
2471 /* Determine how to disconnect */
2472 if (p->owner != ast) {
2473 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
2474 ast_mutex_unlock(&p->lock);
2477 /* If the call is not UP, we need to send CANCEL instead of BYE */
2478 if (ast->_state != AST_STATE_UP)
2484 ast_dsp_free(p->vad);
2487 ast->tech_pvt = NULL;
2489 ast_mutex_lock(&usecnt_lock);
2491 ast_mutex_unlock(&usecnt_lock);
2492 ast_update_use_count();
2494 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2496 /* Start the process if it's not already started */
2497 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2498 if (needcancel) { /* Outgoing call, not up */
2499 if (ast_test_flag(p, SIP_OUTGOING)) {
2500 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
2501 /* Actually don't destroy us yet, wait for the 487 on our original
2502 INVITE, but do set an autodestruct just in case we never get it. */
2503 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2504 sip_scheddestroy(p, 15000);
2505 /* stop retransmitting an INVITE that has not received a response */
2506 __sip_pretend_ack(p);
2507 if ( p->initid != -1 ) {
2508 /* channel still up - reverse dec of inUse counter
2509 only if the channel is not auto-congested */
2510 update_call_counter(p, INC_CALL_LIMIT);
2512 } else { /* Incoming call, not up */
2514 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2515 transmit_response_reliable(p, res, &p->initreq, 1);
2517 transmit_response_reliable(p, "603 Declined", &p->initreq, 1);
2519 } else { /* Call is in UP state, send BYE */
2520 if (!p->pendinginvite) {
2522 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
2524 /* Note we will need a BYE when this all settles out
2525 but we can't send one while we have "INVITE" outstanding. */
2526 ast_set_flag(p, SIP_PENDINGBYE);
2527 ast_clear_flag(p, SIP_NEEDREINVITE);
2531 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
2532 ast_mutex_unlock(&p->lock);
2536 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
2537 * Part of PBX interface */
2538 static int sip_answer(struct ast_channel *ast)
2542 struct sip_pvt *p = ast->tech_pvt;
2544 ast_mutex_lock(&p->lock);
2545 if (ast->_state != AST_STATE_UP) {
2550 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
2552 fmt=ast_getformatbyname(codec);
2554 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
2555 if (p->jointcapability & fmt) {
2556 p->jointcapability &= fmt;
2557 p->capability &= fmt;
2559 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2560 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
2563 ast_setstate(ast, AST_STATE_UP);
2565 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
2566 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
2568 ast_mutex_unlock(&p->lock);
2572 /*! \brief sip_write: Send frame to media channel (rtp) */
2573 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2575 struct sip_pvt *p = ast->tech_pvt;
2577 switch (frame->frametype) {
2578 case AST_FRAME_VOICE:
2579 if (!(frame->subclass & ast->nativeformats)) {
2580 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2581 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2585 ast_mutex_lock(&p->lock);
2587 /* If channel is not up, activate early media session */
2588 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2589 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2590 ast_set_flag(p, SIP_PROGRESS_SENT);
2592 time(&p->lastrtptx);
2593 res = ast_rtp_write(p->rtp, frame);
2595 ast_mutex_unlock(&p->lock);
2598 case AST_FRAME_VIDEO:
2600 ast_mutex_lock(&p->lock);
2602 /* Activate video early media */
2603 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2604 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2605 ast_set_flag(p, SIP_PROGRESS_SENT);
2607 time(&p->lastrtptx);
2608 res = ast_rtp_write(p->vrtp, frame);
2610 ast_mutex_unlock(&p->lock);
2613 case AST_FRAME_IMAGE:
2617 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2624 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2625 Basically update any ->owner links */
2626 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2628 struct sip_pvt *p = newchan->tech_pvt;
2629 ast_mutex_lock(&p->lock);
2630 if (p->owner != oldchan) {
2631 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2632 ast_mutex_unlock(&p->lock);
2636 ast_mutex_unlock(&p->lock);
2640 /*! \brief sip_senddigit: Send DTMF character on SIP channel */
2641 /* within one call, we're able to transmit in many methods simultaneously */
2642 static int sip_senddigit(struct ast_channel *ast, char digit)
2644 struct sip_pvt *p = ast->tech_pvt;
2646 ast_mutex_lock(&p->lock);
2647 switch (ast_test_flag(p, SIP_DTMF)) {
2649 transmit_info_with_digit(p, digit);
2651 case SIP_DTMF_RFC2833:
2653 ast_rtp_senddigit(p->rtp, digit);
2655 case SIP_DTMF_INBAND:
2659 ast_mutex_unlock(&p->lock);
2665 /*! \brief sip_transfer: Transfer SIP call */
2666 static int sip_transfer(struct ast_channel *ast, const char *dest)
2668 struct sip_pvt *p = ast->tech_pvt;
2671 ast_mutex_lock(&p->lock);
2672 if (ast->_state == AST_STATE_RING)
2673 res = sip_sipredirect(p, dest);
2675 res = transmit_refer(p, dest);
2676 ast_mutex_unlock(&p->lock);
2680 /*! \brief sip_indicate: Play indication to user
2681 * With SIP a lot of indications is sent as messages, letting the device play
2682 the indication - busy signal, congestion etc */
2683 static int sip_indicate(struct ast_channel *ast, int condition)
2685 struct sip_pvt *p = ast->tech_pvt;
2688 ast_mutex_lock(&p->lock);
2690 case AST_CONTROL_RINGING:
2691 if (ast->_state == AST_STATE_RING) {
2692 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
2693 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2694 /* Send 180 ringing if out-of-band seems reasonable */
2695 transmit_response(p, "180 Ringing", &p->initreq);
2696 ast_set_flag(p, SIP_RINGING);
2697 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2700 /* Well, if it's not reasonable, just send in-band */
2705 case AST_CONTROL_BUSY:
2706 if (ast->_state != AST_STATE_UP) {
2707 transmit_response(p, "486 Busy Here", &p->initreq);
2708 ast_set_flag(p, SIP_ALREADYGONE);
2709 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2714 case AST_CONTROL_CONGESTION:
2715 if (ast->_state != AST_STATE_UP) {
2716 transmit_response(p, "503 Service Unavailable", &p->initreq);
2717 ast_set_flag(p, SIP_ALREADYGONE);
2718 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2723 case AST_CONTROL_PROCEEDING:
2724 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2725 transmit_response(p, "100 Trying", &p->initreq);
2730 case AST_CONTROL_PROGRESS:
2731 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2732 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2733 ast_set_flag(p, SIP_PROGRESS_SENT);
2738 case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
2740 ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
2743 case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
2745 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2748 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
2749 if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
2750 transmit_info_with_vidupdate(p);
2759 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2763 ast_mutex_unlock(&p->lock);
2769 /*! \brief sip_new: Initiate a call in the SIP channel */
2770 /* called from sip_request_call (calls from the pbx ) */
2771 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
2773 struct ast_channel *tmp;
2774 struct ast_variable *v = NULL;
2778 char iabuf[INET_ADDRSTRLEN];
2779 char peer[MAXHOSTNAMELEN];
2782 ast_mutex_unlock(&i->lock);
2783 /* Don't hold a sip pvt lock while we allocate a channel */
2784 tmp = ast_channel_alloc(1);
2785 ast_mutex_lock(&i->lock);
2787 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2790 tmp->tech = &sip_tech;
2791 /* Select our native format based on codec preference until we receive
2792 something from another device to the contrary. */
2793 if (i->jointcapability)
2794 what = i->jointcapability;
2795 else if (i->capability)
2796 what = i->capability;
2798 what = global_capability;
2799 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
2800 fmt = ast_best_codec(tmp->nativeformats);
2803 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, thread_safe_rand() & 0xffff);
2804 else if (strchr(i->fromdomain,':'))
2805 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2807 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2809 tmp->type = channeltype;
2810 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2811 i->vad = ast_dsp_new();
2812 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2814 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2817 tmp->fds[0] = ast_rtp_fd(i->rtp);
2818 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2821 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2822 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2824 if (state == AST_STATE_RING)
2826 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2827 tmp->writeformat = fmt;
2828 tmp->rawwriteformat = fmt;
2829 tmp->readformat = fmt;
2830 tmp->rawreadformat = fmt;
2833 tmp->callgroup = i->callgroup;
2834 tmp->pickupgroup = i->pickupgroup;
2835 tmp->cid.cid_pres = i->callingpres;
2836 if (!ast_strlen_zero(i->accountcode))
2837 ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
2839 tmp->amaflags = i->amaflags;
2840 if (!ast_strlen_zero(i->language))
2841 ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
2842 if (!ast_strlen_zero(i->musicclass))
2843 ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
2845 ast_mutex_lock(&usecnt_lock);
2847 ast_mutex_unlock(&usecnt_lock);
2848 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2849 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2850 if (!ast_strlen_zero(i->cid_num))
2851 tmp->cid.cid_num = ast_strdup(i->cid_num);
2852 if (!ast_strlen_zero(i->cid_name))
2853 tmp->cid.cid_name = ast_strdup(i->cid_name);
2854 if (!ast_strlen_zero(i->rdnis))
2855 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
2856 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2857 tmp->cid.cid_dnid = ast_strdup(i->exten);
2859 if (!ast_strlen_zero(i->uri)) {
2860 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2862 if (!ast_strlen_zero(i->domain)) {
2863 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2865 if (!ast_strlen_zero(i->useragent)) {
2866 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2868 if (!ast_strlen_zero(i->callid)) {
2869 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2872 snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
2873 pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
2875 ast_setstate(tmp, state);
2876 if (state != AST_STATE_DOWN) {
2877 if (ast_pbx_start(tmp)) {
2878 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2883 /* Set channel variables for this call from configuration */
2884 for (v = i->chanvars ; v ; v = v->next)
2885 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2890 /*! \brief get_sdp_by_line: Reads one line of SIP message body */
2891 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2893 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2894 return ast_skip_blanks(line + nameLen + 1);
2899 /*! \brief get_sdp: Gets all kind of SIP message bodies, including SDP,
2900 but the name wrongly applies _only_ sdp */
2901 static char *get_sdp(struct sip_request *req, char *name)
2904 int len = strlen(name);
2907 for (x=0; x<req->lines; x++) {
2908 r = get_sdp_by_line(req->line[x], name, len);
2916 static void sdpLineNum_iterator_init(int* iterator)
2921 static char* get_sdp_iterate(int* iterator,
2922 struct sip_request *req, char *name)
2924 int len = strlen(name);
2927 while (*iterator < req->lines) {
2928 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2935 static char *find_alias(const char *name, char *_default)
2938 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2939 if (!strcasecmp(aliases[x].fullname, name))
2940 return aliases[x].shortname;
2944 static char *__get_header(struct sip_request *req, char *name, int *start)
2949 * Technically you can place arbitrary whitespace both before and after the ':' in
2950 * a header, although RFC3261 clearly says you shouldn't before, and place just
2951 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
2952 * a good idea to say you can do it, and if you can do it, why in the hell would.
2953 * you say you shouldn't.
2954 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
2955 * and we always allow spaces after that for compatibility.
2957 for (pass = 0; name && pass < 2;pass++) {
2958 int x, len = strlen(name);
2959 for (x=*start; x<req->headers; x++) {
2960 if (!strncasecmp(req->header[x], name, len)) {
2961 char *r = req->header[x] + len; /* skip name */
2962 if (pedanticsipchecking)
2963 r = ast_skip_blanks(r);
2967 return ast_skip_blanks(r+1);
2971 if (pass == 0) /* Try aliases */
2972 name = find_alias(name, NULL);
2975 /* Don't return NULL, so get_header is always a valid pointer */
2979 /*! \brief get_header: Get header from SIP request */
2980 static char *get_header(struct sip_request *req, char *name)
2983 return __get_header(req, name, &start);
2986 /*! \brief sip_rtp_read: Read RTP from network */
2987 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2989 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
2990 struct ast_frame *f;
2991 static struct ast_frame null_frame = { AST_FRAME_NULL, };
2994 /* We have no RTP allocated for this channel */
3000 f = ast_rtp_read(p->rtp); /* RTP Audio */
3003 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
3006 f = ast_rtp_read(p->vrtp); /* RTP Video */
3009 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
3014 /* Don't forward RFC2833 if we're not supposed to */
3015 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
3018 /* We already hold the channel lock */
3019 if (f->frametype == AST_FRAME_VOICE) {
3020 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
3021 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
3022 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
3023 ast_set_read_format(p->owner, p->owner->readformat);
3024 ast_set_write_format(p->owner, p->owner->writeformat);
3026 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
3027 f = ast_dsp_process(p->owner, p->vad, f);
3028 if (f && (f->frametype == AST_FRAME_DTMF))
3029 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
3036 /*! \brief sip_read: Read SIP RTP from channel */
3037 static struct ast_frame *sip_read(struct ast_channel *ast)
3039 struct ast_frame *fr;
3040 struct sip_pvt *p = ast->tech_pvt;
3041 ast_mutex_lock(&p->lock);
3042 fr = sip_rtp_read(ast, p);
3043 time(&p->lastrtprx);
3044 ast_mutex_unlock(&p->lock);