2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
34 * \todo Better support of forking
36 * \ingroup channel_drivers
44 #include <sys/socket.h>
45 #include <sys/ioctl.h>
52 #include <sys/signal.h>
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <arpa/inet.h>
56 #include <netinet/ip.h>
61 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
63 #include "asterisk/lock.h"
64 #include "asterisk/channel.h"
65 #include "asterisk/config.h"
66 #include "asterisk/logger.h"
67 #include "asterisk/module.h"
68 #include "asterisk/pbx.h"
69 #include "asterisk/options.h"
70 #include "asterisk/lock.h"
71 #include "asterisk/sched.h"
72 #include "asterisk/io.h"
73 #include "asterisk/rtp.h"
74 #include "asterisk/acl.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/callerid.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/app.h"
79 #include "asterisk/musiconhold.h"
80 #include "asterisk/dsp.h"
81 #include "asterisk/features.h"
82 #include "asterisk/acl.h"
83 #include "asterisk/srv.h"
84 #include "asterisk/astdb.h"
85 #include "asterisk/causes.h"
86 #include "asterisk/utils.h"
87 #include "asterisk/file.h"
88 #include "asterisk/astobj.h"
89 #include "asterisk/dnsmgr.h"
90 #include "asterisk/devicestate.h"
91 #include "asterisk/linkedlists.h"
92 #include "asterisk/stringfields.h"
95 #include "asterisk/astosp.h"
106 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
107 #ifndef IPTOS_MINCOST
108 #define IPTOS_MINCOST 0x02
111 /* #define VOCAL_DATA_HACK */
113 #define DEFAULT_DEFAULT_EXPIRY 120
114 #define DEFAULT_MIN_EXPIRY 60
115 #define DEFAULT_MAX_EXPIRY 3600
116 #define DEFAULT_REGISTRATION_TIMEOUT 20
117 #define DEFAULT_MAX_FORWARDS "70"
119 /* guard limit must be larger than guard secs */
120 /* guard min must be < 1000, and should be >= 250 */
121 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
122 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
124 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
125 GUARD_PCT turns out to be lower than this, it
126 will use this time instead.
127 This is in milliseconds. */
128 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
129 below EXPIRY_GUARD_LIMIT */
130 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
132 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
133 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
134 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
135 static int expiry = DEFAULT_EXPIRY;
138 #define MAX(a,b) ((a) > (b) ? (a) : (b))
141 #define CALLERID_UNKNOWN "Unknown"
145 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
146 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
147 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
149 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
150 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
151 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
153 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
154 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
157 static const char desc[] = "Session Initiation Protocol (SIP)";
158 static const char channeltype[] = "SIP";
159 static const char config[] = "sip.conf";
160 static const char notify_config[] = "sip_notify.conf";
165 /* Do _NOT_ make any changes to this enum, or the array following it;
166 if you think you are doing the right thing, you are probably
167 not doing the right thing. If you think there are changes
168 needed, get someone else to review them first _before_
169 submitting a patch. If these two lists do not match properly
170 bad things will happen.
173 enum subscriptiontype {
182 static const struct cfsubscription_types {
183 enum subscriptiontype type;
184 const char * const event;
185 const char * const mediatype;
186 const char * const text;
187 } subscription_types[] = {
188 { NONE, "-", "unknown", "unknown" },
189 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
190 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
191 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
192 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
193 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" } /* Pre-RFC 3863 with MS additions */
220 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
221 static const struct cfsip_methods {
223 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
226 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
227 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
228 { SIP_REGISTER, NO_RTP, "REGISTER" },
229 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
230 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
231 { SIP_INVITE, RTP, "INVITE" },
232 { SIP_ACK, NO_RTP, "ACK" },
233 { SIP_PRACK, NO_RTP, "PRACK" },
234 { SIP_BYE, NO_RTP, "BYE" },
235 { SIP_REFER, NO_RTP, "REFER" },
236 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
237 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
238 { SIP_UPDATE, NO_RTP, "UPDATE" },
239 { SIP_INFO, NO_RTP, "INFO" },
240 { SIP_CANCEL, NO_RTP, "CANCEL" },
241 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
244 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
245 static const struct cfalias {
246 char * const fullname;
247 char * const shortname;
249 { "Content-Type", "c" },
250 { "Content-Encoding", "e" },
254 { "Content-Length", "l" },
257 { "Supported", "k" },
259 { "Referred-By", "b" },
260 { "Allow-Events", "u" },
263 { "Accept-Contact", "a" },
264 { "Reject-Contact", "j" },
265 { "Request-Disposition", "d" },
266 { "Session-Expires", "x" },
269 /*! Define SIP option tags, used in Require: and Supported: headers
270 We need to be aware of these properties in the phones to use
271 the replace: header. We should not do that without knowing
272 that the other end supports it...
273 This is nothing we can configure, we learn by the dialog
274 Supported: header on the REGISTER (peer) or the INVITE
276 We are not using many of these today, but will in the future.
277 This is documented in RFC 3261
280 #define NOT_SUPPORTED 0
282 #define SIP_OPT_REPLACES (1 << 0)
283 #define SIP_OPT_100REL (1 << 1)
284 #define SIP_OPT_TIMER (1 << 2)
285 #define SIP_OPT_EARLY_SESSION (1 << 3)
286 #define SIP_OPT_JOIN (1 << 4)
287 #define SIP_OPT_PATH (1 << 5)
288 #define SIP_OPT_PREF (1 << 6)
289 #define SIP_OPT_PRECONDITION (1 << 7)
290 #define SIP_OPT_PRIVACY (1 << 8)
291 #define SIP_OPT_SDP_ANAT (1 << 9)
292 #define SIP_OPT_SEC_AGREE (1 << 10)
293 #define SIP_OPT_EVENTLIST (1 << 11)
294 #define SIP_OPT_GRUU (1 << 12)
295 #define SIP_OPT_TARGET_DIALOG (1 << 13)
297 /*! \brief List of well-known SIP options. If we get this in a require,
298 we should check the list and answer accordingly. */
299 static const struct cfsip_options {
300 int id; /*!< Bitmap ID */
301 int supported; /*!< Supported by Asterisk ? */
302 char * const text; /*!< Text id, as in standard */
304 /* Replaces: header for transfer */
305 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
306 /* RFC3262: PRACK 100% reliability */
307 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
308 /* SIP Session Timers */
309 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
310 /* RFC3959: SIP Early session support */
311 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
312 /* SIP Join header support */
313 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
314 /* RFC3327: Path support */
315 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
316 /* RFC3840: Callee preferences */
317 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
318 /* RFC3312: Precondition support */
319 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
320 /* RFC3323: Privacy with proxies*/
321 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
322 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
323 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
324 /* RFC3329: Security agreement mechanism */
325 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
326 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
327 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
328 /* GRUU: Globally Routable User Agent URI's */
329 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
330 /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
331 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
335 /*! \brief SIP Methods we support */
336 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
338 /*! \brief SIP Extensions we support */
339 #define SUPPORTED_EXTENSIONS "replaces"
341 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
343 /* Default values, set and reset in reload_config before reading configuration */
344 /* These are default values in the source. There are other recommended values in the
345 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
346 yet encouraging new behaviour on new installations
348 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
349 #define DEFAULT_CONTEXT "default"
350 #define DEFAULT_MUSICCLASS "default"
351 #define DEFAULT_VMEXTEN "asterisk"
352 #define DEFAULT_CALLERID "asterisk"
353 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
354 #define DEFAULT_MWITIME 10
355 #define DEFAULT_ALLOWGUEST TRUE
356 #define DEFAULT_VIDEOSUPPORT FALSE
357 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
358 #define DEFAULT_COMPACTHEADERS FALSE
359 #define DEFAULT_TOS FALSE
360 #define DEFAULT_ALLOW_EXT_DOM TRUE
361 #define DEFAULT_REALM "asterisk"
362 #define DEFAULT_NOTIFYRINGING TRUE
363 #define DEFAULT_PEDANTIC FALSE
364 #define DEFAULT_AUTOCREATEPEER FALSE
365 #define DEFAULT_QUALIFY FALSE
366 #ifndef DEFAULT_USERAGENT
367 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
370 /* Default setttings are used as a channel setting and as a default when
371 configuring devices */
372 static char default_context[AST_MAX_CONTEXT];
373 static char default_subscribecontext[AST_MAX_CONTEXT];
374 static char default_language[MAX_LANGUAGE];
375 static char default_callerid[AST_MAX_EXTENSION];
376 static char default_fromdomain[AST_MAX_EXTENSION];
377 static char default_notifymime[AST_MAX_EXTENSION];
378 static int default_qualify; /*!< Default Qualify= setting */
379 static char default_vmexten[AST_MAX_EXTENSION];
380 static char default_musicclass[MAX_MUSICCLASS]; /*!< Global music on hold class */
382 /* Global settings only apply to the channel */
383 static int global_notifyringing; /*!< Send notifications on ringing */
384 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
385 static int pedanticsipchecking; /*!< Extra checking ? Default off */
386 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
387 static int relaxdtmf; /*!< Relax DTMF */
388 static int global_rtptimeout; /*!< Time out call if no RTP */
389 static int global_rtpholdtimeout;
390 static int global_rtpkeepalive; /*!< Send RTP keepalives */
391 static int global_reg_timeout;
392 static int global_regattempts_max; /*!< Registration attempts before giving up */
393 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
394 static int global_mwitime; /*!< Time between MWI checks for peers */
395 static int global_tos; /*!< IP Type of service */
396 static int global_videosupport; /*!< Videosupport on or off */
397 static int compactheaders; /*!< send compact sip headers */
398 static int recordhistory; /*!< Record SIP history. Off by default */
399 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
400 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
401 static char regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
402 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
403 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
405 /*! \brief Codecs that we support by default: */
406 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
407 static int noncodeccapability = AST_RTP_DTMF;
409 /* Object counters */
410 static int suserobjs = 0; /*!< Static users */
411 static int ruserobjs = 0; /*!< Realtime users */
412 static int speerobjs = 0; /*!< Statis peers */
413 static int rpeerobjs = 0; /*!< Realtime peers */
414 static int apeerobjs = 0; /*!< Autocreated peer objects */
415 static int regobjs = 0; /*!< Registry objects */
417 static struct ast_flags global_flags = {0}; /*!< global SIP_ flags */
418 static struct ast_flags global_flags_page2 = {0}; /*!< more global SIP_ flags */
420 static int usecnt =0;
422 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
424 AST_MUTEX_DEFINE_STATIC(rand_lock); /*!< Lock for thread-safe random generator */
426 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
427 AST_MUTEX_DEFINE_STATIC(iflock);
429 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
430 when it's doing something critical. */
431 AST_MUTEX_DEFINE_STATIC(netlock);
433 AST_MUTEX_DEFINE_STATIC(monlock);
435 /*! \brief This is the thread for the monitor which checks for input on the channels
436 which are not currently in use. */
437 static pthread_t monitor_thread = AST_PTHREADT_NULL;
439 static int restart_monitor(void);
442 static struct in_addr __ourip;
443 static struct sockaddr_in outboundproxyip;
445 static struct sockaddr_in debugaddr;
448 static struct sched_context *sched;
449 static struct io_context *io;
452 #define DEC_CALL_LIMIT 0
453 #define INC_CALL_LIMIT 1
455 static struct ast_codec_pref prefs;
458 /*! \brief sip_request: The data grabbed from the UDP socket */
460 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
461 char *rlPart2; /*!< The Request URI or Response Status */
462 int len; /*!< Length */
463 int headers; /*!< # of SIP Headers */
464 int method; /*!< Method of this request */
465 char *header[SIP_MAX_HEADERS];
466 int lines; /*!< SDP Content */
467 char *line[SIP_MAX_LINES];
468 char data[SIP_MAX_PACKET];
469 int debug; /*!< Debug flag for this packet */
470 unsigned int flags; /*!< SIP_PKT Flags for this packet */
475 /*! \brief Parameters to the transmit_invite function */
476 struct sip_invite_param {
477 const char *distinctive_ring; /*!< Distinctive ring header */
478 const char *osptoken; /*!< OSP token for this call */
479 int addsipheaders; /*!< Add extra SIP headers */
480 const char *uri_options; /*!< URI options to add to the URI */
481 const char *vxml_url; /*!< VXML url for Cisco phones */
482 char *auth; /*!< Authentication */
483 char *authheader; /*!< Auth header */
484 enum sip_auth_type auth_type; /*!< Authentication type */
488 struct sip_route *next;
493 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
494 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
498 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
499 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
500 enum domain_mode mode; /*!< How did we find this domain? */
501 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
504 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
507 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
509 AST_LIST_ENTRY(sip_history) list;
510 char event[0]; /* actually more, depending on needs */
513 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
515 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
517 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
518 char username[256]; /*!< Username */
519 char secret[256]; /*!< Secret */
520 char md5secret[256]; /*!< MD5Secret */
521 struct sip_auth *next; /*!< Next auth structure in list */
524 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
525 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed */
526 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
527 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
528 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
529 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
530 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
531 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
532 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
533 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
534 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
535 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
536 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
537 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
538 #define SIP_SELFDESTRUCT (1 << 14)
539 #define SIP_DYNAMIC (1 << 15) /*!< Is this a dynamic peer? */
540 /* --- Choices for DTMF support in SIP channel */
541 #define SIP_DTMF (3 << 16) /*!< three settings, uses two bits */
542 #define SIP_DTMF_RFC2833 (0 << 16) /*!< RTP DTMF */
543 #define SIP_DTMF_INBAND (1 << 16) /*!< Inband audio, only for ULAW/ALAW */
544 #define SIP_DTMF_INFO (2 << 16) /*!< SIP Info messages */
545 #define SIP_DTMF_AUTO (3 << 16) /*!< AUTO switch between rfc2833 and in-band DTMF */
547 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
548 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
549 #define SIP_NAT_RFC3581 (1 << 18)
550 #define SIP_NAT_ROUTE (2 << 18)
551 #define SIP_NAT_ALWAYS (3 << 18)
552 /* re-INVITE related settings */
553 #define SIP_REINVITE (3 << 20) /*!< two bits used */
554 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
555 #define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
556 /* "insecure" settings */
557 #define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */
558 #define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */
559 /* Sending PROGRESS in-band settings */
560 #define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */
561 #define SIP_PROG_INBAND_NEVER (0 << 24)
562 #define SIP_PROG_INBAND_NO (1 << 24)
563 #define SIP_PROG_INBAND_YES (2 << 24)
564 /* Open Settlement Protocol authentication */
565 #define SIP_OSPAUTH (3 << 26) /*!< four settings, uses two bits */
566 #define SIP_OSPAUTH_NO (0 << 26)
567 #define SIP_OSPAUTH_GATEWAY (1 << 26)
568 #define SIP_OSPAUTH_PROXY (2 << 26)
569 #define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
571 #define SIP_CALL_ONHOLD (1 << 28)
572 #define SIP_CALL_LIMIT (1 << 29)
573 /* Remote Party-ID Support */
574 #define SIP_SENDRPID (1 << 30)
575 /* Did this connection increment the counter of in-use calls? */
576 #define SIP_INC_COUNT (1 << 31)
578 #define SIP_FLAGS_TO_COPY \
579 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
580 SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
581 SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
583 /* a new page of flags for peer */
584 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
585 #define SIP_PAGE2_RTUPDATE (1 << 1)
586 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
587 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
588 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
589 #define SIP_PAGE2_DEBUG (3 << 5)
590 #define SIP_PAGE2_DEBUG_CONFIG (1 << 5)
591 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 6)
593 /* SIP packet flags */
594 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
595 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
597 #define sipdebug ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG)
598 #define sipdebug_config ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG_CONFIG)
599 #define sipdebug_console ast_test_flag(&global_flags_page2, SIP_PAGE2_DEBUG_CONSOLE)
601 static int global_rtautoclear = 120;
603 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
604 static struct sip_pvt {
605 ast_mutex_t lock; /*!< Dialog private lock */
606 int method; /*!< SIP method that opened this dialog */
607 AST_DECLARE_STRING_FIELDS(
608 AST_STRING_FIELD(callid); /*!< Global CallID */
609 AST_STRING_FIELD(randdata); /*!< Random data */
610 AST_STRING_FIELD(accountcode); /*!< Account code */
611 AST_STRING_FIELD(realm); /*!< Authorization realm */
612 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
613 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
614 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
615 AST_STRING_FIELD(domain); /*!< Authorization domain */
616 AST_STRING_FIELD(refer_to); /*!< Place to store REFER-TO extension */
617 AST_STRING_FIELD(referred_by); /*!< Place to store REFERRED-BY extension */
618 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
619 AST_STRING_FIELD(from); /*!< The From: header */
620 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
621 AST_STRING_FIELD(exten); /*!< Extension where to start */
622 AST_STRING_FIELD(context); /*!< Context for this call */
623 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
624 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
625 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
626 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
627 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
628 AST_STRING_FIELD(language); /*!< Default language for this call */
629 AST_STRING_FIELD(musicclass); /*!< Music on Hold class */
630 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
631 AST_STRING_FIELD(theirtag); /*!< Their tag */
632 AST_STRING_FIELD(username); /*!< [user] name */
633 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
634 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
635 AST_STRING_FIELD(uri); /*!< Original requested URI */
636 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
637 AST_STRING_FIELD(peersecret); /*!< Password */
638 AST_STRING_FIELD(peermd5secret);
639 AST_STRING_FIELD(cid_num); /*!< Caller*ID */
640 AST_STRING_FIELD(cid_name); /*!< Caller*ID */
641 AST_STRING_FIELD(via); /*!< Via: header */
642 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
643 AST_STRING_FIELD(our_contact); /*!< Our contact header */
644 AST_STRING_FIELD(rpid); /*!< Our RPID header */
645 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
647 struct ast_codec_pref prefs; /*!< codec prefs */
648 unsigned int ocseq; /*!< Current outgoing seqno */
649 unsigned int icseq; /*!< Current incoming seqno */
650 ast_group_t callgroup; /*!< Call group */
651 ast_group_t pickupgroup; /*!< Pickup group */
652 int lastinvite; /*!< Last Cseq of invite */
653 unsigned int flags; /*!< SIP_ flags */
654 int timer_t1; /*!< SIP timer T1, ms rtt */
655 unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */
656 int capability; /*!< Special capability (codec) */
657 int jointcapability; /*!< Supported capability at both ends (codecs ) */
658 int peercapability; /*!< Supported peer capability */
659 int prefcodec; /*!< Preferred codec (outbound only) */
660 int noncodeccapability;
661 int callingpres; /*!< Calling presentation */
662 int authtries; /*!< Times we've tried to authenticate */
663 int expiry; /*!< How long we take to expire */
664 int branch; /*!< One random number */
665 char tag[11]; /*!< Another random number */
666 int sessionid; /*!< SDP Session ID */
667 int sessionversion; /*!< SDP Session Version */
668 struct sockaddr_in sa; /*!< Our peer */
669 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
670 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
671 int redircodecs; /*!< Redirect codecs */
672 struct sockaddr_in recv; /*!< Received as */
673 struct in_addr ourip; /*!< Our IP */
674 struct ast_channel *owner; /*!< Who owns us */
675 struct sip_pvt *refer_call; /*!< Call we are referring */
676 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
677 int route_persistant; /*!< Is this the "real" route? */
678 struct sip_auth *peerauth; /*!< Realm authentication */
679 int noncecount; /*!< Nonce-count */
680 char lastmsg[256]; /*!< Last Message sent/received */
681 int amaflags; /*!< AMA Flags */
682 int pendinginvite; /*!< Any pending invite */
684 int osphandle; /*!< OSP Handle for call */
685 time_t ospstart; /*!< OSP Start time */
686 unsigned int osptimelimit; /*!< OSP call duration limit */
688 struct sip_request initreq; /*!< Initial request */
690 int maxtime; /*!< Max time for first response */
691 int initid; /*!< Auto-congest ID if appropriate */
692 int autokillid; /*!< Auto-kill ID */
693 time_t lastrtprx; /*!< Last RTP received */
694 time_t lastrtptx; /*!< Last RTP sent */
695 int rtptimeout; /*!< RTP timeout time */
696 int rtpholdtimeout; /*!< RTP timeout when on hold */
697 int rtpkeepalive; /*!< Send RTP packets for keepalive */
698 enum subscriptiontype subscribed; /*!< Is this dialog a subscription? */
700 int laststate; /*!< Last known extension state */
703 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
705 struct sip_peer *peerpoke; /*!< If this dialog is to poke a peer, which one */
706 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
707 struct ast_rtp *rtp; /*!< RTP Session */
708 struct ast_rtp *vrtp; /*!< Video RTP session */
709 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
710 struct sip_history_head *history; /*!< History of this SIP dialog */
711 struct ast_variable *chanvars; /*!< Channel variables to set for call */
712 struct sip_pvt *next; /*!< Next dialog in chain */
713 struct sip_invite_param *options; /*!< Options for INVITE */
716 #define FLAG_RESPONSE (1 << 0)
717 #define FLAG_FATAL (1 << 1)
719 /*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
721 struct sip_pkt *next; /*!< Next packet */
722 int retrans; /*!< Retransmission number */
723 int method; /*!< SIP method for this packet */
724 int seqno; /*!< Sequence number */
725 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
726 struct sip_pvt *owner; /*!< Owner AST call */
727 int retransid; /*!< Retransmission ID */
728 int timer_a; /*!< SIP timer A, retransmission timer */
729 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
730 int packetlen; /*!< Length of packet */
734 /*! \brief Structure for SIP user data. User's place calls to us */
736 /* Users who can access various contexts */
737 ASTOBJ_COMPONENTS(struct sip_user);
738 char secret[80]; /*!< Password */
739 char md5secret[80]; /*!< Password in md5 */
740 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
741 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
742 char cid_num[80]; /*!< Caller ID num */
743 char cid_name[80]; /*!< Caller ID name */
744 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
745 char language[MAX_LANGUAGE]; /*!< Default language for this user */
746 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
747 char useragent[256]; /*!< User agent in SIP request */
748 struct ast_codec_pref prefs; /*!< codec prefs */
749 ast_group_t callgroup; /*!< Call group */
750 ast_group_t pickupgroup; /*!< Pickup Group */
751 unsigned int flags; /*!< SIP flags */
752 unsigned int sipoptions; /*!< Supported SIP options */
753 struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
754 int amaflags; /*!< AMA flags for billing */
755 int callingpres; /*!< Calling id presentation */
756 int capability; /*!< Codec capability */
757 int inUse; /*!< Number of calls in use */
758 int call_limit; /*!< Limit of concurrent calls */
759 struct ast_ha *ha; /*!< ACL setting */
760 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
763 /* Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
765 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
766 /*!< peer->name is the unique name of this object */
767 char secret[80]; /*!< Password */
768 char md5secret[80]; /*!< Password in MD5 */
769 struct sip_auth *auth; /*!< Realm authentication list */
770 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
771 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
772 char username[80]; /*!< Temporary username until registration */
773 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
774 int amaflags; /*!< AMA Flags (for billing) */
775 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
776 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
777 char fromuser[80]; /*!< From: user when calling this peer */
778 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
779 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
780 char cid_num[80]; /*!< Caller ID num */
781 char cid_name[80]; /*!< Caller ID name */
782 int callingpres; /*!< Calling id presentation */
783 int inUse; /*!< Number of calls in use */
784 int call_limit; /*!< Limit of concurrent calls */
785 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
786 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
787 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
788 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
789 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
790 struct ast_codec_pref prefs; /*!< codec prefs */
792 time_t lastmsgcheck; /*!< Last time we checked for MWI */
793 unsigned int flags; /*!< SIP flags */
794 unsigned int sipoptions; /*!< Supported SIP options */
795 struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
796 int expire; /*!< When to expire this peer registration */
797 int capability; /*!< Codec capability */
798 int rtptimeout; /*!< RTP timeout */
799 int rtpholdtimeout; /*!< RTP Hold Timeout */
800 int rtpkeepalive; /*!< Send RTP packets for keepalive */
801 ast_group_t callgroup; /*!< Call group */
802 ast_group_t pickupgroup; /*!< Pickup group */
803 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
804 struct sockaddr_in addr; /*!< IP address of peer */
807 struct sip_pvt *call; /*!< Call pointer */
808 int pokeexpire; /*!< When to expire poke (qualify= checking) */
809 int lastms; /*!< How long last response took (in ms), or -1 for no response */
810 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
811 struct timeval ps; /*!< Ping send time */
813 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
814 struct ast_ha *ha; /*!< Access control list */
815 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
819 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
820 static int sip_reloading = 0;
821 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
823 /* States for outbound registrations (with register= lines in sip.conf */
824 #define REG_STATE_UNREGISTERED 0
825 #define REG_STATE_REGSENT 1
826 #define REG_STATE_AUTHSENT 2
827 #define REG_STATE_REGISTERED 3
828 #define REG_STATE_REJECTED 4
829 #define REG_STATE_TIMEOUT 5
830 #define REG_STATE_NOAUTH 6
831 #define REG_STATE_FAILED 7
834 /*! \brief sip_registry: Registrations with other SIP proxies */
835 struct sip_registry {
836 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
837 AST_DECLARE_STRING_FIELDS(
838 AST_STRING_FIELD(callid); /*!< Global Call-ID */
839 AST_STRING_FIELD(realm); /*!< Authorization realm */
840 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
841 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
842 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
843 AST_STRING_FIELD(domain); /*!< Authorization domain */
844 AST_STRING_FIELD(username); /*!< Who we are registering as */
845 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
846 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
847 AST_STRING_FIELD(secret); /*!< Password in clear text */
848 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
849 AST_STRING_FIELD(contact); /*!< Contact extension */
850 AST_STRING_FIELD(random);
852 int portno; /*!< Optional port override */
853 int expire; /*!< Sched ID of expiration */
854 int regattempts; /*!< Number of attempts (since the last success) */
855 int timeout; /*!< sched id of sip_reg_timeout */
856 int refresh; /*!< How often to refresh */
857 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
858 int regstate; /*!< Registration state (see above) */
859 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
860 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
861 struct sockaddr_in us; /*!< Who the server thinks we are */
862 int noncecount; /*!< Nonce-count */
863 char lastmsg[256]; /*!< Last Message sent/received */
866 /*! \brief The user list: Users and friends */
867 static struct ast_user_list {
868 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
871 /*! \brief The peer list: Peers and Friends */
872 static struct ast_peer_list {
873 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
876 /*! \brief The register list: Other SIP proxys we register with and place calls to */
877 static struct ast_register_list {
878 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
883 static int __sip_do_register(struct sip_registry *r);
885 static int sipsock = -1;
888 static struct sockaddr_in bindaddr = { 0, };
889 static struct sockaddr_in externip;
890 static char externhost[MAXHOSTNAMELEN] = "";
891 static time_t externexpire = 0;
892 static int externrefresh = 10;
893 static struct ast_ha *localaddr;
894 static int callevents; /*!< Whether we send manager events or not */
896 /* The list of manual NOTIFY types we know how to send */
897 struct ast_config *notify_types;
899 static struct sip_auth *authl = NULL; /*!< Authentication list */
902 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
903 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
904 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
905 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);
906 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
907 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
908 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
909 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
910 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
911 static int transmit_info_with_vidupdate(struct sip_pvt *p);
912 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
913 static int transmit_refer(struct sip_pvt *p, const char *dest);
914 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
915 static struct sip_peer *temp_peer(const char *name);
916 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
917 static void free_old_route(struct sip_route *route);
918 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
919 static int update_call_counter(struct sip_pvt *fup, int event);
920 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
921 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
922 static int sip_do_reload(enum channelreloadreason reason);
923 static int expire_register(void *data);
925 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
926 static int sip_devicestate(void *data);
927 static int sip_sendtext(struct ast_channel *ast, const char *text);
928 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
929 static int sip_hangup(struct ast_channel *ast);
930 static int sip_answer(struct ast_channel *ast);
931 static struct ast_frame *sip_read(struct ast_channel *ast);
932 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
933 static int sip_indicate(struct ast_channel *ast, int condition);
934 static int sip_transfer(struct ast_channel *ast, const char *dest);
935 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
936 static int sip_senddigit(struct ast_channel *ast, char digit);
937 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
938 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
939 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
940 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
941 static void append_date(struct sip_request *req); /* Append date to SIP packet */
942 static int determine_firstline_parts(struct sip_request *req);
943 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
944 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
945 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
946 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
947 int find_sip_method(char *msg);
948 unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported);
950 /*! \brief Definition of this channel for PBX channel registration */
951 static const struct ast_channel_tech sip_tech = {
953 .description = "Session Initiation Protocol (SIP)",
954 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
955 .properties = AST_CHAN_TP_WANTSJITTER,
956 .requester = sip_request_call,
957 .devicestate = sip_devicestate,
959 .hangup = sip_hangup,
960 .answer = sip_answer,
963 .write_video = sip_write,
964 .indicate = sip_indicate,
965 .transfer = sip_transfer,
967 .send_digit = sip_senddigit,
968 .bridge = ast_rtp_bridge,
969 .send_text = sip_sendtext,
973 \brief Thread-safe random number generator
974 \return a random number
976 This function uses a mutex lock to guarantee that no
977 two threads will receive the same random number.
979 static force_inline int thread_safe_rand(void)
983 ast_mutex_lock(&rand_lock);
985 ast_mutex_unlock(&rand_lock);
990 /*! \brief find_sip_method: Find SIP method from header
991 * Strictly speaking, SIP methods are case SENSITIVE, but we don't check
992 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
993 int find_sip_method(char *msg)
997 if (ast_strlen_zero(msg))
1000 for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
1001 if (!strcasecmp(sip_methods[i].text, msg))
1002 res = sip_methods[i].id;
1007 /*! \brief parse_sip_options: Parse supported header in incoming packet */
1008 unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
1012 char *temp = ast_strdupa(supported);
1014 unsigned int profile = 0;
1016 if (ast_strlen_zero(supported) )
1019 if (option_debug > 2 && sipdebug)
1020 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1025 if ( (sep = strchr(next, ',')) != NULL) {
1029 while (*next == ' ') /* Skip spaces */
1031 if (option_debug > 2 && sipdebug)
1032 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1033 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
1034 if (!strcasecmp(next, sip_options[i].text)) {
1035 profile |= sip_options[i].id;
1037 if (option_debug > 2 && sipdebug)
1038 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1042 if (option_debug > 2 && sipdebug)
1043 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1047 pvt->sipoptions = profile;
1049 ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
1054 /*! \brief sip_debug_test_addr: See if we pass debug IP filter */
1055 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
1059 if (debugaddr.sin_addr.s_addr) {
1060 if (((ntohs(debugaddr.sin_port) != 0)
1061 && (debugaddr.sin_port != addr->sin_port))
1062 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1068 /*! \brief sip_debug_test_pvt: Test PVT for debugging output */
1069 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1073 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
1077 /*! \brief __sip_xmit: Transmit SIP message */
1078 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1081 char iabuf[INET_ADDRSTRLEN];
1083 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1084 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
1086 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
1089 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));
1094 static void sip_destroy(struct sip_pvt *p);
1096 /*! \brief build_via: Build a Via header for a request */
1097 static void build_via(struct sip_pvt *p)
1099 char iabuf[INET_ADDRSTRLEN];
1100 /* Work around buggy UNIDEN UIP200 firmware */
1101 const char *rport = ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1103 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1104 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1105 ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1108 /*! \brief ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? */
1109 /* Only used for outbound registrations */
1110 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1113 * Using the localaddr structure built up with localnet statements
1114 * apply it to their address to see if we need to substitute our
1115 * externip or can get away with our internal bindaddr
1117 struct sockaddr_in theirs;
1118 theirs.sin_addr = *them;
1119 if (localaddr && externip.sin_addr.s_addr &&
1120 ast_apply_ha(localaddr, &theirs)) {
1121 char iabuf[INET_ADDRSTRLEN];
1122 if (externexpire && (time(NULL) >= externexpire)) {
1123 struct ast_hostent ahp;
1125 time(&externexpire);
1126 externexpire += externrefresh;
1127 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1128 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1130 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1132 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
1133 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1134 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1136 else if (bindaddr.sin_addr.s_addr)
1137 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
1139 return ast_ouraddrfor(them, us);
1143 /*! \brief append_history: Append to SIP dialog history
1144 \return Always returns 0 */
1145 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1147 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1148 __attribute__ ((format (printf, 2, 3)));
1150 /*! \brief Append to SIP dialog history with arg list */
1151 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1153 char buf[80], *c = buf; /* max history length */
1154 struct sip_history *hist;
1157 vsnprintf(buf, sizeof(buf), fmt, ap);
1158 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1159 l = strlen(buf) + 1;
1160 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1162 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1166 memcpy(hist->event, buf, l);
1167 AST_LIST_INSERT_TAIL(p->history, hist, list);
1170 /*! \brief Append to SIP dialog history with arg list */
1171 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1175 if (!recordhistory || !p)
1178 append_history_va(p, fmt, ap);
1184 /*! \brief retrans_pkt: Retransmit SIP message if no answer */
1185 static int retrans_pkt(void *data)
1187 struct sip_pkt *pkt=data, *prev, *cur = NULL;
1188 char iabuf[INET_ADDRSTRLEN];
1189 int reschedule = DEFAULT_RETRANS;
1192 ast_mutex_lock(&pkt->owner->lock);
1194 if (pkt->retrans < MAX_RETRANS) {
1196 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1197 if (sipdebug && option_debug > 3)
1198 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);
1202 if (sipdebug && option_debug > 3)
1203 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1207 pkt->timer_a = 2 * pkt->timer_a;
1209 /* For non-invites, a maximum of 4 secs */
1210 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1211 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1214 /* Reschedule re-transmit */
1215 reschedule = siptimer_a;
1216 if (option_debug > 3)
1217 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);
1220 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1221 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
1222 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);
1224 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);
1227 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1228 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1229 ast_mutex_unlock(&pkt->owner->lock);
1232 /* Too many retries */
1233 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1234 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 {
1235 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1236 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1238 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1240 pkt->retransid = -1;
1242 if (ast_test_flag(pkt, FLAG_FATAL)) {
1243 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1244 ast_mutex_unlock(&pkt->owner->lock);
1246 ast_mutex_lock(&pkt->owner->lock);
1248 if (pkt->owner->owner) {
1249 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
1250 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1251 ast_queue_hangup(pkt->owner->owner);
1252 ast_mutex_unlock(&pkt->owner->owner->lock);
1254 /* If no channel owner, destroy now */
1255 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
1258 /* In any case, go ahead and remove the packet */
1260 cur = pkt->owner->packets;
1269 prev->next = cur->next;
1271 pkt->owner->packets = cur->next;
1272 ast_mutex_unlock(&pkt->owner->lock);
1276 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1278 ast_mutex_unlock(&pkt->owner->lock);
1282 /*! \brief __sip_reliable_xmit: transmit packet with retransmits */
1283 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1285 struct sip_pkt *pkt;
1286 int siptimer_a = DEFAULT_RETRANS;
1288 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1290 memcpy(pkt->data, data, len);
1291 pkt->method = sipmethod;
1292 pkt->packetlen = len;
1293 pkt->next = p->packets;
1297 pkt->data[len] = '\0';
1298 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1300 ast_set_flag(pkt, FLAG_FATAL);
1302 siptimer_a = pkt->timer_t1 * 2;
1304 /* Schedule retransmission */
1305 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1306 if (option_debug > 3 && sipdebug)
1307 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1308 pkt->next = p->packets;
1311 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1312 if (sipmethod == SIP_INVITE) {
1313 /* Note this is a pending invite */
1314 p->pendinginvite = seqno;
1319 /*! \brief __sip_autodestruct: Kill a SIP dialog (called by scheduler) */
1320 static int __sip_autodestruct(void *data)
1322 struct sip_pvt *p = data;
1325 /* If this is a subscription, tell the phone that we got a timeout */
1326 if (p->subscribed) {
1327 p->subscribed = TIMEOUT;
1328 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1329 p->subscribed = NONE;
1330 append_history(p, "Subscribestatus", "timeout");
1331 if (option_debug > 2)
1332 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1333 return 10000; /* Reschedule this destruction so that we know that it's gone */
1336 /* Reset schedule ID */
1340 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1341 append_history(p, "AutoDestroy", "");
1343 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1344 ast_queue_hangup(p->owner);
1351 /*! \brief sip_scheddestroy: Schedule destruction of SIP call */
1352 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1354 if (sip_debug_test_pvt(p))
1355 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1357 append_history(p, "SchedDestroy", "%d ms", ms);
1359 if (p->autokillid > -1)
1360 ast_sched_del(sched, p->autokillid);
1361 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1365 /*! \brief sip_cancel_destroy: Cancel destruction of SIP dialog */
1366 static int sip_cancel_destroy(struct sip_pvt *p)
1368 if (p->autokillid > -1)
1369 ast_sched_del(sched, p->autokillid);
1370 append_history(p, "CancelDestroy", "");
1375 /*! \brief __sip_ack: Acknowledges receipt of a packet and stops retransmission */
1376 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1378 struct sip_pkt *cur, *prev = NULL;
1380 int resetinvite = 0;
1381 /* Just in case... */
1384 msg = sip_methods[sipmethod].text;
1388 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1389 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1390 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1391 ast_mutex_lock(&p->lock);
1392 if (!resp && (seqno == p->pendinginvite)) {
1393 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1394 p->pendinginvite = 0;
1397 /* this is our baby */
1399 prev->next = cur->next;
1401 p->packets = cur->next;
1402 if (cur->retransid > -1) {
1403 if (sipdebug && option_debug > 3)
1404 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1405 ast_sched_del(sched, cur->retransid);
1408 ast_mutex_unlock(&p->lock);
1415 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1419 /* Pretend to ack all packets */
1420 static int __sip_pretend_ack(struct sip_pvt *p)
1422 struct sip_pkt *cur=NULL;
1425 if (cur == p->packets) {
1426 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1431 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
1432 else { /* Unknown packet type */
1435 ast_copy_string(method, p->packets->data, sizeof(method));
1436 c = ast_skip_blanks(method); /* XXX what ? */
1438 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1444 /*! \brief __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) */
1445 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1447 struct sip_pkt *cur;
1449 char *msg = sip_methods[sipmethod].text;
1453 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1454 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1455 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1456 /* this is our baby */
1457 if (cur->retransid > -1) {
1458 if (option_debug > 3 && sipdebug)
1459 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
1460 ast_sched_del(sched, cur->retransid);
1462 cur->retransid = -1;
1468 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");
1472 static void parse_request(struct sip_request *req);
1473 static char *get_header(struct sip_request *req, char *name);
1474 static void copy_request(struct sip_request *dst,struct sip_request *src);
1476 /*! \brief parse_copy: Copy SIP request, parse it */
1477 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1479 memset(dst, 0, sizeof(*dst));
1480 memcpy(dst->data, src->data, sizeof(dst->data));
1481 dst->len = src->len;
1485 /*! \brief send_response: Transmit response on SIP request*/
1486 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1490 if (sip_debug_test_pvt(p)) {
1491 char iabuf[INET_ADDRSTRLEN];
1492 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1493 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);
1495 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);
1497 if (recordhistory) {
1498 struct sip_request tmp;
1499 parse_copy(&tmp, req);
1500 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1503 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method) :
1504 __sip_xmit(p, req->data, req->len);
1510 /*! \brief send_request: Send SIP Request to the other part of the dialogue */
1511 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1515 if (sip_debug_test_pvt(p)) {
1516 char iabuf[INET_ADDRSTRLEN];
1517 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1518 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);
1520 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);
1522 if (recordhistory) {
1523 struct sip_request tmp;
1524 parse_copy(&tmp, req);
1525 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1528 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1529 __sip_xmit(p, req->data, req->len);
1533 /*! \brief get_in_brackets: Pick out text in brackets from character string */
1534 /* returns pointer to terminated stripped string. modifies input string. */
1535 static char *get_in_brackets(char *tmp)
1539 char *first_bracket;
1540 char *second_bracket;
1545 first_quote = strchr(parse, '"');
1546 first_bracket = strchr(parse, '<');
1547 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1549 for (parse = first_quote + 1; *parse; parse++) {
1550 if ((*parse == '"') && (last_char != '\\'))
1555 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1561 if (first_bracket) {
1562 second_bracket = strchr(first_bracket + 1, '>');
1563 if (second_bracket) {
1564 *second_bracket = '\0';
1565 return first_bracket + 1;
1567 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1575 /*! \brief sip_sendtext: Send SIP MESSAGE text within a call */
1576 /* Called from PBX core text message functions */
1577 static int sip_sendtext(struct ast_channel *ast, const char *text)
1579 struct sip_pvt *p = ast->tech_pvt;
1580 int debug=sip_debug_test_pvt(p);
1583 ast_verbose("Sending text %s on %s\n", text, ast->name);
1586 if (ast_strlen_zero(text))
1589 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1590 transmit_message_with_text(p, text);
1594 /*! \brief realtime_update_peer: Update peer object in realtime storage */
1595 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1599 char regseconds[20];
1604 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
1605 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1606 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1609 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
1611 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1614 /*! \brief register_peer_exten: Automatically add peer extension to dial plan */
1615 static void register_peer_exten(struct sip_peer *peer, int onoff)
1618 char *stringp, *ext;
1619 if (!ast_strlen_zero(regcontext)) {
1620 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
1622 while((ext = strsep(&stringp, "&"))) {
1624 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", ast_strdup(peer->name), free, channeltype);
1626 ast_context_remove_extension(regcontext, ext, 1, NULL);
1631 /*! \brief sip_destroy_peer: Destroy peer object from memory */
1632 static void sip_destroy_peer(struct sip_peer *peer)
1634 /* Delete it, it needs to disappear */
1636 sip_destroy(peer->call);
1637 if (peer->chanvars) {
1638 ast_variables_destroy(peer->chanvars);
1639 peer->chanvars = NULL;
1641 if (peer->expire > -1)
1642 ast_sched_del(sched, peer->expire);
1643 if (peer->pokeexpire > -1)
1644 ast_sched_del(sched, peer->pokeexpire);
1645 register_peer_exten(peer, 0);
1646 ast_free_ha(peer->ha);
1647 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1649 else if (ast_test_flag(peer, SIP_REALTIME))
1653 clear_realm_authentication(peer->auth);
1654 peer->auth = (struct sip_auth *) NULL;
1656 ast_dnsmgr_release(peer->dnsmgr);
1660 /*! \brief update_peer: Update peer data in database (if used) */
1661 static void update_peer(struct sip_peer *p, int expiry)
1663 int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1664 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
1665 (ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) {
1666 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
1671 /*! \brief realtime_peer: Get peer from realtime storage
1672 * Checks the "sippeers" realtime family from extconfig.conf
1673 * \todo Consider adding check of port address when matching here to follow the same
1674 * algorithm as for static peers. Will we break anything by adding that?
1676 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1678 struct sip_peer *peer=NULL;
1679 struct ast_variable *var;
1680 struct ast_variable *tmp;
1681 char *newpeername = (char *) peername;
1684 /* First check on peer name */
1686 var = ast_load_realtime("sippeers", "name", peername, NULL);
1687 else if (sin) { /* Then check on IP address for dynamic peers */
1688 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1689 var = ast_load_realtime("sippeers", "host", iabuf, NULL); /* First check for fixed IP hosts */
1691 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */
1699 for (tmp = var; tmp; tmp = tmp->next) {
1700 /* If this is type=user, then skip this object. */
1701 if (!strcasecmp(tmp->name, "type") &&
1702 !strcasecmp(tmp->value, "user")) {
1703 ast_variables_destroy(var);
1705 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1706 newpeername = tmp->value;
1710 if (!newpeername) { /* Did not find peer in realtime */
1711 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1712 ast_variables_destroy(var);
1713 return (struct sip_peer *) NULL;
1716 /* Peer found in realtime, now build it in memory */
1717 peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1719 ast_variables_destroy(var);
1720 return (struct sip_peer *) NULL;
1723 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1725 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1726 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1727 if (peer->expire > -1) {
1728 ast_sched_del(sched, peer->expire);
1730 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1732 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1734 ast_set_flag(peer, SIP_REALTIME);
1736 ast_variables_destroy(var);
1741 /*! \brief sip_addrcmp: Support routine for find_peer */
1742 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1744 /* We know name is the first field, so we can cast */
1745 struct sip_peer *p = (struct sip_peer *)name;
1746 return !(!inaddrcmp(&p->addr, sin) ||
1747 (ast_test_flag(p, SIP_INSECURE_PORT) &&
1748 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1751 /*! \brief find_peer: Locate peer by name or ip address
1752 * This is used on incoming SIP message to find matching peer on ip
1753 or outgoing message to find matching peer on name */
1754 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1756 struct sip_peer *p = NULL;
1759 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1761 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
1763 if (!p && realtime) {
1764 p = realtime_peer(peer, sin);
1769 /*! \brief sip_destroy_user: Remove user object from in-memory storage */
1770 static void sip_destroy_user(struct sip_user *user)
1772 ast_free_ha(user->ha);
1773 if (user->chanvars) {
1774 ast_variables_destroy(user->chanvars);
1775 user->chanvars = NULL;
1777 if (ast_test_flag(user, SIP_REALTIME))
1784 /*! \brief realtime_user: Load user from realtime storage
1785 * Loads user from "sipusers" category in realtime (extconfig.conf)
1786 * Users are matched on From: user name (the domain in skipped) */
1787 static struct sip_user *realtime_user(const char *username)
1789 struct ast_variable *var;
1790 struct ast_variable *tmp;
1791 struct sip_user *user = NULL;
1793 var = ast_load_realtime("sipusers", "name", username, NULL);
1798 for (tmp = var; tmp; tmp = tmp->next) {
1799 if (!strcasecmp(tmp->name, "type") &&
1800 !strcasecmp(tmp->value, "peer")) {
1801 ast_variables_destroy(var);
1806 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1808 if (!user) { /* No user found */
1809 ast_variables_destroy(var);
1813 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1814 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1816 ASTOBJ_CONTAINER_LINK(&userl,user);
1818 /* Move counter from s to r... */
1821 ast_set_flag(user, SIP_REALTIME);
1823 ast_variables_destroy(var);
1827 /*! \brief find_user: Locate user by name
1828 * Locates user by name (From: sip uri user name part) first
1829 * from in-memory list (static configuration) then from
1830 * realtime storage (defined in extconfig.conf) */
1831 static struct sip_user *find_user(const char *name, int realtime)
1833 struct sip_user *u = NULL;
1834 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1835 if (!u && realtime) {
1836 u = realtime_user(name);
1841 /*! \brief create_addr_from_peer: create address structure from peer reference */
1842 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1844 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1845 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
1846 if (peer->addr.sin_addr.s_addr) {
1847 r->sa.sin_family = peer->addr.sin_family;
1848 r->sa.sin_addr = peer->addr.sin_addr;
1849 r->sa.sin_port = peer->addr.sin_port;
1851 r->sa.sin_family = peer->defaddr.sin_family;
1852 r->sa.sin_addr = peer->defaddr.sin_addr;
1853 r->sa.sin_port = peer->defaddr.sin_port;
1855 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1860 ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
1861 r->capability = peer->capability;
1862 r->prefs = peer->prefs;
1864 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1865 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1868 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1869 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1871 ast_string_field_set(r, peername, peer->username);
1872 ast_string_field_set(r, authname, peer->username);
1873 ast_string_field_set(r, username, peer->username);
1874 ast_string_field_set(r, peersecret, peer->secret);
1875 ast_string_field_set(r, peermd5secret, peer->md5secret);
1876 ast_string_field_set(r, tohost, peer->tohost);
1877 ast_string_field_set(r, fullcontact, peer->fullcontact);
1878 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1881 tmpcall = ast_strdupa(r->callid);
1883 c = strchr(tmpcall, '@');
1886 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
1890 if (ast_strlen_zero(r->tohost)) {
1891 char iabuf[INET_ADDRSTRLEN];
1893 if (peer->addr.sin_addr.s_addr)
1894 ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr);
1896 ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr);
1897 ast_string_field_set(r, tohost, iabuf);
1899 if (!ast_strlen_zero(peer->fromdomain))
1900 ast_string_field_set(r, fromdomain, peer->fromdomain);
1901 if (!ast_strlen_zero(peer->fromuser))
1902 ast_string_field_set(r, fromuser, peer->fromuser);
1903 r->maxtime = peer->maxms;
1904 r->callgroup = peer->callgroup;
1905 r->pickupgroup = peer->pickupgroup;
1906 /* Set timer T1 to RTT for this peer (if known by qualify=) */
1907 if (peer->maxms && peer->lastms)
1908 r->timer_t1 = peer->lastms;
1909 if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
1910 r->noncodeccapability |= AST_RTP_DTMF;
1912 r->noncodeccapability &= ~AST_RTP_DTMF;
1913 ast_string_field_set(r, context, peer->context);
1914 r->rtptimeout = peer->rtptimeout;
1915 r->rtpholdtimeout = peer->rtpholdtimeout;
1916 r->rtpkeepalive = peer->rtpkeepalive;
1917 if (peer->call_limit)
1918 ast_set_flag(r, SIP_CALL_LIMIT);
1923 /*! \brief create_addr: create address structure from peer name
1924 * Or, if peer not found, find it in the global DNS
1925 * returns TRUE (-1) on failure, FALSE on success */
1926 static int create_addr(struct sip_pvt *dialog, const char *opeer)
1929 struct ast_hostent ahp;
1934 char host[MAXHOSTNAMELEN], *hostn;
1937 ast_copy_string(peer, opeer, sizeof(peer));
1938 port = strchr(peer, ':');
1943 dialog->sa.sin_family = AF_INET;
1944 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
1945 p = find_peer(peer, NULL, 1);
1949 if (create_addr_from_peer(dialog, p))
1950 ASTOBJ_UNREF(p, sip_destroy_peer);
1958 portno = atoi(port);
1960 portno = DEFAULT_SIP_PORT;
1962 char service[MAXHOSTNAMELEN];
1965 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1966 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1972 hp = ast_gethostbyname(hostn, &ahp);
1974 ast_string_field_set(dialog, tohost, peer);
1975 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
1976 dialog->sa.sin_port = htons(portno);
1977 memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
1980 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1984 ASTOBJ_UNREF(p, sip_destroy_peer);
1989 /*! \brief auto_congest: Scheduled congestion on a call */
1990 static int auto_congest(void *nothing)
1992 struct sip_pvt *p = nothing;
1993 ast_mutex_lock(&p->lock);
1996 if (!ast_mutex_trylock(&p->owner->lock)) {
1997 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1998 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1999 ast_mutex_unlock(&p->owner->lock);
2002 ast_mutex_unlock(&p->lock);
2009 /*! \brief sip_call: Initiate SIP call from PBX
2010 * used from the dial() application */
2011 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2016 const char *osphandle = NULL;
2018 struct varshead *headp;
2019 struct ast_var_t *current;
2024 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2025 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2030 /* Check whether there is vxml_url, distinctive ring variables */
2032 headp=&ast->varshead;
2033 AST_LIST_TRAVERSE(headp,current,entries) {
2034 /* Check whether there is a VXML_URL variable */
2035 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2036 p->options->vxml_url = ast_var_value(current);
2037 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2038 p->options->uri_options = ast_var_value(current);
2039 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2040 /* Check whether there is a ALERT_INFO variable */
2041 p->options->distinctive_ring = ast_var_value(current);
2042 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2043 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2044 p->options->addsipheaders = 1;
2049 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
2050 p->options->osptoken = ast_var_value(current);
2051 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
2052 osphandle = ast_var_value(current);
2058 ast_set_flag(p, SIP_OUTGOING);
2060 if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
2061 /* Force Disable OSP support */
2063 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
2064 p->options->osptoken = NULL;
2069 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2070 res = update_call_counter(p, INC_CALL_LIMIT);
2072 p->callingpres = ast->cid.cid_pres;
2073 p->jointcapability = p->capability;
2074 transmit_invite(p, SIP_INVITE, 1, 2);
2076 /* Initialize auto-congest time */
2077 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2083 /*! \brief sip_registry_destroy: Destroy registry object */
2084 /* Objects created with the register= statement in static configuration */
2085 static void sip_registry_destroy(struct sip_registry *reg)
2089 /* Clear registry before destroying to ensure
2090 we don't get reentered trying to grab the registry lock */
2091 reg->call->registry = NULL;
2092 sip_destroy(reg->call);
2094 if (reg->expire > -1)
2095 ast_sched_del(sched, reg->expire);
2096 if (reg->timeout > -1)
2097 ast_sched_del(sched, reg->timeout);
2098 ast_string_field_free_all(reg);
2104 /*! \brief __sip_destroy: Execute destrucion of SIP dialog structure, release memory */
2105 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2107 struct sip_pvt *cur, *prev = NULL;
2110 if (sip_debug_test_pvt(p))
2111 ast_verbose("Destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2114 sip_dump_history(p);
2119 if (p->stateid > -1)
2120 ast_extension_state_del(p->stateid, NULL);
2122 ast_sched_del(sched, p->initid);
2123 if (p->autokillid > -1)
2124 ast_sched_del(sched, p->autokillid);
2127 ast_rtp_destroy(p->rtp);
2130 ast_rtp_destroy(p->vrtp);
2133 free_old_route(p->route);
2137 if (p->registry->call == p)
2138 p->registry->call = NULL;
2139 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2142 /* Unlink us from the owner if we have one */
2145 ast_mutex_lock(&p->owner->lock);
2147 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2148 p->owner->tech_pvt = NULL;
2150 ast_mutex_unlock(&p->owner->lock);
2154 while(!AST_LIST_EMPTY(p->history)) {
2155 struct sip_history *hist = AST_LIST_FIRST(p->history);
2156 AST_LIST_REMOVE_HEAD(p->history, list);
2167 prev->next = cur->next;
2176 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2180 ast_sched_del(sched, p->initid);
2182 while((cp = p->packets)) {
2183 p->packets = p->packets->next;
2184 if (cp->retransid > -1) {
2185 ast_sched_del(sched, cp->retransid);
2190 ast_variables_destroy(p->chanvars);
2193 ast_mutex_destroy(&p->lock);
2195 ast_string_field_free_all(p);
2200 /*! \brief update_call_counter: Handle call_limit for SIP users
2201 * Setting a call-limit will cause calls above the limit not to be accepted.
2203 * Remember that for a type=friend, there's one limit for the user and
2204 * another for the peer, not a combined call limit.
2205 * This will cause unexpected behaviour in subscriptions, since a "friend"
2206 * is *two* devices in Asterisk, not one.
2208 * Thought: For realtime, we should propably update storage with inuse counter...
2210 static int update_call_counter(struct sip_pvt *fup, int event)
2213 int *inuse, *call_limit;
2214 int outgoing = ast_test_flag(fup, SIP_OUTGOING);
2215 struct sip_user *u = NULL;
2216 struct sip_peer *p = NULL;
2218 if (option_debug > 2)
2219 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2220 /* Test if we need to check call limits, in order to avoid
2221 realtime lookups if we do not need it */
2222 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
2225 ast_copy_string(name, fup->username, sizeof(name));
2227 /* Check the list of users */
2228 if (!outgoing) /* Only check users for incoming calls */
2229 u = find_user(name, 1);
2233 call_limit = &u->call_limit;
2236 /* Try to find peer */
2238 p = find_peer(fup->peername, NULL, 1);
2241 call_limit = &p->call_limit;
2242 ast_copy_string(name, fup->peername, sizeof(name));
2244 if (option_debug > 1)
2245 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2250 /* incoming and outgoing affects the inUse counter */
2251 case DEC_CALL_LIMIT:
2253 if (ast_test_flag(fup, SIP_INC_COUNT))
2258 if (option_debug > 1 || sipdebug) {
2259 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2262 case INC_CALL_LIMIT:
2263 if (*call_limit > 0 ) {
2264 if (*inuse >= *call_limit) {
2265 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);
2267 ASTOBJ_UNREF(u, sip_destroy_user);
2269 ASTOBJ_UNREF(p, sip_destroy_peer);
2274 ast_set_flag(fup, SIP_INC_COUNT);
2275 if (option_debug > 1 || sipdebug) {
2276 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2280 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2283 ASTOBJ_UNREF(u, sip_destroy_user);
2285 ASTOBJ_UNREF(p, sip_destroy_peer);
2289 /*! \brief sip_destroy: Destroy SIP call structure */
2290 static void sip_destroy(struct sip_pvt *p)
2292 ast_mutex_lock(&iflock);
2293 __sip_destroy(p, 1);
2294 ast_mutex_unlock(&iflock);
2298 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
2300 /*! \brief hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes */
2301 static int hangup_sip2cause(int cause)
2303 /* Possible values taken from causes.h */
2306 case 401: /* Unauthorized */
2307 return AST_CAUSE_CALL_REJECTED;
2308 case 403: /* Not found */
2309 return AST_CAUSE_CALL_REJECTED;
2310 case 404: /* Not found */
2311 return AST_CAUSE_UNALLOCATED;
2312 case 405: /* Method not allowed */
2313 return AST_CAUSE_INTERWORKING;
2314 case 407: /* Proxy authentication required */
2315 return AST_CAUSE_CALL_REJECTED;
2316 case 408: /* No reaction */
2317 return AST_CAUSE_NO_USER_RESPONSE;
2318 case 409: /* Conflict */
2319 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2320 case 410: /* Gone */
2321 return AST_CAUSE_UNALLOCATED;
2322 case 411: /* Length required */
2323 return AST_CAUSE_INTERWORKING;
2324 case 413: /* Request entity too large */
2325 return AST_CAUSE_INTERWORKING;
2326 case 414: /* Request URI too large */
2327 return AST_CAUSE_INTERWORKING;
2328 case 415: /* Unsupported media type */
2329 return AST_CAUSE_INTERWORKING;
2330 case 420: /* Bad extension */
2331 return AST_CAUSE_NO_ROUTE_DESTINATION;
2332 case 480: /* No answer */
2333 return AST_CAUSE_FAILURE;
2334 case 481: /* No answer */
2335 return AST_CAUSE_INTERWORKING;
2336 case 482: /* Loop detected */
2337 return AST_CAUSE_INTERWORKING;
2338 case 483: /* Too many hops */
2339 return AST_CAUSE_NO_ANSWER;
2340 case 484: /* Address incomplete */
2341 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2342 case 485: /* Ambigous */
2343 return AST_CAUSE_UNALLOCATED;
2344 case 486: /* Busy everywhere */
2345 return AST_CAUSE_BUSY;
2346 case 487: /* Request terminated */
2347 return AST_CAUSE_INTERWORKING;
2348 case 488: /* No codecs approved */
2349 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2350 case 491: /* Request pending */
2351 return AST_CAUSE_INTERWORKING;
2352 case 493: /* Undecipherable */
2353 return AST_CAUSE_INTERWORKING;
2354 case 500: /* Server internal failure */
2355 return AST_CAUSE_FAILURE;
2356 case 501: /* Call rejected */
2357 return AST_CAUSE_FACILITY_REJECTED;
2359 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2360 case 503: /* Service unavailable */
2361 return AST_CAUSE_CONGESTION;
2362 case 504: /* Gateway timeout */
2363 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2364 case 505: /* SIP version not supported */
2365 return AST_CAUSE_INTERWORKING;
2366 case 600: /* Busy everywhere */
2367 return AST_CAUSE_USER_BUSY;
2368 case 603: /* Decline */
2369 return AST_CAUSE_CALL_REJECTED;
2370 case 604: /* Does not exist anywhere */
2371 return AST_CAUSE_UNALLOCATED;
2372 case 606: /* Not acceptable */
2373 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2375 return AST_CAUSE_NORMAL;
2382 /*! \brief hangup_cause2sip: Convert Asterisk hangup causes to SIP codes
2384 Possible values from causes.h
2385 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
2386 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
2388 In addition to these, a lot of PRI codes is defined in causes.h
2389 ...should we take care of them too ?
2393 ISUP Cause value SIP response
2394 ---------------- ------------
2395 1 unallocated number 404 Not Found
2396 2 no route to network 404 Not found
2397 3 no route to destination 404 Not found
2398 16 normal call clearing --- (*)
2399 17 user busy 486 Busy here
2400 18 no user responding 408 Request Timeout
2401 19 no answer from the user 480 Temporarily unavailable
2402 20 subscriber absent 480 Temporarily unavailable
2403 21 call rejected 403 Forbidden (+)
2404 22 number changed (w/o diagnostic) 410 Gone
2405 22 number changed (w/ diagnostic) 301 Moved Permanently
2406 23 redirection to new destination 410 Gone
2407 26 non-selected user clearing 404 Not Found (=)
2408 27 destination out of order 502 Bad Gateway
2409 28 address incomplete 484 Address incomplete
2410 29 facility rejected 501 Not implemented
2411 31 normal unspecified 480 Temporarily unavailable
2414 static char *hangup_cause2sip(int cause)
2418 case AST_CAUSE_UNALLOCATED: /* 1 */
2419 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
2420 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
2421 return "404 Not Found";
2422 case AST_CAUSE_CONGESTION: /* 34 */
2423 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
2424 return "503 Service Unavailable";
2425 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
2426 return "408 Request Timeout";
2427 case AST_CAUSE_NO_ANSWER: /* 19 */
2428 return "480 Temporarily unavailable";
2429 case AST_CAUSE_CALL_REJECTED: /* 21 */
2430 return "403 Forbidden";
2431 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
2433 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
2434 return "480 Temporarily unavailable";
2435 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2436 return "484 Address incomplete";
2437 case AST_CAUSE_USER_BUSY:
2438 return "486 Busy here";
2439 case AST_CAUSE_FAILURE:
2440 return "500 Server internal failure";
2441 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
2442 return "501 Not Implemented";
2443 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2444 return "503 Service Unavailable";
2445 /* Used in chan_iax2 */
2446 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2447 return "502 Bad Gateway";
2448 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2449 return "488 Not Acceptable Here";
2451 case AST_CAUSE_NOTDEFINED:
2453 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2462 /*! \brief sip_hangup: Hangup SIP call
2463 * Part of PBX interface, called from ast_hangup */
2464 static int sip_hangup(struct ast_channel *ast)
2466 struct sip_pvt *p = ast->tech_pvt;
2468 struct ast_flags locflags = {0};
2471 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2474 if (option_debug && sipdebug)
2475 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2477 ast_mutex_lock(&p->lock);
2479 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2480 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2483 if (option_debug && sipdebug)
2484 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2485 update_call_counter(p, DEC_CALL_LIMIT);
2486 /* Determine how to disconnect */
2487 if (p->owner != ast) {
2488 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
2489 ast_mutex_unlock(&p->lock);
2492 /* If the call is not UP, we need to send CANCEL instead of BYE */
2493 if (ast->_state != AST_STATE_UP)
2499 ast_dsp_free(p->vad);
2502 ast->tech_pvt = NULL;
2504 ast_mutex_lock(&usecnt_lock);
2506 ast_mutex_unlock(&usecnt_lock);
2507 ast_update_use_count();
2509 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2511 /* Start the process if it's not already started */
2512 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2513 if (needcancel) { /* Outgoing call, not up */
2514 if (ast_test_flag(p, SIP_OUTGOING)) {
2515 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
2516 /* Actually don't destroy us yet, wait for the 487 on our original
2517 INVITE, but do set an autodestruct just in case we never get it. */
2518 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2519 sip_scheddestroy(p, 15000);
2520 /* stop retransmitting an INVITE that has not received a response */
2521 __sip_pretend_ack(p);
2522 if ( p->initid != -1 ) {
2523 /* channel still up - reverse dec of inUse counter
2524 only if the channel is not auto-congested */
2525 update_call_counter(p, INC_CALL_LIMIT);
2527 } else { /* Incoming call, not up */
2529 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2530 transmit_response_reliable(p, res, &p->initreq, 1);
2532 transmit_response_reliable(p, "603 Declined", &p->initreq, 1);
2534 } else { /* Call is in UP state, send BYE */
2535 if (!p->pendinginvite) {
2537 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
2539 /* Note we will need a BYE when this all settles out
2540 but we can't send one while we have "INVITE" outstanding. */
2541 ast_set_flag(p, SIP_PENDINGBYE);
2542 ast_clear_flag(p, SIP_NEEDREINVITE);
2546 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
2547 ast_mutex_unlock(&p->lock);
2551 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
2552 * Part of PBX interface */
2553 static int sip_answer(struct ast_channel *ast)
2557 struct sip_pvt *p = ast->tech_pvt;
2559 ast_mutex_lock(&p->lock);
2560 if (ast->_state != AST_STATE_UP) {
2565 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
2567 fmt=ast_getformatbyname(codec);
2569 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
2570 if (p->jointcapability & fmt) {
2571 p->jointcapability &= fmt;
2572 p->capability &= fmt;
2574 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2575 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
2578 ast_setstate(ast, AST_STATE_UP);
2580 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
2581 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
2583 ast_mutex_unlock(&p->lock);
2587 /*! \brief sip_write: Send frame to media channel (rtp) */
2588 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2590 struct sip_pvt *p = ast->tech_pvt;
2592 switch (frame->frametype) {
2593 case AST_FRAME_VOICE:
2594 if (!(frame->subclass & ast->nativeformats)) {
2595 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2596 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2600 ast_mutex_lock(&p->lock);
2602 /* If channel is not up, activate early media session */
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->rtp, frame);
2610 ast_mutex_unlock(&p->lock);
2613 case AST_FRAME_VIDEO:
2615 ast_mutex_lock(&p->lock);
2617 /* Activate video early media */
2618 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2619 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2620 ast_set_flag(p, SIP_PROGRESS_SENT);
2622 time(&p->lastrtptx);
2623 res = ast_rtp_write(p->vrtp, frame);
2625 ast_mutex_unlock(&p->lock);
2628 case AST_FRAME_IMAGE:
2632 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2639 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2640 Basically update any ->owner links */
2641 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2643 struct sip_pvt *p = newchan->tech_pvt;
2644 ast_mutex_lock(&p->lock);
2645 if (p->owner != oldchan) {
2646 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2647 ast_mutex_unlock(&p->lock);
2651 ast_mutex_unlock(&p->lock);
2655 /*! \brief sip_senddigit: Send DTMF character on SIP channel */
2656 /* within one call, we're able to transmit in many methods simultaneously */
2657 static int sip_senddigit(struct ast_channel *ast, char digit)
2659 struct sip_pvt *p = ast->tech_pvt;
2661 ast_mutex_lock(&p->lock);
2662 switch (ast_test_flag(p, SIP_DTMF)) {
2664 transmit_info_with_digit(p, digit);
2666 case SIP_DTMF_RFC2833:
2668 ast_rtp_senddigit(p->rtp, digit);
2670 case SIP_DTMF_INBAND:
2674 ast_mutex_unlock(&p->lock);
2680 /*! \brief sip_transfer: Transfer SIP call */
2681 static int sip_transfer(struct ast_channel *ast, const char *dest)
2683 struct sip_pvt *p = ast->tech_pvt;
2686 ast_mutex_lock(&p->lock);
2687 if (ast->_state == AST_STATE_RING)
2688 res = sip_sipredirect(p, dest);
2690 res = transmit_refer(p, dest);
2691 ast_mutex_unlock(&p->lock);
2695 /*! \brief sip_indicate: Play indication to user
2696 * With SIP a lot of indications is sent as messages, letting the device play
2697 the indication - busy signal, congestion etc */
2698 static int sip_indicate(struct ast_channel *ast, int condition)
2700 struct sip_pvt *p = ast->tech_pvt;
2703 ast_mutex_lock(&p->lock);
2705 case AST_CONTROL_RINGING:
2706 if (ast->_state == AST_STATE_RING) {
2707 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
2708 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2709 /* Send 180 ringing if out-of-band seems reasonable */
2710 transmit_response(p, "180 Ringing", &p->initreq);
2711 ast_set_flag(p, SIP_RINGING);
2712 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2715 /* Well, if it's not reasonable, just send in-band */
2720 case AST_CONTROL_BUSY:
2721 if (ast->_state != AST_STATE_UP) {
2722 transmit_response(p, "486 Busy Here", &p->initreq);
2723 ast_set_flag(p, SIP_ALREADYGONE);
2724 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2729 case AST_CONTROL_CONGESTION:
2730 if (ast->_state != AST_STATE_UP) {
2731 transmit_response(p, "503 Service Unavailable", &p->initreq);
2732 ast_set_flag(p, SIP_ALREADYGONE);
2733 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2738 case AST_CONTROL_PROCEEDING:
2739 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2740 transmit_response(p, "100 Trying", &p->initreq);
2745 case AST_CONTROL_PROGRESS:
2746 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2747 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2748 ast_set_flag(p, SIP_PROGRESS_SENT);
2753 case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
2755 ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
2758 case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
2760 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2763 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
2764 if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
2765 transmit_info_with_vidupdate(p);
2774 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2778 ast_mutex_unlock(&p->lock);
2784 /*! \brief sip_new: Initiate a call in the SIP channel */
2785 /* called from sip_request_call (calls from the pbx ) */
2786 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
2788 struct ast_channel *tmp;
2789 struct ast_variable *v = NULL;
2793 char iabuf[INET_ADDRSTRLEN];
2794 char peer[MAXHOSTNAMELEN];
2797 ast_mutex_unlock(&i->lock);
2798 /* Don't hold a sip pvt lock while we allocate a channel */
2799 tmp = ast_channel_alloc(1);
2800 ast_mutex_lock(&i->lock);
2802 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2805 tmp->tech = &sip_tech;
2806 /* Select our native format based on codec preference until we receive
2807 something from another device to the contrary. */
2808 if (i->jointcapability)
2809 what = i->jointcapability;
2810 else if (i->capability)
2811 what = i->capability;
2813 what = global_capability;
2814 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
2815 fmt = ast_best_codec(tmp->nativeformats);
2818 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, thread_safe_rand() & 0xffff);
2819 else if (strchr(i->fromdomain,':'))
2820 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2822 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2824 tmp->type = channeltype;
2825 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2826 i->vad = ast_dsp_new();
2827 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2829 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2832 tmp->fds[0] = ast_rtp_fd(i->rtp);
2833 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2836 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2837 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2839 if (state == AST_STATE_RING)
2841 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2842 tmp->writeformat = fmt;
2843 tmp->rawwriteformat = fmt;
2844 tmp->readformat = fmt;
2845 tmp->rawreadformat = fmt;
2848 tmp->callgroup = i->callgroup;
2849 tmp->pickupgroup = i->pickupgroup;
2850 tmp->cid.cid_pres = i->callingpres;
2851 if (!ast_strlen_zero(i->accountcode))
2852 ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
2854 tmp->amaflags = i->amaflags;
2855 if (!ast_strlen_zero(i->language))
2856 ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
2857 if (!ast_strlen_zero(i->musicclass))
2858 ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
2860 ast_mutex_lock(&usecnt_lock);
2862 ast_mutex_unlock(&usecnt_lock);
2863 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2864 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2865 if (!ast_strlen_zero(i->cid_num))
2866 tmp->cid.cid_num = ast_strdup(i->cid_num);
2867 if (!ast_strlen_zero(i->cid_name))
2868 tmp->cid.cid_name = ast_strdup(i->cid_name);
2869 if (!ast_strlen_zero(i->rdnis))
2870 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
2871 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2872 tmp->cid.cid_dnid = ast_strdup(i->exten);
2874 if (!ast_strlen_zero(i->uri)) {
2875 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2877 if (!ast_strlen_zero(i->domain)) {
2878 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2880 if (!ast_strlen_zero(i->useragent)) {
2881 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2883 if (!ast_strlen_zero(i->callid)) {
2884 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2887 snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
2888 pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
2890 ast_setstate(tmp, state);
2891 if (state != AST_STATE_DOWN) {
2892 if (ast_pbx_start(tmp)) {
2893 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2898 /* Set channel variables for this call from configuration */
2899 for (v = i->chanvars ; v ; v = v->next)
2900 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2905 /*! \brief get_sdp_by_line: Reads one line of SIP message body */
2906 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2908 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2909 return ast_skip_blanks(line + nameLen + 1);
2914 /*! \brief get_sdp: Gets all kind of SIP message bodies, including SDP,
2915 but the name wrongly applies _only_ sdp */
2916 static char *get_sdp(struct sip_request *req, char *name)
2919 int len = strlen(name);
2922 for (x=0; x<req->lines; x++) {
2923 r = get_sdp_by_line(req->line[x], name, len);
2931 static void sdpLineNum_iterator_init(int* iterator)
2936 static char* get_sdp_iterate(int* iterator,
2937 struct sip_request *req, char *name)
2939 int len = strlen(name);
2942 while (*iterator < req->lines) {
2943 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2950 static char *find_alias(const char *name, char *_default)
2953 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2954 if (!strcasecmp(aliases[x].fullname, name))
2955 return aliases[x].shortname;
2959 static char *__get_header(struct sip_request *req, char *name, int *start)
2964 * Technically you can place arbitrary whitespace both before and after the ':' in
2965 * a header, although RFC3261 clearly says you shouldn't before, and place just
2966 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
2967 * a good idea to say you can do it, and if you can do it, why in the hell would.
2968 * you say you shouldn't.
2969 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
2970 * and we always allow spaces after that for compatibility.
2972 for (pass = 0; name && pass < 2;pass++) {
2973 int x, len = strlen(name);
2974 for (x=*start; x<req->headers; x++) {
2975 if (!strncasecmp(req->header[x], name, len)) {
2976 char *r = req->header[x] + len; /* skip name */
2977 if (pedanticsipchecking)
2978 r = ast_skip_blanks(r);
2982 return ast_skip_blanks(r+1);
2986 if (pass == 0) /* Try aliases */
2987 name = find_alias(name, NULL);
2990 /* Don't return NULL, so get_header is always a valid pointer */
2994 /*! \brief get_header: Get header from SIP request */
2995 static char *get_header(struct sip_request *req, char *name)
2998 return __get_header(req, name, &start);
3001 /*! \brief sip_rtp_read: Read RTP from network */
3002 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
3004 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
3005 struct ast_frame *f;
3006 static struct ast_frame null_frame = { AST_FRAME_NULL, };
3009 /* We have no RTP allocated for this channel */
3015 f = ast_rtp_read(p->rtp); /* RTP Audio */
3018 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
3021 f = ast_rtp_read(p->vrtp); /* RTP Video */
3024 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
3029 /* Don't forward RFC2833 if we're not supposed to */
3030 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
3033 /* We already hold the channel lock */
3034 if (f->frametype == AST_FRAME_VOICE) {
3035 if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
3036 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
3037 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
3038 ast_set_read_format(p->owner, p->owner->readformat);
3039 ast_set_write_format(p->owner, p->owner->writeformat);
3041 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
3042 f = ast_dsp_process(p->owner, p->vad, f);
3043 if (f && (f->frametype == AST_FRAME_DTMF))
3044 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
3051 /*! \brief sip_read: Read SIP RTP from channel */
3052 static struct ast_frame *sip_read(struct ast_channel *ast)
3054 struct ast_frame *fr;
3055 struct sip_pvt *p = ast->tech_pvt;
3056 ast_mutex_lock(&p->lock);
3057 fr = sip_rtp_read(ast, p);
3058 time(&p->lastrtprx);
3059 ast_mutex_unlock(&p->lock);
3063 /*! \brief build_callid_pvt: Build SIP Call-ID value for a non-REGISTER transaction */
3064 static void build_callid_pvt(struct sip_pvt *pvt)
3068 char iabuf[INET_ADDRSTRLEN];
3071 val[x] = thread_safe_rand();
3073 if (ast_strlen_zero(pvt->fromdomain))
3074 /* It's not important that we really use our right IP here... */
3075 ast_string_field_build(pvt, callid, "%08x%08x%08x%08x@%s",
3076 val[0], val[1], val[2], val[3],
3077 ast_inet_ntoa(iabuf, sizeof(iabuf), pvt->ourip));
3079 ast_string_field_build(pvt, callid, "%08x%08x%08x%08x@%s",
3080 val[0], val[1], val[2], val[3],
3084 /*! \brief build_callid_registry: Build SIP Call-ID value for a REGISTER transaction */
3085 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
3089 char iabuf[INET_ADDRSTRLEN];
3092 val[x] = thread_safe_rand();
3094 if (ast_strlen_zero(fromdomain))
3095 /* It's not important that we really use our right IP here... */
3096 ast_string_field_build(reg, callid, "%08x%08x%08x%08x@%s",
3097 val[0], val[1], val[2], val[3],
3098 ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
3100 ast_string_field_build(reg, callid, "%08x%08x%08x%08x@%s",
3101 val[0], val[1], val[2], val[3],
3105 static void make_our_tag(char *tagbuf, size_t len)
3107 snprintf(tagbuf, len, "as%08x", thread_safe_rand());
3110 /*! \brief sip_alloc: Allocate SIP_PVT structure and set defaults */
3111 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
3112 int useglobal_nat, const int intended_method)
3116 if (!(p = ast_calloc(1, sizeof(*p))))
3119 if (ast_string_field_init(p)) {
3124 ast_mutex_init(&p->lock);
3126 p->method = intended_method;
3129 p->subscribed = NONE;
3132 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
3133 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
3136 p->osptimelimit = 0;
3139 memcpy(&p->sa, sin, sizeof(p->sa));
3140 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
3141 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3143 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3146 p->branch = thread_safe_rand();
3147 make_our_tag(p->tag, sizeof(p->tag));
3148 /* Start with 101 instead of 1 */
3151 if (sip_methods[intended_method].need_rtp) {
3152 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3153 if (global_videosupport)
3154 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3155 if (!p->rtp || (global_videosupport && !p->vrtp)) {
3156 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", global_videosupport ? "and video" : "", strerror(errno));
3157 ast_mutex_destroy(&p->lock);
3159 ast_variables_destroy(p->chanvars);
3165 ast_rtp_settos(p->rtp, global_tos);
3167 ast_rtp_settos(p->vrtp, global_tos);
3168 p->rtptimeout = global_rtptimeout;
3169 p->rtpholdtimeout = global_rtpholdtimeout;
3170 p->rtpkeepalive = global_rtpkeepalive;
3173 if (useglobal_nat && sin) {
3174 /* Setup NAT structure according to global settings if we have an address */
3175 ast_copy_flags(p, &global_flags, SIP_NAT);
3176 memcpy(&p->recv, sin, sizeof(p->recv));
3178 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3180 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3183 if (p->method != SIP_REGISTER)
3184 ast_string_field_set(p, fromdomain, default_fromdomain);
3187 build_callid_pvt(p);
3189 ast_string_field_set(p, callid, callid);
3190 ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
3191 /* Assign default music on hold class */
3192 ast_string_field_set(p, musicclass, default_musicclass);
3193 p->capability = global_capability;
3194 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
3195 p->noncodeccapability |= AST_RTP_DTMF;
3196 ast_string_field_set(p, context, default_context);
3198 /* Add to active dialog list */
3199 ast_mutex_lock(&iflock);
3202 ast_mutex_unlock(&iflock);
3204 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
3208 /*! \brief find_call: Connect incoming SIP message to current dialog or create new dialog structure */
3209 /* Called by handle_request, sipsock_read */
3210 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
3218 callid = get_header(req, "Call-ID");
3220 if (pedanticsipchecking) {
3221 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
3222 we need more to identify a branch - so we have to check branch, from
3223 and to tags to identify a call leg.
3224 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
3227 if (gettag(req, "To", totag, sizeof(totag)))
3228 ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
3229 gettag(req, "From", fromtag, sizeof(fromtag));
3231 if (req->method == SIP_RESPONSE)
3237 if (option_debug > 4 )
3238 ast_log(LOG_DEBUG, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
3241 ast_mutex_lock(&iflock);
3243 while(p) { /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
3245 if (req->method == SIP_REGISTER)
3246 found = (!strcmp(p->callid, callid));
3248 found = (!strcmp(p->callid, callid) &&
3249 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
3251 if (option_debug > 4)
3252 ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
3254 /* If we get a new request within an existing to-tag - check the to tag as well */
3255 if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */
3256 if (p->tag[0] == '\0' && totag[0]) {
3257 /* We have no to tag, but they have. Wrong dialog */
3259 } else if (totag[0]) { /* Both have tags, compare them */
3260 if (strcmp(totag, p->tag)) {
3261 found = 0; /* This is not our packet */
3264 if (!found && option_debug > 4)
3265 ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
3270 /* Found the call */
3271 ast_mutex_lock(&p->lock);
3272 ast_mutex_unlock(&iflock);
3277 ast_mutex_unlock(&iflock);
3278 p = sip_alloc(callid, sin, 1, intended_method);
3280 ast_mutex_lock(&p->lock);
3284 /*! \brief sip_register: Parse register=> line in sip.conf and add to registry */
3285 static int sip_register(char *value, int lineno)
3287 struct sip_registry *reg;
3289 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
3296 ast_copy_string(copy, value, sizeof(copy));
3299 hostname = strrchr(stringp, '@');
3304 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
3305 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
3309 username = strsep(&stringp, ":");
3311 secret = strsep(&stringp, ":");
3313 authuser = strsep(&stringp, ":");
3316 hostname = strsep(&stringp, "/");
3318 contact = strsep(&stringp, "/");
3319 if (ast_strlen_zero(contact))
3322 hostname = strsep(&stringp, ":");
3323 porta = strsep(&stringp, ":");
3325 if (porta && !atoi(porta)) {
3326 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3329 if (!(reg = ast_calloc(1, sizeof(*reg))))
3332 if (ast_string_field_init(reg)) {
3333 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
3340 ast_string_field_set(reg, contact, contact);
3342 ast_string_field_set(reg, username, username);
3344 ast_string_field_set(reg, hostname, hostname);
3346 ast_string_field_set(reg, authuser, authuser);
3348 ast_string_field_set(reg, secret, secret);
3351 reg->refresh = default_expiry;
3352 reg->portno = porta ? atoi(porta) : 0;
3353 reg->callid_valid = 0;
3355 ASTOBJ_CONTAINER_LINK(®l, reg);
3356 ASTOBJ_UNREF(reg,sip_registry_destroy);
3360 /*! \brief lws2sws: Parse multiline SIP headers into one header */
3361 /* This is enabled if pedanticsipchecking is enabled */
3362 static int lws2sws(char *msgbuf, int len)
3368 /* Eliminate all CRs */
3369 if (msgbuf[h] == '\r') {
3373 /* Check for end-of-line */
3374 if (msgbuf[h] == '\n') {
3375 /* Check for end-of-message */
3378 /* Check for a continuation line */
3379 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
3380 /* Merge continuation line */
3384 /* Propagate LF and start new line */
3385 msgbuf[t++] = msgbuf[h++];
3389 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
3394 msgbuf[t++] = msgbuf[h++];
3398 msgbuf[t++] = msgbuf[h++];
3406 /*! \brief parse_request: Parse a SIP message */
3407 static void parse_request(struct sip_request *req)
3409 /* Divide fields by NULL's */
3415 /* First header starts immediately */
3419 /* We've got a new header */
3422 if (sipdebug && option_debug > 3)
3423 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
3424 if (ast_strlen_zero(req->header[f])) {
3425 /* Line by itself means we're now in content */
3429 if (f >= SIP_MAX_HEADERS - 1) {
3430 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
3433 req->header[f] = c + 1;
3434 } else if (*c == '\r') {
3435 /* Ignore but eliminate \r's */
3440 /* Check for last header */
3441 if (!ast_strlen_zero(req->header[f])) {
3442 if (sipdebug && option_debug > 3)
3443 ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
3447 /* Now we process any mime content */
3452 /* We've got a new line */
3454 if (sipdebug && option_debug > 3)
3455 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
3456 if (f >= SIP_MAX_LINES - 1) {
3457 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
3460 req->line[f] = c + 1;
3461 } else if (*c == '\r') {
3462 /* Ignore and eliminate \r's */
3467 /* Check for last line */
3468 if (!ast_strlen_zero(req->line[f]))
3472 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
3473 /* Split up the first line parts */
3474 determine_firstline_parts(req);
3477 /*! \brief process_sdp: Process SIP SDP and activate RTP channels*/
3478 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
3484 char iabuf[INET_ADDRSTRLEN];
3488 int peercapability, peernoncodeccapability;
3489 int vpeercapability=0, vpeernoncodeccapability=0;
3490 struct sockaddr_in sin;
3493 struct ast_hostent ahp;
3495 int destiterator = 0;
3499 int debug=sip_debug_test_pvt(p);