2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
34 * \todo Better support of forking
35 * \todo VIA branch tag transaction checking
36 * \todo Transaction support
38 * \ingroup channel_drivers
40 * \par Overview of the handling of SIP sessions
41 * The SIP channel handles several types of SIP sessions, or dialogs,
42 * not all of them being "telephone calls".
43 * - Incoming calls that will be sent to the PBX core
44 * - Outgoing calls, generated by the PBX
45 * - SIP subscriptions and notifications of states and voicemail messages
46 * - SIP registrations, both inbound and outbound
47 * - SIP peer management (peerpoke, OPTIONS)
50 * In the SIP channel, there's a list of active SIP dialogs, which includes
51 * all of these when they are active. "sip show channels" in the CLI will
52 * show most of these, excluding subscriptions which are shown by
53 * "sip show subscriptions"
55 * \par incoming packets
56 * Incoming packets are received in the monitoring thread, then handled by
57 * sipsock_read(). This function parses the packet and matches an existing
58 * dialog or starts a new SIP dialog.
60 * sipsock_read sends the packet to handle_request(), that parses a bit more.
61 * if it's a response to an outbound request, it's sent to handle_response().
62 * If it is a request, handle_request sends it to one of a list of functions
63 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64 * sipsock_read locks the ast_channel if it exists (an active call) and
65 * unlocks it after we have processed the SIP message.
67 * A new INVITE is sent to handle_request_invite(), that will end up
68 * starting a new channel in the PBX, the new channel after that executing
69 * in a separate channel thread. This is an incoming "call".
70 * When the call is answered, either by a bridged channel or the PBX itself
71 * the sip_answer() function is called.
73 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
77 * Outbound calls are set up by the PBX through the sip_request_call()
78 * function. After that, they are activated by sip_call().
81 * The PBX issues a hangup on both incoming and outgoing calls through
82 * the sip_hangup() function
84 * \par Deprecated stuff
85 * This is deprecated and will be removed after the 1.4 release
86 * - the SIPUSERAGENT dialplan variable
87 * - the ALERT_INFO dialplan variable
93 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
99 #include <sys/socket.h>
100 #include <sys/ioctl.h>
107 #include <sys/signal.h>
108 #include <netinet/in.h>
109 #include <netinet/in_systm.h>
110 #include <arpa/inet.h>
111 #include <netinet/ip.h>
114 #include "asterisk/lock.h"
115 #include "asterisk/channel.h"
116 #include "asterisk/config.h"
117 #include "asterisk/logger.h"
118 #include "asterisk/module.h"
119 #include "asterisk/pbx.h"
120 #include "asterisk/options.h"
121 #include "asterisk/lock.h"
122 #include "asterisk/sched.h"
123 #include "asterisk/io.h"
124 #include "asterisk/rtp.h"
125 #include "asterisk/udptl.h"
126 #include "asterisk/acl.h"
127 #include "asterisk/manager.h"
128 #include "asterisk/callerid.h"
129 #include "asterisk/cli.h"
130 #include "asterisk/app.h"
131 #include "asterisk/musiconhold.h"
132 #include "asterisk/dsp.h"
133 #include "asterisk/features.h"
134 #include "asterisk/acl.h"
135 #include "asterisk/srv.h"
136 #include "asterisk/astdb.h"
137 #include "asterisk/causes.h"
138 #include "asterisk/utils.h"
139 #include "asterisk/file.h"
140 #include "asterisk/astobj.h"
141 #include "asterisk/dnsmgr.h"
142 #include "asterisk/devicestate.h"
143 #include "asterisk/linkedlists.h"
144 #include "asterisk/stringfields.h"
145 #include "asterisk/monitor.h"
146 #include "asterisk/localtime.h"
147 #include "asterisk/abstract_jb.h"
148 #include "asterisk/compiler.h"
158 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
159 #ifndef IPTOS_MINCOST
160 #define IPTOS_MINCOST 0x02
163 /* #define VOCAL_DATA_HACK */
165 #define DEFAULT_DEFAULT_EXPIRY 120
166 #define DEFAULT_MIN_EXPIRY 60
167 #define DEFAULT_MAX_EXPIRY 3600
168 #define DEFAULT_REGISTRATION_TIMEOUT 20
169 #define DEFAULT_MAX_FORWARDS "70"
171 /* guard limit must be larger than guard secs */
172 /* guard min must be < 1000, and should be >= 250 */
173 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
174 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
176 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
177 GUARD_PCT turns out to be lower than this, it
178 will use this time instead.
179 This is in milliseconds. */
180 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
181 below EXPIRY_GUARD_LIMIT */
182 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
184 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
185 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
186 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
187 static int expiry = DEFAULT_EXPIRY;
190 #define MAX(a,b) ((a) > (b) ? (a) : (b))
193 #define CALLERID_UNKNOWN "Unknown"
195 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
196 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
197 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
199 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
200 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
201 #define SIP_TRANS_TIMEOUT 32000 /*!< SIP request timeout (rfc 3261) 64*T1
202 \todo Use known T1 for timeout (peerpoke)
204 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
205 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
207 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
208 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
209 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
211 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
213 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
214 static struct ast_jb_conf default_jbconf =
218 .resync_threshold = -1,
221 static struct ast_jb_conf global_jbconf;
223 static const char config[] = "sip.conf";
224 static const char notify_config[] = "sip_notify.conf";
225 static int usecnt = 0;
231 /*! \brief Authorization scheme for call transfers
232 \note Not a bitfield flag, since there are plans for other modes,
233 like "only allow transfers for authenticated devices" */
235 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
236 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
245 /* Do _NOT_ make any changes to this enum, or the array following it;
246 if you think you are doing the right thing, you are probably
247 not doing the right thing. If you think there are changes
248 needed, get someone else to review them first _before_
249 submitting a patch. If these two lists do not match properly
250 bad things will happen.
254 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
255 If it fails, it's critical and will cause a teardown of the session */
256 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
257 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
260 enum parse_register_result {
261 PARSE_REGISTER_FAILED,
262 PARSE_REGISTER_UPDATE,
263 PARSE_REGISTER_QUERY,
266 enum subscriptiontype {
276 static const struct cfsubscription_types {
277 enum subscriptiontype type;
278 const char * const event;
279 const char * const mediatype;
280 const char * const text;
281 } subscription_types[] = {
282 { NONE, "-", "unknown", "unknown" },
283 /* RFC 4235: SIP Dialog event package */
284 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
285 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
286 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
287 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
288 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
291 /*! \brief SIP Request methods known by Asterisk */
293 SIP_UNKNOWN, /* Unknown response */
294 SIP_RESPONSE, /* Not request, response to outbound request */
300 SIP_PRACK, /* Not supported at all */
305 SIP_UPDATE, /* We can send UPDATE; but not accept it */
308 SIP_PUBLISH, /* Not supported at all */
311 /*! \brief Authentication types - proxy or www authentication
312 \note Endpoints, like Asterisk, should always use WWW authentication to
313 allow multiple authentications in the same call - to the proxy and
321 /*! \brief Authentication result from check_auth* functions */
322 enum check_auth_result {
324 AUTH_CHALLENGE_SENT = 1,
325 AUTH_SECRET_FAILED = -1,
326 AUTH_USERNAME_MISMATCH = -2,
329 AUTH_UNKNOWN_DOMAIN = -5,
332 /*! \brief States for outbound registrations (with register= lines in sip.conf */
333 enum sipregistrystate {
334 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
335 REG_STATE_REGSENT, /*!< Registration request sent */
336 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
337 REG_STATE_REGISTERED, /*!< Registred and done */
338 REG_STATE_REJECTED, /*!< Registration rejected */
339 REG_STATE_TIMEOUT, /*!< Registration timed out */
340 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
341 REG_STATE_FAILED, /*!< Registration failed after several tries */
345 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
346 static const struct cfsip_methods {
348 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
351 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
352 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
353 { SIP_REGISTER, NO_RTP, "REGISTER" },
354 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
355 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
356 { SIP_INVITE, RTP, "INVITE" },
357 { SIP_ACK, NO_RTP, "ACK" },
358 { SIP_PRACK, NO_RTP, "PRACK" },
359 { SIP_BYE, NO_RTP, "BYE" },
360 { SIP_REFER, NO_RTP, "REFER" },
361 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
362 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
363 { SIP_UPDATE, NO_RTP, "UPDATE" },
364 { SIP_INFO, NO_RTP, "INFO" },
365 { SIP_CANCEL, NO_RTP, "CANCEL" },
366 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
369 /*! Define SIP option tags, used in Require: and Supported: headers
370 We need to be aware of these properties in the phones to use
371 the replace: header. We should not do that without knowing
372 that the other end supports it...
373 This is nothing we can configure, we learn by the dialog
374 Supported: header on the REGISTER (peer) or the INVITE
376 We are not using many of these today, but will in the future.
377 This is documented in RFC 3261
380 #define NOT_SUPPORTED 0
382 #define SIP_OPT_REPLACES (1 << 0)
383 #define SIP_OPT_100REL (1 << 1)
384 #define SIP_OPT_TIMER (1 << 2)
385 #define SIP_OPT_EARLY_SESSION (1 << 3)
386 #define SIP_OPT_JOIN (1 << 4)
387 #define SIP_OPT_PATH (1 << 5)
388 #define SIP_OPT_PREF (1 << 6)
389 #define SIP_OPT_PRECONDITION (1 << 7)
390 #define SIP_OPT_PRIVACY (1 << 8)
391 #define SIP_OPT_SDP_ANAT (1 << 9)
392 #define SIP_OPT_SEC_AGREE (1 << 10)
393 #define SIP_OPT_EVENTLIST (1 << 11)
394 #define SIP_OPT_GRUU (1 << 12)
395 #define SIP_OPT_TARGET_DIALOG (1 << 13)
396 #define SIP_OPT_NOREFERSUB (1 << 14)
397 #define SIP_OPT_HISTINFO (1 << 15)
398 #define SIP_OPT_RESPRIORITY (1 << 16)
400 /*! \brief List of well-known SIP options. If we get this in a require,
401 we should check the list and answer accordingly. */
402 static const struct cfsip_options {
403 int id; /*!< Bitmap ID */
404 int supported; /*!< Supported by Asterisk ? */
405 char * const text; /*!< Text id, as in standard */
406 } sip_options[] = { /* XXX used in 3 places */
407 /* RFC3891: Replaces: header for transfer */
408 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
409 /* One version of Polycom firmware has the wrong label */
410 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
411 /* RFC3262: PRACK 100% reliability */
412 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
413 /* RFC4028: SIP Session Timers */
414 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
415 /* RFC3959: SIP Early session support */
416 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
417 /* RFC3911: SIP Join header support */
418 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
419 /* RFC3327: Path support */
420 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
421 /* RFC3840: Callee preferences */
422 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
423 /* RFC3312: Precondition support */
424 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
425 /* RFC3323: Privacy with proxies*/
426 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
427 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
428 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
429 /* RFC3329: Security agreement mechanism */
430 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
431 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
432 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
433 /* GRUU: Globally Routable User Agent URI's */
434 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
435 /* Target-dialog: draft-ietf-sip-target-dialog-03.txt */
436 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
437 /* Disable the REFER subscription, RFC 4488 */
438 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
439 /* ietf-sip-history-info-06.txt */
440 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
441 /* ietf-sip-resource-priority-10.txt */
442 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
446 /*! \brief SIP Methods we support */
447 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
449 /*! \brief SIP Extensions we support */
450 #define SUPPORTED_EXTENSIONS "replaces"
453 /* Default values, set and reset in reload_config before reading configuration */
454 /* These are default values in the source. There are other recommended values in the
455 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
456 yet encouraging new behaviour on new installations
458 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
459 #define DEFAULT_CONTEXT "default"
460 #define DEFAULT_MOHINTERPRET "default"
461 #define DEFAULT_MOHSUGGEST ""
462 #define DEFAULT_VMEXTEN "asterisk"
463 #define DEFAULT_CALLERID "asterisk"
464 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
465 #define DEFAULT_MWITIME 10
466 #define DEFAULT_ALLOWGUEST TRUE
467 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
468 #define DEFAULT_COMPACTHEADERS FALSE
469 #define DEFAULT_TOS_SIP 0 /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
470 #define DEFAULT_TOS_AUDIO 0 /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
471 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
472 #define DEFAULT_ALLOW_EXT_DOM TRUE
473 #define DEFAULT_REALM "asterisk"
474 #define DEFAULT_NOTIFYRINGING TRUE
475 #define DEFAULT_PEDANTIC FALSE
476 #define DEFAULT_AUTOCREATEPEER FALSE
477 #define DEFAULT_QUALIFY FALSE
478 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
479 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
480 #ifndef DEFAULT_USERAGENT
481 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
485 /* Default setttings are used as a channel setting and as a default when
486 configuring devices */
487 static char default_context[AST_MAX_CONTEXT];
488 static char default_subscribecontext[AST_MAX_CONTEXT];
489 static char default_language[MAX_LANGUAGE];
490 static char default_callerid[AST_MAX_EXTENSION];
491 static char default_fromdomain[AST_MAX_EXTENSION];
492 static char default_notifymime[AST_MAX_EXTENSION];
493 static int default_qualify; /*!< Default Qualify= setting */
494 static char default_vmexten[AST_MAX_EXTENSION];
495 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
496 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
497 * a bridged channel on hold */
498 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
499 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
501 /* Global settings only apply to the channel */
502 static int global_rtautoclear;
503 static int global_notifyringing; /*!< Send notifications on ringing */
504 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
505 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
506 static int pedanticsipchecking; /*!< Extra checking ? Default off */
507 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
508 static int global_relaxdtmf; /*!< Relax DTMF */
509 static int global_rtptimeout; /*!< Time out call if no RTP */
510 static int global_rtpholdtimeout;
511 static int global_rtpkeepalive; /*!< Send RTP keepalives */
512 static int global_reg_timeout;
513 static int global_regattempts_max; /*!< Registration attempts before giving up */
514 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
515 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
516 the global setting is in globals_flags[1] */
517 static int global_mwitime; /*!< Time between MWI checks for peers */
518 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
519 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
520 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
521 static int compactheaders; /*!< send compact sip headers */
522 static int recordhistory; /*!< Record SIP history. Off by default */
523 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
524 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
525 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
526 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
527 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
528 static int global_callevents; /*!< Whether we send manager events or not */
529 static int global_t1min; /*!< T1 roundtrip time minimum */
530 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
532 /*! \brief Codecs that we support by default: */
533 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
534 static int noncodeccapability = AST_RTP_DTMF;
536 /* Object counters */
537 static int suserobjs = 0; /*!< Static users */
538 static int ruserobjs = 0; /*!< Realtime users */
539 static int speerobjs = 0; /*!< Statis peers */
540 static int rpeerobjs = 0; /*!< Realtime peers */
541 static int apeerobjs = 0; /*!< Autocreated peer objects */
542 static int regobjs = 0; /*!< Registry objects */
544 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
546 static int global_autoframing = 0;
548 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
549 AST_MUTEX_DEFINE_STATIC(iflock);
551 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
552 when it's doing something critical. */
553 AST_MUTEX_DEFINE_STATIC(netlock);
555 AST_MUTEX_DEFINE_STATIC(monlock);
557 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
559 /*! \brief This is the thread for the monitor which checks for input on the channels
560 which are not currently in use. */
561 static pthread_t monitor_thread = AST_PTHREADT_NULL;
563 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
564 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
566 static struct sched_context *sched; /*!< The scheduling context */
567 static struct io_context *io; /*!< The IO context */
569 #define DEC_CALL_LIMIT 0
570 #define INC_CALL_LIMIT 1
571 #define DEC_CALL_RINGING 2
572 #define INC_CALL_RINGING 3
574 /*! \brief sip_request: The data grabbed from the UDP socket */
576 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
577 char *rlPart2; /*!< The Request URI or Response Status */
578 int len; /*!< Length */
579 int headers; /*!< # of SIP Headers */
580 int method; /*!< Method of this request */
581 int lines; /*!< Body Content */
582 unsigned int flags; /*!< SIP_PKT Flags for this packet */
583 char *header[SIP_MAX_HEADERS];
584 char *line[SIP_MAX_LINES];
585 char data[SIP_MAX_PACKET];
586 unsigned int sdp_start; /*!< the line number where the SDP begins */
587 unsigned int sdp_end; /*!< the line number where the SDP ends */
591 * A sip packet is stored into the data[] buffer, with the header followed
592 * by an empty line and the body of the message.
593 * On outgoing packets, data is accumulated in data[] with len reflecting
594 * the next available byte, headers and lines count the number of lines
595 * in both parts. There are no '\0' in data[0..len-1].
597 * On received packet, the input read from the socket is copied into data[],
598 * len is set and the string is NUL-terminated. Then a parser fills up
599 * the other fields -header[] and line[] to point to the lines of the
600 * message, rlPart1 and rlPart2 parse the first lnie as below:
602 * Requests have in the first line METHOD URI SIP/2.0
603 * rlPart1 = method; rlPart2 = uri;
604 * Responses have in the first line SIP/2.0 code description
605 * rlPart1 = SIP/2.0; rlPart2 = code + description;
609 /*! \brief structure used in transfers */
611 struct ast_channel *chan1; /*!< First channel involved */
612 struct ast_channel *chan2; /*!< Second channel involved */
613 struct sip_request req; /*!< Request that caused the transfer (REFER) */
614 int seqno; /*!< Sequence number */
619 /*! \brief Parameters to the transmit_invite function */
620 struct sip_invite_param {
621 const char *distinctive_ring; /*!< Distinctive ring header */
622 int addsipheaders; /*!< Add extra SIP headers */
623 const char *uri_options; /*!< URI options to add to the URI */
624 const char *vxml_url; /*!< VXML url for Cisco phones */
625 char *auth; /*!< Authentication */
626 char *authheader; /*!< Auth header */
627 enum sip_auth_type auth_type; /*!< Authentication type */
628 const char *replaces; /*!< Replaces header for call transfers */
629 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
632 /*! \brief Structure to save routing information for a SIP session */
634 struct sip_route *next;
638 /*! \brief Modes for SIP domain handling in the PBX */
640 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
641 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
644 /*! \brief Domain data structure.
645 \note In the future, we will connect this to a configuration tree specific
649 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
650 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
651 enum domain_mode mode; /*!< How did we find this domain? */
652 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
655 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
658 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
660 AST_LIST_ENTRY(sip_history) list;
661 char event[0]; /* actually more, depending on needs */
664 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
666 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
668 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
669 char username[256]; /*!< Username */
670 char secret[256]; /*!< Secret */
671 char md5secret[256]; /*!< MD5Secret */
672 struct sip_auth *next; /*!< Next auth structure in list */
675 /*--- Various flags for the flags field in the pvt structure */
676 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
677 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
678 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
679 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
680 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
681 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
682 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
683 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
684 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
685 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
686 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
687 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
688 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
689 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
690 #define SIP_CAN_BYE (1 << 14) /*!< Can we send BYE on this dialog? */
691 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 15) /*!< Do not hangup at first ast_hangup */
692 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
693 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
694 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
695 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
696 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
698 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
699 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
700 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
701 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
702 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
703 /* re-INVITE related settings */
704 #define SIP_REINVITE (7 << 20) /*!< three bits used */
705 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
706 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */
707 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
708 /* "insecure" settings */
709 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */
710 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */
711 /* Sending PROGRESS in-band settings */
712 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */
713 #define SIP_PROG_INBAND_NEVER (0 << 25)
714 #define SIP_PROG_INBAND_NO (1 << 25)
715 #define SIP_PROG_INBAND_YES (2 << 25)
716 #define SIP_FREE_BIT (1 << 27) /*!< Undefined bit - not in use */
717 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */
718 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */
719 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */
720 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */
722 #define SIP_FLAGS_TO_COPY \
723 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
724 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
725 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
727 /*--- a new page of flags (for flags[1] */
729 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
730 #define SIP_PAGE2_RTUPDATE (1 << 1)
731 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
732 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
733 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5)
734 /* Space for addition of other realtime flags in the future */
735 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10)
736 #define SIP_PAGE2_DEBUG (3 << 11)
737 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11)
738 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12)
739 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */
740 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */
741 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15)
742 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */
743 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */
744 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */
745 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */
746 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */
747 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */
748 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support */
749 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support */
750 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */
751 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */
752 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (2 << 24) /*!< 24: Inactive */
753 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 26)
755 #define SIP_PAGE2_FLAGS_TO_COPY \
756 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE)
758 /* SIP packet flags */
759 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
760 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
761 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
762 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
763 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
765 /* T.38 set of flags */
766 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
767 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
768 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
769 /* Rate management */
770 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
771 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
772 /* UDP Error correction */
773 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
774 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
775 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
776 /* T38 Spec version */
777 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
778 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
779 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
780 /* Maximum Fax Rate */
781 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
782 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
783 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
784 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
785 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
786 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
788 /*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
789 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
791 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
792 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
793 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
795 /*! \brief T38 States for a call */
797 T38_DISABLED = 0, /*!< Not enabled */
798 T38_LOCAL_DIRECT, /*!< Offered from local */
799 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
800 T38_PEER_DIRECT, /*!< Offered from peer */
801 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
802 T38_ENABLED /*!< Negotiated (enabled) */
805 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
806 struct t38properties {
807 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
808 int capability; /*!< Our T38 capability */
809 int peercapability; /*!< Peers T38 capability */
810 int jointcapability; /*!< Supported T38 capability at both ends */
811 enum t38state state; /*!< T.38 state */
814 /*! \brief Parameters to know status of transfer */
816 REFER_IDLE, /*!< No REFER is in progress */
817 REFER_SENT, /*!< Sent REFER to transferee */
818 REFER_RECEIVED, /*!< Received REFER from transferer */
819 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
820 REFER_ACCEPTED, /*!< Accepted by transferee */
821 REFER_RINGING, /*!< Target Ringing */
822 REFER_200OK, /*!< Answered by transfer target */
823 REFER_FAILED, /*!< REFER declined - go on */
824 REFER_NOAUTH /*!< We had no auth for REFER */
827 static const struct c_referstatusstring {
828 enum referstatus status;
830 } referstatusstrings[] = {
831 { REFER_IDLE, "<none>" },
832 { REFER_SENT, "Request sent" },
833 { REFER_RECEIVED, "Request received" },
834 { REFER_ACCEPTED, "Accepted" },
835 { REFER_RINGING, "Target ringing" },
836 { REFER_200OK, "Done" },
837 { REFER_FAILED, "Failed" },
838 { REFER_NOAUTH, "Failed - auth failure" }
841 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */
842 /* OEJ: Should be moved to string fields */
844 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
845 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
846 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
847 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
848 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
849 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
850 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
851 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */
852 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */
853 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */
854 struct sip_pvt *refer_call; /*!< Call we are referring */
855 int attendedtransfer; /*!< Attended or blind transfer? */
856 int localtransfer; /*!< Transfer to local domain? */
857 enum referstatus status; /*!< REFER status */
860 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
861 static struct sip_pvt {
862 ast_mutex_t lock; /*!< Dialog private lock */
863 int method; /*!< SIP method that opened this dialog */
864 AST_DECLARE_STRING_FIELDS(
865 AST_STRING_FIELD(callid); /*!< Global CallID */
866 AST_STRING_FIELD(randdata); /*!< Random data */
867 AST_STRING_FIELD(accountcode); /*!< Account code */
868 AST_STRING_FIELD(realm); /*!< Authorization realm */
869 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
870 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
871 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
872 AST_STRING_FIELD(domain); /*!< Authorization domain */
873 AST_STRING_FIELD(from); /*!< The From: header */
874 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
875 AST_STRING_FIELD(exten); /*!< Extension where to start */
876 AST_STRING_FIELD(context); /*!< Context for this call */
877 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
878 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
879 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
880 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
881 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
882 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
883 AST_STRING_FIELD(language); /*!< Default language for this call */
884 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
885 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
886 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
887 AST_STRING_FIELD(theirtag); /*!< Their tag */
888 AST_STRING_FIELD(username); /*!< [user] name */
889 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
890 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
891 AST_STRING_FIELD(uri); /*!< Original requested URI */
892 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
893 AST_STRING_FIELD(peersecret); /*!< Password */
894 AST_STRING_FIELD(peermd5secret);
895 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
896 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
897 AST_STRING_FIELD(via); /*!< Via: header */
898 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
899 AST_STRING_FIELD(our_contact); /*!< Our contact header */
900 AST_STRING_FIELD(rpid); /*!< Our RPID header */
901 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
903 unsigned int ocseq; /*!< Current outgoing seqno */
904 unsigned int icseq; /*!< Current incoming seqno */
905 ast_group_t callgroup; /*!< Call group */
906 ast_group_t pickupgroup; /*!< Pickup group */
907 int lastinvite; /*!< Last Cseq of invite */
908 struct ast_flags flags[2]; /*!< SIP_ flags */
909 int timer_t1; /*!< SIP timer T1, ms rtt */
910 unsigned int sipoptions; /*!< Supported SIP options on the other end */
911 struct ast_codec_pref prefs; /*!< codec prefs */
912 int capability; /*!< Special capability (codec) */
913 int jointcapability; /*!< Supported capability at both ends (codecs ) */
914 int peercapability; /*!< Supported peer capability */
915 int prefcodec; /*!< Preferred codec (outbound only) */
916 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
917 int redircodecs; /*!< Redirect codecs */
918 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
919 struct t38properties t38; /*!< T38 settings */
920 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
921 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
922 int callingpres; /*!< Calling presentation */
923 int authtries; /*!< Times we've tried to authenticate */
924 int expiry; /*!< How long we take to expire */
925 long branch; /*!< The branch identifier of this session */
926 char tag[11]; /*!< Our tag for this session */
927 int sessionid; /*!< SDP Session ID */
928 int sessionversion; /*!< SDP Session Version */
929 struct sockaddr_in sa; /*!< Our peer */
930 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
931 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
932 time_t lastrtprx; /*!< Last RTP received */
933 time_t lastrtptx; /*!< Last RTP sent */
934 int rtptimeout; /*!< RTP timeout time */
935 int rtpholdtimeout; /*!< RTP timeout when on hold */
936 int rtpkeepalive; /*!< Send RTP packets for keepalive */
937 struct sockaddr_in recv; /*!< Received as */
938 struct in_addr ourip; /*!< Our IP */
939 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
940 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
941 int route_persistant; /*!< Is this the "real" route? */
942 struct sip_auth *peerauth; /*!< Realm authentication */
943 int noncecount; /*!< Nonce-count */
944 char lastmsg[256]; /*!< Last Message sent/received */
945 int amaflags; /*!< AMA Flags */
946 int pendinginvite; /*!< Any pending invite ? (seqno of this) */
947 struct sip_request initreq; /*!< Initial request that opened the SIP dialog */
949 int maxtime; /*!< Max time for first response */
950 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
951 int autokillid; /*!< Auto-kill ID (scheduler) */
952 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
953 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
954 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
955 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
956 int laststate; /*!< SUBSCRIBE: Last known extension state */
957 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
959 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
961 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
962 Used in peerpoke, mwi subscriptions */
963 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
964 struct ast_rtp *rtp; /*!< RTP Session */
965 struct ast_rtp *vrtp; /*!< Video RTP session */
966 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
967 struct sip_history_head *history; /*!< History of this SIP dialog */
968 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
969 struct sip_pvt *next; /*!< Next dialog in chain */
970 struct sip_invite_param *options; /*!< Options for INVITE */
974 #define FLAG_RESPONSE (1 << 0)
975 #define FLAG_FATAL (1 << 1)
977 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
979 struct sip_pkt *next; /*!< Next packet in linked list */
980 int retrans; /*!< Retransmission number */
981 int method; /*!< SIP method for this packet */
982 int seqno; /*!< Sequence number */
983 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
984 struct sip_pvt *owner; /*!< Owner AST call */
985 int retransid; /*!< Retransmission ID */
986 int timer_a; /*!< SIP timer A, retransmission timer */
987 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
988 int packetlen; /*!< Length of packet */
992 /*! \brief Structure for SIP user data. User's place calls to us */
994 /* Users who can access various contexts */
995 ASTOBJ_COMPONENTS(struct sip_user);
996 char secret[80]; /*!< Password */
997 char md5secret[80]; /*!< Password in md5 */
998 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
999 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1000 char cid_num[80]; /*!< Caller ID num */
1001 char cid_name[80]; /*!< Caller ID name */
1002 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1003 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1004 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1005 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1006 char useragent[256]; /*!< User agent in SIP request */
1007 struct ast_codec_pref prefs; /*!< codec prefs */
1008 ast_group_t callgroup; /*!< Call group */
1009 ast_group_t pickupgroup; /*!< Pickup Group */
1010 unsigned int sipoptions; /*!< Supported SIP options */
1011 struct ast_flags flags[2]; /*!< SIP_ flags */
1012 int amaflags; /*!< AMA flags for billing */
1013 int callingpres; /*!< Calling id presentation */
1014 int capability; /*!< Codec capability */
1015 int inUse; /*!< Number of calls in use */
1016 int call_limit; /*!< Limit of concurrent calls */
1017 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1018 struct ast_ha *ha; /*!< ACL setting */
1019 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1020 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1024 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1025 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1027 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
1028 /*!< peer->name is the unique name of this object */
1029 char secret[80]; /*!< Password */
1030 char md5secret[80]; /*!< Password in MD5 */
1031 struct sip_auth *auth; /*!< Realm authentication list */
1032 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1033 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1034 char username[80]; /*!< Temporary username until registration */
1035 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1036 int amaflags; /*!< AMA Flags (for billing) */
1037 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1038 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1039 char fromuser[80]; /*!< From: user when calling this peer */
1040 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1041 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1042 char cid_num[80]; /*!< Caller ID num */
1043 char cid_name[80]; /*!< Caller ID name */
1044 int callingpres; /*!< Calling id presentation */
1045 int inUse; /*!< Number of calls in use */
1046 int inRinging; /*!< Number of calls ringing */
1047 int onHold; /*!< Peer has someone on hold */
1048 int call_limit; /*!< Limit of concurrent calls */
1049 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1050 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1051 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1052 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1053 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1054 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1055 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1056 struct ast_codec_pref prefs; /*!< codec prefs */
1058 time_t lastmsgcheck; /*!< Last time we checked for MWI */
1059 unsigned int sipoptions; /*!< Supported SIP options */
1060 struct ast_flags flags[2]; /*!< SIP_ flags */
1061 int expire; /*!< When to expire this peer registration */
1062 int capability; /*!< Codec capability */
1063 int rtptimeout; /*!< RTP timeout */
1064 int rtpholdtimeout; /*!< RTP Hold Timeout */
1065 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1066 ast_group_t callgroup; /*!< Call group */
1067 ast_group_t pickupgroup; /*!< Pickup group */
1068 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1069 struct sockaddr_in addr; /*!< IP address of peer */
1070 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1073 struct sip_pvt *call; /*!< Call pointer */
1074 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1075 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1076 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1077 struct timeval ps; /*!< Ping send time */
1079 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1080 struct ast_ha *ha; /*!< Access control list */
1081 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1082 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1089 /*! \brief Registrations with other SIP proxies */
1090 struct sip_registry {
1091 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1092 AST_DECLARE_STRING_FIELDS(
1093 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1094 AST_STRING_FIELD(realm); /*!< Authorization realm */
1095 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1096 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1097 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1098 AST_STRING_FIELD(domain); /*!< Authorization domain */
1099 AST_STRING_FIELD(username); /*!< Who we are registering as */
1100 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1101 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1102 AST_STRING_FIELD(secret); /*!< Password in clear text */
1103 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1104 AST_STRING_FIELD(contact); /*!< Contact extension */
1105 AST_STRING_FIELD(random);
1107 int portno; /*!< Optional port override */
1108 int expire; /*!< Sched ID of expiration */
1109 int regattempts; /*!< Number of attempts (since the last success) */
1110 int timeout; /*!< sched id of sip_reg_timeout */
1111 int refresh; /*!< How often to refresh */
1112 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1113 enum sipregistrystate regstate; /*!< Registration state (see above) */
1114 time_t regtime; /*!< Last succesful registration time */
1115 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1116 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1117 struct sockaddr_in us; /*!< Who the server thinks we are */
1118 int noncecount; /*!< Nonce-count */
1119 char lastmsg[256]; /*!< Last Message sent/received */
1122 /* --- Linked lists of various objects --------*/
1124 /*! \brief The user list: Users and friends */
1125 static struct ast_user_list {
1126 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1129 /*! \brief The peer list: Peers and Friends */
1130 static struct ast_peer_list {
1131 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1134 /*! \brief The register list: Other SIP proxys we register with and place calls to */
1135 static struct ast_register_list {
1136 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1140 /*! \todo Move the sip_auth list to AST_LIST */
1141 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
1144 /* --- Sockets and networking --------------*/
1145 static int sipsock = -1; /*!< Main socket for SIP network communication */
1146 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
1147 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1148 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
1149 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1150 static int externrefresh = 10;
1151 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1152 static struct in_addr __ourip;
1153 static struct sockaddr_in outboundproxyip;
1155 static struct sockaddr_in debugaddr;
1157 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1159 /*---------------------------- Forward declarations of functions in chan_sip.c */
1160 /*! \note This is added to help splitting up chan_sip.c into several files
1161 in coming releases */
1163 /*--- PBX interface functions */
1164 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1165 static int sip_devicestate(void *data);
1166 static int sip_sendtext(struct ast_channel *ast, const char *text);
1167 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1168 static int sip_hangup(struct ast_channel *ast);
1169 static int sip_answer(struct ast_channel *ast);
1170 static struct ast_frame *sip_read(struct ast_channel *ast);
1171 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1172 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1173 static int sip_transfer(struct ast_channel *ast, const char *dest);
1174 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1175 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1176 static int sip_senddigit_end(struct ast_channel *ast, char digit);
1178 /*--- Transmitting responses and requests */
1179 static int sipsock_read(int *id, int fd, short events, void *ignore);
1180 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1181 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1182 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1183 static int retrans_pkt(void *data);
1184 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1185 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1186 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1187 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1188 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1189 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1190 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1191 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1192 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1193 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1194 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1195 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1196 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1197 static int transmit_info_with_digit(struct sip_pvt *p, const char digit);
1198 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1199 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1200 static int transmit_refer(struct sip_pvt *p, const char *dest);
1201 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1202 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1203 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
1204 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1205 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1206 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1207 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1208 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1209 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1210 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1211 static int does_peer_need_mwi(struct sip_peer *peer);
1213 /*--- Dialog management */
1214 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1215 int useglobal_nat, const int intended_method);
1216 static int __sip_autodestruct(void *data);
1217 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1218 static void sip_cancel_destroy(struct sip_pvt *p);
1219 static void sip_destroy(struct sip_pvt *p);
1220 static void __sip_destroy(struct sip_pvt *p, int lockowner);
1221 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset);
1222 static void __sip_pretend_ack(struct sip_pvt *p);
1223 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1224 static int auto_congest(void *nothing);
1225 static int update_call_counter(struct sip_pvt *fup, int event);
1226 static int hangup_sip2cause(int cause);
1227 static const char *hangup_cause2sip(int cause);
1228 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1229 static void free_old_route(struct sip_route *route);
1230 static void list_route(struct sip_route *route);
1231 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1232 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1233 struct sip_request *req, char *uri);
1234 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1235 static void check_pendings(struct sip_pvt *p);
1236 static void *sip_park_thread(void *stuff);
1237 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1238 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1240 /*--- Codec handling / SDP */
1241 static void try_suggested_sip_codec(struct sip_pvt *p);
1242 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1243 static const char *get_sdp(struct sip_request *req, const char *name);
1244 static int find_sdp(struct sip_request *req);
1245 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1246 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1247 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1249 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1250 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1252 static int add_sdp(struct sip_request *resp, struct sip_pvt *p);
1254 /*--- Authentication stuff */
1255 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1256 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1257 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1258 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1259 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
1260 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
1261 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1262 const char *secret, const char *md5secret, int sipmethod,
1263 char *uri, enum xmittype reliable, int ignore);
1264 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1265 int sipmethod, char *uri, enum xmittype reliable,
1266 struct sockaddr_in *sin, struct sip_peer **authpeer);
1267 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1268 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1269 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len);
1271 /*--- Domain handling */
1272 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1273 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1274 static void clear_sip_domains(void);
1276 /*--- SIP realm authentication */
1277 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1278 static int clear_realm_authentication(struct sip_auth *authlist);
1279 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1281 /*--- Misc functions */
1282 static int sip_do_reload(enum channelreloadreason reason);
1283 static int reload_config(enum channelreloadreason reason);
1284 static int expire_register(void *data);
1285 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1286 static void *do_monitor(void *data);
1287 static int restart_monitor(void);
1288 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1289 static void sip_destroy(struct sip_pvt *p);
1290 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */
1291 static int sip_refer_allocate(struct sip_pvt *p);
1292 static void ast_quiet_chan(struct ast_channel *chan);
1293 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1295 /*--- Device monitoring and Device/extension state handling */
1296 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1297 static int sip_devicestate(void *data);
1298 static int sip_poke_noanswer(void *data);
1299 static int sip_poke_peer(struct sip_peer *peer);
1300 static void sip_poke_all_peers(void);
1301 static void sip_peer_hold(struct sip_pvt *p, int hold);
1303 /*--- Applications, functions, CLI and manager command helpers */
1304 static const char *sip_nat_mode(const struct sip_pvt *p);
1305 static int sip_show_inuse(int fd, int argc, char *argv[]);
1306 static char *transfermode2str(enum transfermodes mode) attribute_const;
1307 static char *nat2str(int nat) attribute_const;
1308 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1309 static int sip_show_users(int fd, int argc, char *argv[]);
1310 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
1311 static int manager_sip_show_peers( struct mansession *s, struct message *m );
1312 static int sip_show_peers(int fd, int argc, char *argv[]);
1313 static int sip_show_objects(int fd, int argc, char *argv[]);
1314 static void print_group(int fd, unsigned int group, int crlf);
1315 static const char *dtmfmode2str(int mode) attribute_const;
1316 static const char *insecure2str(int port, int invite) attribute_const;
1317 static void cleanup_stale_contexts(char *new, char *old);
1318 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1319 static const char *domain_mode_to_text(const enum domain_mode mode);
1320 static int sip_show_domains(int fd, int argc, char *argv[]);
1321 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1322 static int manager_sip_show_peer( struct mansession *s, struct message *m);
1323 static int sip_show_peer(int fd, int argc, char *argv[]);
1324 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1325 static int sip_show_user(int fd, int argc, char *argv[]);
1326 static int sip_show_registry(int fd, int argc, char *argv[]);
1327 static int sip_show_settings(int fd, int argc, char *argv[]);
1328 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1329 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1330 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1331 static int sip_show_channels(int fd, int argc, char *argv[]);
1332 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1333 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1334 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1335 static char *complete_sip_peer(const char *word, int state, int flags2);
1336 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1337 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1338 static char *complete_sip_user(const char *word, int state, int flags2);
1339 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1340 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1341 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1342 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1343 static int sip_show_channel(int fd, int argc, char *argv[]);
1344 static int sip_show_history(int fd, int argc, char *argv[]);
1345 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1346 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1347 static int sip_do_debug(int fd, int argc, char *argv[]);
1348 static int sip_no_debug(int fd, int argc, char *argv[]);
1349 static int sip_notify(int fd, int argc, char *argv[]);
1350 static int sip_do_history(int fd, int argc, char *argv[]);
1351 static int sip_no_history(int fd, int argc, char *argv[]);
1352 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1353 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1354 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1355 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1356 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1357 static int sip_addheader(struct ast_channel *chan, void *data);
1358 static int sip_do_reload(enum channelreloadreason reason);
1359 static int sip_reload(int fd, int argc, char *argv[]);
1362 Functions for enabling debug per IP or fully, or enabling history logging for
1365 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1366 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1367 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1368 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1369 static void sip_dump_history(struct sip_pvt *dialog);
1371 /*--- Device object handling */
1372 static struct sip_peer *temp_peer(const char *name);
1373 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1374 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1375 static int update_call_counter(struct sip_pvt *fup, int event);
1376 static void sip_destroy_peer(struct sip_peer *peer);
1377 static void sip_destroy_user(struct sip_user *user);
1378 static int sip_poke_peer(struct sip_peer *peer);
1379 static void set_peer_defaults(struct sip_peer *peer);
1380 static struct sip_peer *temp_peer(const char *name);
1381 static void register_peer_exten(struct sip_peer *peer, int onoff);
1382 static void sip_destroy_peer(struct sip_peer *peer);
1383 static void sip_destroy_user(struct sip_user *user);
1384 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1385 static struct sip_user *find_user(const char *name, int realtime);
1386 static int sip_poke_peer_s(void *data);
1387 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1388 static int expire_register(void *data);
1389 static void reg_source_db(struct sip_peer *peer);
1390 static void destroy_association(struct sip_peer *peer);
1391 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1393 /* Realtime device support */
1394 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1395 static struct sip_user *realtime_user(const char *username);
1396 static void update_peer(struct sip_peer *p, int expiry);
1397 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1398 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1400 /*--- Internal UA client handling (outbound registrations) */
1401 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1402 static void sip_registry_destroy(struct sip_registry *reg);
1403 static int sip_register(char *value, int lineno);
1404 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1405 static int sip_reregister(void *data);
1406 static int __sip_do_register(struct sip_registry *r);
1407 static int sip_reg_timeout(void *data);
1408 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader);
1409 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1410 static void sip_send_all_registers(void);
1412 /*--- Parsing SIP requests and responses */
1413 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1414 static int determine_firstline_parts(struct sip_request *req);
1415 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1416 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1417 static int find_sip_method(const char *msg);
1418 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1419 static void parse_request(struct sip_request *req);
1420 static const char *get_header(const struct sip_request *req, const char *name);
1421 static char *referstatus2str(enum referstatus rstatus) attribute_pure;
1422 static int method_match(enum sipmethod id, const char *name);
1423 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1424 static char *get_in_brackets(char *tmp);
1425 static const char *find_alias(const char *name, const char *_default);
1426 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1427 static const char *get_header(const struct sip_request *req, const char *name);
1428 static int lws2sws(char *msgbuf, int len);
1429 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1430 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1431 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1432 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1433 static int set_address_from_contact(struct sip_pvt *pvt);
1434 static void check_via(struct sip_pvt *p, struct sip_request *req);
1435 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1436 static int get_rpid_num(const char *input, char *output, int maxlen);
1437 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1438 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1439 static int get_msg_text(char *buf, int len, struct sip_request *req);
1440 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1441 static void free_old_route(struct sip_route *route);
1443 /*--- Constructing requests and responses */
1444 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1445 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1446 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1447 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1448 static int init_resp(struct sip_request *resp, const char *msg);
1449 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1450 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1451 static void build_via(struct sip_pvt *p);
1452 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1453 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1454 static char *generate_random_string(char *buf, size_t size);
1455 static void build_callid_pvt(struct sip_pvt *pvt);
1456 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1457 static void make_our_tag(char *tagbuf, size_t len);
1458 static int add_header(struct sip_request *req, const char *var, const char *value);
1459 static int add_header_contentLength(struct sip_request *req, int len);
1460 static int add_line(struct sip_request *req, const char *line);
1461 static int add_text(struct sip_request *req, const char *text);
1462 static int add_digit(struct sip_request *req, char digit);
1463 static int add_vidupdate(struct sip_request *req);
1464 static void add_route(struct sip_request *req, struct sip_route *route);
1465 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1466 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1467 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1468 static void set_destination(struct sip_pvt *p, char *uri);
1469 static void append_date(struct sip_request *req);
1470 static void build_contact(struct sip_pvt *p);
1471 static void build_rpid(struct sip_pvt *p);
1473 /*------Request handling functions */
1474 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1475 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e);
1476 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1477 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1478 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1479 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1480 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1481 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1482 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1483 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1484 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1485 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1486 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1487 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1489 /*------Response handling functions */
1490 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1491 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1492 static int handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req);
1493 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1494 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
1496 /*----- RTP interface functions */
1497 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1498 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1499 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1500 static int sip_get_codec(struct ast_channel *chan);
1501 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1503 /*------ T38 Support --------- */
1504 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1505 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1506 static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
1507 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1508 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1510 /*! \brief Definition of this channel for PBX channel registration */
1511 static const struct ast_channel_tech sip_tech = {
1513 .description = "Session Initiation Protocol (SIP)",
1514 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1515 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1516 .requester = sip_request_call,
1517 .devicestate = sip_devicestate,
1519 .hangup = sip_hangup,
1520 .answer = sip_answer,
1523 .write_video = sip_write,
1524 .indicate = sip_indicate,
1525 .transfer = sip_transfer,
1527 .send_digit_begin = sip_senddigit_begin,
1528 .send_digit_end = sip_senddigit_end,
1529 .bridge = ast_rtp_bridge,
1530 .early_bridge = ast_rtp_early_bridge,
1531 .send_text = sip_sendtext,
1534 /**--- some list management macros. **/
1536 #define UNLINK(element, head, prev) do { \
1538 (prev)->next = (element)->next; \
1540 (head) = (element)->next; \
1543 /*! \brief Interface structure with callbacks used to connect to RTP module */
1544 static struct ast_rtp_protocol sip_rtp = {
1546 get_rtp_info: sip_get_rtp_peer,
1547 get_vrtp_info: sip_get_vrtp_peer,
1548 set_rtp_peer: sip_set_rtp_peer,
1549 get_codec: sip_get_codec,
1552 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1553 static struct ast_udptl_protocol sip_udptl = {
1555 get_udptl_info: sip_get_udptl_peer,
1556 set_udptl_peer: sip_set_udptl_peer,
1559 /*! \brief Convert transfer status to string */
1560 static char *referstatus2str(enum referstatus rstatus)
1562 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1565 for (x = 0; x < i; x++) {
1566 if (referstatusstrings[x].status == rstatus)
1567 return (char *) referstatusstrings[x].text;
1572 /*! \brief Initialize the initital request packet in the pvt structure.
1573 This packet is used for creating replies and future requests in
1575 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1577 if (p->initreq.headers) {
1578 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1580 /* Use this as the basis */
1581 copy_request(&p->initreq, req);
1582 parse_request(&p->initreq);
1583 if (ast_test_flag(req, SIP_PKT_DEBUG))
1584 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1588 /*! \brief returns true if 'name' (with optional trailing whitespace)
1589 * matches the sip method 'id'.
1590 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1591 * a case-insensitive comparison to be more tolerant.
1592 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1594 static int method_match(enum sipmethod id, const char *name)
1596 int len = strlen(sip_methods[id].text);
1597 int l_name = name ? strlen(name) : 0;
1598 /* true if the string is long enough, and ends with whitespace, and matches */
1599 return (l_name >= len && name[len] < 33 &&
1600 !strncasecmp(sip_methods[id].text, name, len));
1603 /*! \brief find_sip_method: Find SIP method from header */
1604 static int find_sip_method(const char *msg)
1608 if (ast_strlen_zero(msg))
1610 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1611 if (method_match(i, msg))
1612 res = sip_methods[i].id;
1617 /*! \brief Parse supported header in incoming packet */
1618 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1621 char *temp = ast_strdupa(supported);
1622 unsigned int profile = 0;
1625 if (ast_strlen_zero(supported) )
1628 if (option_debug > 2 && sipdebug)
1629 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1631 for (next = temp; next; next = sep) {
1633 if ( (sep = strchr(next, ',')) != NULL)
1635 next = ast_skip_blanks(next);
1636 if (option_debug > 2 && sipdebug)
1637 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1638 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1639 if (!strcasecmp(next, sip_options[i].text)) {
1640 profile |= sip_options[i].id;
1642 if (option_debug > 2 && sipdebug)
1643 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1647 if (!found && option_debug > 2 && sipdebug) {
1648 if (!strncasecmp(next, "x-", 2))
1649 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1651 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1656 pvt->sipoptions = profile;
1660 /*! \brief See if we pass debug IP filter */
1661 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1665 if (debugaddr.sin_addr.s_addr) {
1666 if (((ntohs(debugaddr.sin_port) != 0)
1667 && (debugaddr.sin_port != addr->sin_port))
1668 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1674 /*! \brief The real destination address for a write */
1675 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1677 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1680 /*! \brief Display SIP nat mode */
1681 static const char *sip_nat_mode(const struct sip_pvt *p)
1683 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1686 /*! \brief Test PVT for debugging output */
1687 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1691 return sip_debug_test_addr(sip_real_dst(p));
1694 /*! \brief Transmit SIP message */
1695 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1698 const struct sockaddr_in *dst = sip_real_dst(p);
1699 res=sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1702 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
1707 /*! \brief Build a Via header for a request */
1708 static void build_via(struct sip_pvt *p)
1710 /* Work around buggy UNIDEN UIP200 firmware */
1711 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1713 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1714 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1715 ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1718 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1720 * Using the localaddr structure built up with localnet statements in sip.conf
1721 * apply it to their address to see if we need to substitute our
1722 * externip or can get away with our internal bindaddr
1724 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1726 struct sockaddr_in theirs, ours;
1728 /* Get our local information */
1729 ast_ouraddrfor(them, us);
1730 theirs.sin_addr = *them;
1731 ours.sin_addr = *us;
1733 if (localaddr && externip.sin_addr.s_addr &&
1734 ast_apply_ha(localaddr, &theirs) &&
1735 !ast_apply_ha(localaddr, &ours)) {
1736 if (externexpire && time(NULL) >= externexpire) {
1737 struct ast_hostent ahp;
1740 externexpire = time(NULL) + externrefresh;
1741 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1742 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1744 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1746 *us = externip.sin_addr;
1748 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n",
1749 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1751 } else if (bindaddr.sin_addr.s_addr)
1752 *us = bindaddr.sin_addr;
1756 /*! \brief Append to SIP dialog history
1757 \return Always returns 0 */
1758 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1760 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1761 __attribute__ ((format (printf, 2, 3)));
1763 /*! \brief Append to SIP dialog history with arg list */
1764 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1766 char buf[80], *c = buf; /* max history length */
1767 struct sip_history *hist;
1770 vsnprintf(buf, sizeof(buf), fmt, ap);
1771 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1772 l = strlen(buf) + 1;
1773 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1775 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1779 memcpy(hist->event, buf, l);
1780 AST_LIST_INSERT_TAIL(p->history, hist, list);
1783 /*! \brief Append to SIP dialog history with arg list */
1784 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1788 if (!recordhistory || !p)
1791 append_history_va(p, fmt, ap);
1797 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1798 static int retrans_pkt(void *data)
1800 struct sip_pkt *pkt = data, *prev, *cur = NULL;
1801 int reschedule = DEFAULT_RETRANS;
1803 /* Lock channel PVT */
1804 ast_mutex_lock(&pkt->owner->lock);
1806 if (pkt->retrans < MAX_RETRANS) {
1808 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1809 if (sipdebug && option_debug > 3)
1810 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);
1814 if (sipdebug && option_debug > 3)
1815 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1819 pkt->timer_a = 2 * pkt->timer_a;
1821 /* For non-invites, a maximum of 4 secs */
1822 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1823 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1826 /* Reschedule re-transmit */
1827 reschedule = siptimer_a;
1828 if (option_debug > 3)
1829 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);
1832 if (sip_debug_test_pvt(pkt->owner)) {
1833 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1834 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1835 pkt->retrans, sip_nat_mode(pkt->owner),
1836 ast_inet_ntoa(dst->sin_addr),
1837 ntohs(dst->sin_port), pkt->data);
1840 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1841 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1842 ast_mutex_unlock(&pkt->owner->lock);
1845 /* Too many retries */
1846 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1847 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1848 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");
1850 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1851 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1853 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1855 pkt->retransid = -1;
1857 if (ast_test_flag(pkt, FLAG_FATAL)) {
1858 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1859 ast_mutex_unlock(&pkt->owner->lock); /* SIP_PVT, not channel */
1861 ast_mutex_lock(&pkt->owner->lock);
1863 if (pkt->owner->owner) {
1864 ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1865 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1866 ast_queue_hangup(pkt->owner->owner);
1867 ast_channel_unlock(pkt->owner->owner);
1869 /* If no channel owner, destroy now */
1870 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1873 /* In any case, go ahead and remove the packet */
1874 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1880 prev->next = cur->next;
1882 pkt->owner->packets = cur->next;
1883 ast_mutex_unlock(&pkt->owner->lock);
1887 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1889 ast_mutex_unlock(&pkt->owner->lock);
1893 /*! \brief Transmit packet with retransmits
1894 \return 0 on success, -1 on failure to allocate packet
1896 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1898 struct sip_pkt *pkt;
1899 int siptimer_a = DEFAULT_RETRANS;
1901 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1903 memcpy(pkt->data, data, len);
1904 pkt->method = sipmethod;
1905 pkt->packetlen = len;
1906 pkt->next = p->packets;
1910 pkt->data[len] = '\0';
1911 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1913 ast_set_flag(pkt, FLAG_FATAL);
1915 siptimer_a = pkt->timer_t1 * 2;
1917 /* Schedule retransmission */
1918 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1919 if (option_debug > 3 && sipdebug)
1920 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1921 pkt->next = p->packets;
1924 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1925 if (sipmethod == SIP_INVITE) {
1926 /* Note this is a pending invite */
1927 p->pendinginvite = seqno;
1932 /*! \brief Kill a SIP dialog (called by scheduler) */
1933 static int __sip_autodestruct(void *data)
1935 struct sip_pvt *p = data;
1937 /* If this is a subscription, tell the phone that we got a timeout */
1938 if (p->subscribed) {
1939 p->subscribed = TIMEOUT;
1940 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1941 p->subscribed = NONE;
1942 append_history(p, "Subscribestatus", "timeout");
1943 if (option_debug > 2)
1944 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1945 return 10000; /* Reschedule this destruction so that we know that it's gone */
1948 /* Reset schedule ID */
1952 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
1953 append_history(p, "AutoDestroy", "%s", p->callid);
1955 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1956 ast_queue_hangup(p->owner);
1957 } else if (p->refer) {
1958 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
1965 /*! \brief Schedule destruction of SIP dialog */
1966 static void sip_scheddestroy(struct sip_pvt *p, int ms)
1969 if (p->timer_t1 == 0)
1970 p->timer_t1 = 500; /* Set timer T1 if not set (RFC 3261) */
1971 ms = p->timer_t1 * 64;
1973 if (sip_debug_test_pvt(p))
1974 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1976 append_history(p, "SchedDestroy", "%d ms", ms);
1978 if (p->autokillid > -1)
1979 ast_sched_del(sched, p->autokillid);
1980 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1983 /*! \brief Cancel destruction of SIP dialog */
1984 static void sip_cancel_destroy(struct sip_pvt *p)
1986 if (p->autokillid > -1) {
1987 ast_sched_del(sched, p->autokillid);
1988 append_history(p, "CancelDestroy", "");
1993 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1994 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
1996 struct sip_pkt *cur, *prev = NULL;
1998 /* Just in case... */
2002 msg = sip_methods[sipmethod].text;
2004 ast_mutex_lock(&p->lock);
2005 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2006 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
2007 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
2008 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
2009 if (!resp && (seqno == p->pendinginvite)) {
2010 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2011 p->pendinginvite = 0;
2013 /* this is our baby */
2015 UNLINK(cur, p->packets, prev);
2016 if (cur->retransid > -1) {
2017 if (sipdebug && option_debug > 3)
2018 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2019 ast_sched_del(sched, cur->retransid);
2026 ast_mutex_unlock(&p->lock);
2028 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2031 /*! \brief Pretend to ack all packets
2032 * maybe the lock on p is not strictly necessary but there might be a race */
2033 static void __sip_pretend_ack(struct sip_pvt *p)
2035 struct sip_pkt *cur = NULL;
2037 while (p->packets) {
2039 if (cur == p->packets) {
2040 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2044 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2045 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method, FALSE);
2049 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2050 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2052 struct sip_pkt *cur;
2055 for (cur = p->packets; cur; cur = cur->next) {
2056 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2057 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2058 /* this is our baby */
2059 if (cur->retransid > -1) {
2060 if (option_debug > 3 && sipdebug)
2061 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2062 ast_sched_del(sched, cur->retransid);
2064 cur->retransid = -1;
2070 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");
2075 /*! \brief Copy SIP request, parse it */
2076 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2078 memset(dst, 0, sizeof(*dst));
2079 memcpy(dst->data, src->data, sizeof(dst->data));
2080 dst->len = src->len;
2084 /*! \brief add a blank line if no body */
2085 static void add_blank(struct sip_request *req)
2088 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2089 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2090 req->len += strlen(req->data + req->len);
2094 /*! \brief Transmit response on SIP request*/
2095 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2100 if (sip_debug_test_pvt(p)) {
2101 const struct sockaddr_in *dst = sip_real_dst(p);
2103 ast_verbose("%sTransmitting (%s) to %s:%d:\n%s\n---\n",
2104 reliable ? "Reliably " : "", sip_nat_mode(p),
2105 ast_inet_ntoa(dst->sin_addr),
2106 ntohs(dst->sin_port), req->data);
2108 if (recordhistory) {
2109 struct sip_request tmp;
2110 parse_copy(&tmp, req);
2111 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
2112 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2115 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2116 __sip_xmit(p, req->data, req->len);
2122 /*! \brief Send SIP Request to the other part of the dialogue */
2123 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2128 if (sip_debug_test_pvt(p)) {
2129 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2130 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
2132 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
2134 if (recordhistory) {
2135 struct sip_request tmp;
2136 parse_copy(&tmp, req);
2137 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2140 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2141 __sip_xmit(p, req->data, req->len);
2145 /*! \brief Pick out text in brackets from character string
2146 \return pointer to terminated stripped string
2147 \param tmp input string that will be modified */
2148 static char *get_in_brackets(char *tmp)
2152 char *first_bracket;
2153 char *second_bracket;
2158 first_quote = strchr(parse, '"');
2159 first_bracket = strchr(parse, '<');
2160 if (first_quote && first_bracket && (first_quote < first_bracket)) {
2162 for (parse = first_quote + 1; *parse; parse++) {
2163 if ((*parse == '"') && (last_char != '\\'))
2168 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2174 if (first_bracket) {
2175 second_bracket = strchr(first_bracket + 1, '>');
2176 if (second_bracket) {
2177 *second_bracket = '\0';
2178 return first_bracket + 1;
2180 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2188 /*! \brief Send SIP MESSAGE text within a call
2189 Called from PBX core sendtext() application */
2190 static int sip_sendtext(struct ast_channel *ast, const char *text)
2192 struct sip_pvt *p = ast->tech_pvt;
2193 int debug = sip_debug_test_pvt(p);
2196 ast_verbose("Sending text %s on %s\n", text, ast->name);
2199 if (ast_strlen_zero(text))
2202 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2203 transmit_message_with_text(p, text);
2207 /*! \brief Update peer object in realtime storage
2208 If the Asterisk system name is set in asterisk.conf, we will use
2209 that name and store that in the "regserver" field in the sippeers
2210 table to facilitate multi-server setups.
2212 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2215 char ipaddr[INET_ADDRSTRLEN];
2216 char regseconds[20];
2218 char *sysname = ast_config_AST_SYSTEM_NAME;
2219 char *syslabel = NULL;
2221 time_t nowtime = time(NULL) + expirey;
2222 const char *fc = fullcontact ? "fullcontact" : NULL;
2224 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
2225 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2226 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2228 if (ast_strlen_zero(sysname)) /* No system name, disable this */
2230 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2231 syslabel = "regserver";
2234 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2235 "port", port, "regseconds", regseconds,
2236 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2238 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2239 "port", port, "regseconds", regseconds,
2240 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2243 /*! \brief Automatically add peer extension to dial plan */
2244 static void register_peer_exten(struct sip_peer *peer, int onoff)
2247 char *stringp, *ext, *context;
2249 /* XXX note that global_regcontext is both a global 'enable' flag and
2250 * the name of the global regexten context, if not specified
2253 if (ast_strlen_zero(global_regcontext))
2256 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2258 while ((ext = strsep(&stringp, "&"))) {
2259 if ((context = strchr(ext, '@'))) {
2260 *context++ = '\0'; /* split ext@context */
2261 if (!ast_context_find(context)) {
2262 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2266 context = global_regcontext;
2269 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2270 ast_strdup(peer->name), ast_free, "SIP");
2272 ast_context_remove_extension(context, ext, 1, NULL);
2276 /*! \brief Destroy peer object from memory */
2277 static void sip_destroy_peer(struct sip_peer *peer)
2279 if (option_debug > 2)
2280 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2282 /* Delete it, it needs to disappear */
2284 sip_destroy(peer->call);
2286 if (peer->mwipvt) /* We have an active subscription, delete it */
2287 sip_destroy(peer->mwipvt);
2289 if (peer->chanvars) {
2290 ast_variables_destroy(peer->chanvars);
2291 peer->chanvars = NULL;
2293 if (peer->expire > -1)
2294 ast_sched_del(sched, peer->expire);
2295 if (peer->pokeexpire > -1)
2296 ast_sched_del(sched, peer->pokeexpire);
2297 register_peer_exten(peer, FALSE);
2298 ast_free_ha(peer->ha);
2299 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2301 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
2305 clear_realm_authentication(peer->auth);
2308 ast_dnsmgr_release(peer->dnsmgr);
2312 /*! \brief Update peer data in database (if used) */
2313 static void update_peer(struct sip_peer *p, int expiry)
2315 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2316 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2317 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2318 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2323 /*! \brief realtime_peer: Get peer from realtime storage
2324 * Checks the "sippeers" realtime family from extconfig.conf
2325 * \todo Consider adding check of port address when matching here to follow the same
2326 * algorithm as for static peers. Will we break anything by adding that?
2328 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2330 struct sip_peer *peer;
2331 struct ast_variable *var = NULL;
2332 struct ast_variable *tmp;
2333 char ipaddr[INET_ADDRSTRLEN];
2335 /* First check on peer name */
2337 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2338 else if (sin) { /* Then check on IP address for dynamic peers */
2339 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2340 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */
2342 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */
2348 for (tmp = var; tmp; tmp = tmp->next) {
2349 /* If this is type=user, then skip this object. */
2350 if (!strcasecmp(tmp->name, "type") &&
2351 !strcasecmp(tmp->value, "user")) {
2352 ast_variables_destroy(var);
2354 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2355 newpeername = tmp->value;
2359 if (!newpeername) { /* Did not find peer in realtime */
2360 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2361 ast_variables_destroy(var);
2365 /* Peer found in realtime, now build it in memory */
2366 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2368 ast_variables_destroy(var);
2372 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2374 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2375 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2376 if (peer->expire > -1) {
2377 ast_sched_del(sched, peer->expire);
2379 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2381 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2383 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2385 ast_variables_destroy(var);
2390 /*! \brief Support routine for find_peer */
2391 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2393 /* We know name is the first field, so we can cast */
2394 struct sip_peer *p = (struct sip_peer *) name;
2395 return !(!inaddrcmp(&p->addr, sin) ||
2396 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2397 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2400 /*! \brief Locate peer by name or ip address
2401 * This is used on incoming SIP message to find matching peer on ip
2402 or outgoing message to find matching peer on name */
2403 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2405 struct sip_peer *p = NULL;
2408 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2410 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2413 p = realtime_peer(peer, sin);
2418 /*! \brief Remove user object from in-memory storage */
2419 static void sip_destroy_user(struct sip_user *user)
2421 if (option_debug > 2)
2422 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2423 ast_free_ha(user->ha);
2424 if (user->chanvars) {
2425 ast_variables_destroy(user->chanvars);
2426 user->chanvars = NULL;
2428 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2435 /*! \brief Load user from realtime storage
2436 * Loads user from "sipusers" category in realtime (extconfig.conf)
2437 * Users are matched on From: user name (the domain in skipped) */
2438 static struct sip_user *realtime_user(const char *username)
2440 struct ast_variable *var;
2441 struct ast_variable *tmp;
2442 struct sip_user *user = NULL;
2444 var = ast_load_realtime("sipusers", "name", username, NULL);
2449 for (tmp = var; tmp; tmp = tmp->next) {
2450 if (!strcasecmp(tmp->name, "type") &&
2451 !strcasecmp(tmp->value, "peer")) {
2452 ast_variables_destroy(var);
2457 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2459 if (!user) { /* No user found */
2460 ast_variables_destroy(var);
2464 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2465 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2467 ASTOBJ_CONTAINER_LINK(&userl,user);
2469 /* Move counter from s to r... */
2472 ast_set_flag(&user->flags[0], SIP_REALTIME);
2474 ast_variables_destroy(var);
2478 /*! \brief Locate user by name
2479 * Locates user by name (From: sip uri user name part) first
2480 * from in-memory list (static configuration) then from
2481 * realtime storage (defined in extconfig.conf) */
2482 static struct sip_user *find_user(const char *name, int realtime)
2484 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2486 u = realtime_user(name);
2490 /*! \brief Create address structure from peer reference.
2491 * return -1 on error, 0 on success.
2493 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2497 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2498 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2499 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2500 dialog->recv = dialog->sa;
2504 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2505 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2506 dialog->capability = peer->capability;
2507 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && dialog->vrtp) {
2508 ast_rtp_destroy(dialog->vrtp);
2509 dialog->vrtp = NULL;
2511 dialog->prefs = peer->prefs;
2512 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2513 dialog->t38.capability = global_t38_capability;
2514 if (dialog->udptl) {
2515 if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2516 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2517 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2518 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2519 else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2520 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2521 dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2522 if (option_debug > 1)
2523 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2525 dialog->t38.jointcapability = dialog->t38.capability;
2526 } else if (dialog->udptl) {
2527 ast_udptl_destroy(dialog->udptl);
2528 dialog->udptl = NULL;
2530 natflags = ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
2533 ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", natflags ? "On" : "Off");
2534 ast_rtp_setnat(dialog->rtp, natflags);
2535 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2536 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2540 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", natflags ? "On" : "Off");
2541 ast_rtp_setnat(dialog->vrtp, natflags);
2542 ast_rtp_setdtmf(dialog->vrtp, 0);
2543 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2545 if (dialog->udptl) {
2547 ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
2548 ast_udptl_setnat(dialog->udptl, natflags);
2550 /* Set Frame packetization */
2552 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2553 dialog->autoframing = peer->autoframing;
2555 ast_string_field_set(dialog, peername, peer->username);
2556 ast_string_field_set(dialog, authname, peer->username);
2557 ast_string_field_set(dialog, username, peer->username);
2558 ast_string_field_set(dialog, peersecret, peer->secret);
2559 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2560 ast_string_field_set(dialog, tohost, peer->tohost);
2561 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2562 if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2565 tmpcall = ast_strdupa(dialog->callid);
2566 c = strchr(tmpcall, '@');
2569 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2572 if (ast_strlen_zero(dialog->tohost))
2573 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2574 if (!ast_strlen_zero(peer->fromdomain))
2575 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2576 if (!ast_strlen_zero(peer->fromuser))
2577 ast_string_field_set(dialog, fromuser, peer->fromuser);
2578 dialog->maxtime = peer->maxms;
2579 dialog->callgroup = peer->callgroup;
2580 dialog->pickupgroup = peer->pickupgroup;
2581 dialog->allowtransfer = peer->allowtransfer;
2582 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2583 /* Minimum is settable or default to 100 ms */
2584 if (peer->maxms && peer->lastms)
2585 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2586 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2587 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2588 dialog->noncodeccapability |= AST_RTP_DTMF;
2590 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2591 ast_string_field_set(dialog, context, peer->context);
2592 dialog->rtptimeout = peer->rtptimeout;
2593 dialog->rtpholdtimeout = peer->rtpholdtimeout;
2594 dialog->rtpkeepalive = peer->rtpkeepalive;
2595 if (peer->call_limit)
2596 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2597 dialog->maxcallbitrate = peer->maxcallbitrate;
2602 /*! \brief create address structure from peer name
2603 * Or, if peer not found, find it in the global DNS
2604 * returns TRUE (-1) on failure, FALSE on success */
2605 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2608 struct ast_hostent ahp;
2612 char host[MAXHOSTNAMELEN], *hostn;
2615 ast_copy_string(peer, opeer, sizeof(peer));
2616 port = strchr(peer, ':');
2619 dialog->sa.sin_family = AF_INET;
2620 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2621 p = find_peer(peer, NULL, 1);
2624 int res = create_addr_from_peer(dialog, p);
2625 ASTOBJ_UNREF(p, sip_destroy_peer);
2629 portno = port ? atoi(port) : DEFAULT_SIP_PORT;
2631 char service[MAXHOSTNAMELEN];
2635 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2636 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2642 hp = ast_gethostbyname(hostn, &ahp);
2644 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2647 ast_string_field_set(dialog, tohost, peer);
2648 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2649 dialog->sa.sin_port = htons(portno);
2650 dialog->recv = dialog->sa;
2654 /*! \brief Scheduled congestion on a call */
2655 static int auto_congest(void *nothing)
2657 struct sip_pvt *p = nothing;
2659 ast_mutex_lock(&p->lock);
2662 /* XXX fails on possible deadlock */
2663 if (!ast_channel_trylock(p->owner)) {
2664 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2665 append_history(p, "Cong", "Auto-congesting (timer)");
2666 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2667 ast_channel_unlock(p->owner);
2670 ast_mutex_unlock(&p->lock);
2675 /*! \brief Initiate SIP call from PBX
2676 * used from the dial() application */
2677 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2681 struct varshead *headp;
2682 struct ast_var_t *current;
2683 const char *referer = NULL; /* SIP refererer */
2686 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2687 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2691 /* Check whether there is vxml_url, distinctive ring variables */
2692 headp=&ast->varshead;
2693 AST_LIST_TRAVERSE(headp,current,entries) {
2694 /* Check whether there is a VXML_URL variable */
2695 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2696 p->options->vxml_url = ast_var_value(current);
2697 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2698 p->options->uri_options = ast_var_value(current);
2699 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2700 /* Check whether there is a ALERT_INFO variable */
2701 p->options->distinctive_ring = ast_var_value(current);
2702 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2703 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2704 p->options->addsipheaders = 1;
2705 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2706 /* This is a transfered call */
2707 p->options->transfer = 1;
2708 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2709 /* This is the referer */
2710 referer = ast_var_value(current);
2711 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2712 /* We're replacing a call. */
2713 p->options->replaces = ast_var_value(current);
2714 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2715 p->t38.state = T38_LOCAL_DIRECT;
2717 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2723 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2725 if (p->options->transfer) {
2729 if (sipdebug && option_debug > 2)
2730 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2731 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2733 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2734 ast_string_field_set(p, cid_name, buf);
2737 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2739 res = update_call_counter(p, INC_CALL_RINGING);
2741 p->callingpres = ast->cid.cid_pres;
2742 p->jointcapability = p->capability;
2743 p->t38.jointcapability = p->t38.capability;
2745 ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2746 transmit_invite(p, SIP_INVITE, 1, 2);
2748 /* Initialize auto-congest time */
2749 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2751 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2756 /*! \brief Destroy registry object
2757 Objects created with the register= statement in static configuration */
2758 static void sip_registry_destroy(struct sip_registry *reg)
2761 if (option_debug > 2)
2762 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2765 /* Clear registry before destroying to ensure
2766 we don't get reentered trying to grab the registry lock */
2767 reg->call->registry = NULL;
2768 if (option_debug > 2)
2769 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2770 sip_destroy(reg->call);
2772 if (reg->expire > -1)
2773 ast_sched_del(sched, reg->expire);
2774 if (reg->timeout > -1)
2775 ast_sched_del(sched, reg->timeout);
2776 ast_string_field_free_all(reg);
2782 /*! \brief Execute destruction of SIP dialog structure, release memory */
2783 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2785 struct sip_pvt *cur, *prev = NULL;
2788 if (sip_debug_test_pvt(p) || option_debug > 2)
2789 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2791 /* Remove link from peer to subscription of MWI */
2792 if (p->relatedpeer && p->relatedpeer->mwipvt)
2793 p->relatedpeer->mwipvt = NULL;
2796 sip_dump_history(p);
2801 if (p->stateid > -1)
2802 ast_extension_state_del(p->stateid, NULL);
2804 ast_sched_del(sched, p->initid);
2805 if (p->autokillid > -1)
2806 ast_sched_del(sched, p->autokillid);
2809 ast_rtp_destroy(p->rtp);
2811 ast_rtp_destroy(p->vrtp);
2813 ast_udptl_destroy(p->udptl);
2817 free_old_route(p->route);
2821 if (p->registry->call == p)
2822 p->registry->call = NULL;
2823 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2826 /* Unlink us from the owner if we have one */
2829 ast_channel_lock(p->owner);
2831 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2832 p->owner->tech_pvt = NULL;
2834 ast_channel_unlock(p->owner);
2838 struct sip_history *hist;
2839 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2845 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2847 UNLINK(cur, iflist, prev);
2852 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2856 /* remove all current packets in this dialog */
2857 while((cp = p->packets)) {
2858 p->packets = p->packets->next;
2859 if (cp->retransid > -1)
2860 ast_sched_del(sched, cp->retransid);
2864 ast_variables_destroy(p->chanvars);
2867 ast_mutex_destroy(&p->lock);
2869 ast_string_field_free_all(p);
2874 /*! \brief update_call_counter: Handle call_limit for SIP users
2875 * Setting a call-limit will cause calls above the limit not to be accepted.
2877 * Remember that for a type=friend, there's one limit for the user and
2878 * another for the peer, not a combined call limit.
2879 * This will cause unexpected behaviour in subscriptions, since a "friend"
2880 * is *two* devices in Asterisk, not one.
2882 * Thought: For realtime, we should propably update storage with inuse counter...
2884 * \return 0 if call is ok (no call limit, below treshold)
2885 * -1 on rejection of call
2888 static int update_call_counter(struct sip_pvt *fup, int event)
2891 int *inuse, *call_limit, *inringing = NULL;
2892 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2893 struct sip_user *u = NULL;
2894 struct sip_peer *p = NULL;
2896 if (option_debug > 2)
2897 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2898 /* Test if we need to check call limits, in order to avoid
2899 realtime lookups if we do not need it */
2900 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2903 ast_copy_string(name, fup->username, sizeof(name));
2905 /* Check the list of users */
2906 if (!outgoing) /* Only check users for incoming calls */
2907 u = find_user(name, 1);
2911 call_limit = &u->call_limit;
2914 /* Try to find peer */
2916 p = find_peer(fup->peername, NULL, 1);
2919 call_limit = &p->call_limit;
2920 inringing = &p->inRinging;
2921 ast_copy_string(name, fup->peername, sizeof(name));
2923 if (option_debug > 1)
2924 ast_log(LOG_DEBUG, "%s is not a local device, no call limit\n", name);
2929 /* incoming and outgoing affects the inUse counter */
2930 case DEC_CALL_LIMIT:
2932 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2938 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2942 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
2943 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2946 if (option_debug > 1 || sipdebug) {
2947 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2950 case INC_CALL_RINGING:
2951 case INC_CALL_LIMIT:
2952 if (*call_limit > 0 ) {
2953 if (*inuse >= *call_limit) {
2954 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);
2956 ASTOBJ_UNREF(u, sip_destroy_user);
2958 ASTOBJ_UNREF(p, sip_destroy_peer);
2962 if (inringing && (event == INC_CALL_RINGING)) {
2963 if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2965 ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2970 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2971 if (option_debug > 1 || sipdebug) {
2972 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2975 case DEC_CALL_RINGING:
2977 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
2981 ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
2982 ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
2987 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2990 ast_device_state_changed("SIP/%s", p->name);
2992 ASTOBJ_UNREF(u, sip_destroy_user);
2994 ASTOBJ_UNREF(p, sip_destroy_peer);
2998 /*! \brief Destroy SIP call structure */
2999 static void sip_destroy(struct sip_pvt *p)
3001 ast_mutex_lock(&iflock);
3002 if (option_debug > 2)
3003 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
3004 __sip_destroy(p, 1);
3005 ast_mutex_unlock(&iflock);
3008 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
3009 static int hangup_sip2cause(int cause)
3011 /* Possible values taken from causes.h */
3014 case 401: /* Unauthorized */
3015 return AST_CAUSE_CALL_REJECTED;
3016 case 403: /* Not found */
3017 return AST_CAUSE_CALL_REJECTED;
3018 case 404: /* Not found */
3019 return AST_CAUSE_UNALLOCATED;
3020 case 405: /* Method not allowed */
3021 return AST_CAUSE_INTERWORKING;
3022 case 407: /* Proxy authentication required */
3023 return AST_CAUSE_CALL_REJECTED;
3024 case 408: /* No reaction */
3025 return AST_CAUSE_NO_USER_RESPONSE;
3026 case 409: /* Conflict */
3027 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
3028 case 410: /* Gone */
3029 return AST_CAUSE_UNALLOCATED;
3030 case 411: /* Length required */
3031 return AST_CAUSE_INTERWORKING;
3032 case 413: /* Request entity too large */
3033 return AST_CAUSE_INTERWORKING;
3034 case 414: /* Request URI too large */
3035 return AST_CAUSE_INTERWORKING;
3036 case 415: /* Unsupported media type */
3037 return AST_CAUSE_INTERWORKING;
3038 case 420: /* Bad extension */
3039 return AST_CAUSE_NO_ROUTE_DESTINATION;
3040 case 480: /* No answer */
3041 return AST_CAUSE_NO_ANSWER;
3042 case 481: /* No answer */
3043 return AST_CAUSE_INTERWORKING;
3044 case 482: /* Loop detected */
3045 return AST_CAUSE_INTERWORKING;
3046 case 483: /* Too many hops */
3047 return AST_CAUSE_NO_ANSWER;
3048 case 484: /* Address incomplete */
3049 return AST_CAUSE_INVALID_NUMBER_FORMAT;
3050 case 485: /* Ambigous */
3051 return AST_CAUSE_UNALLOCATED;
3052 case 486: /* Busy everywhere */
3053 return AST_CAUSE_BUSY;
3054 case 487: /* Request terminated */
3055 return AST_CAUSE_INTERWORKING;
3056 case 488: /* No codecs approved */
3057 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3058 case 491: /* Request pending */
3059 return AST_CAUSE_INTERWORKING;
3060 case 493: /* Undecipherable */
3061 return AST_CAUSE_INTERWORKING;
3062 case 500: /* Server internal failure */
3063 return AST_CAUSE_FAILURE;
3064 case 501: /* Call rejected */
3065 return AST_CAUSE_FACILITY_REJECTED;
3067 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3068 case 503: /* Service unavailable */
3069 return AST_CAUSE_CONGESTION;
3070 case 504: /* Gateway timeout */
3071 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3072 case 505: /* SIP version not supported */
3073 return AST_CAUSE_INTERWORKING;
3074 case 600: /* Busy everywhere */
3075 return AST_CAUSE_USER_BUSY;
3076 case 603: /* Decline */
3077 return AST_CAUSE_CALL_REJECTED;
3078 case 604: /* Does not exist anywhere */
3079 return AST_CAUSE_UNALLOCATED;
3080 case 606: /* Not acceptable */
3081 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3083 return AST_CAUSE_NORMAL;
3089 /*! \brief Convert Asterisk hangup causes to SIP codes
3091 Possible values from causes.h
3092 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
3093 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
3095 In addition to these, a lot of PRI codes is defined in causes.h
3096 ...should we take care of them too ?
3100 ISUP Cause value SIP response
3101 ---------------- ------------
3102 1 unallocated number 404 Not Found
3103 2 no route to network 404 Not found
3104 3 no route to destination 404 Not found
3105 16 normal call clearing --- (*)
3106 17 user busy 486 Busy here
3107 18 no user responding 408 Request Timeout
3108 19 no answer from the user 480 Temporarily unavailable
3109 20 subscriber absent 480 Temporarily unavailable
3110 21 call rejected 403 Forbidden (+)
3111 22 number changed (w/o diagnostic) 410 Gone
3112 22 number changed (w/ diagnostic) 301 Moved Permanently
3113 23 redirection to new destination 410 Gone
3114 26 non-selected user clearing 404 Not Found (=)
3115 27 destination out of order 502 Bad Gateway
3116 28 address incomplete 484 Address incomplete
3117 29 facility rejected 501 Not implemented
3118 31 normal unspecified 480 Temporarily unavailable
3121 static const char *hangup_cause2sip(int cause)
3124 case AST_CAUSE_UNALLOCATED: /* 1 */
3125 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
3126 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
3127 return "404 Not Found";
3128 case AST_CAUSE_CONGESTION: /* 34 */
3129 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
3130 return "503 Service Unavailable";
3131 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
3132 return "408 Request Timeout";
3133 case AST_CAUSE_NO_ANSWER: /* 19 */
3134 return "480 Temporarily unavailable";
3135 case AST_CAUSE_CALL_REJECTED: /* 21 */
3136 return "403 Forbidden";
3137 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
3139 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
3140 return "480 Temporarily unavailable";
3141 case AST_CAUSE_INVALID_NUMBER_FORMAT:
3142 return "484 Address incomplete";
3143 case AST_CAUSE_USER_BUSY:
3144 return "486 Busy here";
3145 case AST_CAUSE_FAILURE:
3146 return "500 Server internal failure";
3147 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
3148 return "501 Not Implemented";
3149 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
3150 return "503 Service Unavailable";
3151 /* Used in chan_iax2 */
3152 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
3153 return "502 Bad Gateway";
3154 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
3155 return "488 Not Acceptable Here";
3157 case AST_CAUSE_NOTDEFINED:
3159 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
3168 /*! \brief sip_hangup: Hangup SIP call
3169 * Part of PBX interface, called from ast_hangup */
3170 static int sip_hangup(struct ast_channel *ast)
3172 struct sip_pvt *p = ast->tech_pvt;
3173 int needcancel = FALSE;
3174 int needdestroy = 0;
3175 struct ast_channel *oldowner = ast;
3178 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
3182 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
3183 if (option_debug >3)
3184 ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
3185 if (p->autokillid > -1)
3186 sip_cancel_destroy(p);
3187 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3188 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
3189 ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
3190 p->owner->tech_pvt = NULL;
3191 p->owner = NULL; /* Owner will be gone after we return, so take it away */
3195 if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
3196 ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
3198 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
3200 if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE))
3201 ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");
3203 ast_mutex_lock(&p->lock);
3204 if (option_debug && sipdebug)
3205 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
3206 update_call_counter(p, DEC_CALL_LIMIT);
3208 /* Determine how to disconnect */
3209 if (p->owner != ast) {
3210 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
3211 ast_mutex_unlock(&p->lock);
3214 /* If the call is not UP, we need to send CANCEL instead of BYE */
3215 if (ast->_state == AST_STATE_RING || ast->_state == AST_STATE_RINGING) {
3217 if (option_debug > 3)
3218 ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
3223 ast_dsp_free(p->vad);
3226 ast->tech_pvt = NULL;
3228 ast_atomic_fetchadd_int(&usecnt, -1);
3229 ast_update_use_count();
3231 /* Do not destroy this pvt until we have timeout or
3232 get an answer to the BYE or INVITE/CANCEL
3233 If we get no answer during retransmit period, drop the call anyway.
3234 (Sorry, mother-in-law, you can't deny a hangup by sending
3235 603 declined to BYE...)
3237 if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
3238 needdestroy = 1; /* Set destroy flag at end of this function */
3240 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3242 /* Start the process if it's not already started */
3243 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
3244 if (needcancel) { /* Outgoing call, not up */
3245 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3246 /* stop retransmitting an INVITE that has not received a response */
3247 __sip_pretend_ack(p);
3249 /* if we can't send right now, mark it pending */
3250 if (!ast_test_flag(&p->flags[0], SIP_CAN_BYE)) {
3251 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3252 /* Do we need a timer here if we don't hear from them at all? */
3254 /* Send a new request: CANCEL */
3255 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
3256 /* Actually don't destroy us yet, wait for the 487 on our original
3257 INVITE, but do set an autodestruct just in case we never get it. */
3259 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3261 if ( p->initid != -1 ) {
3262 /* channel still up - reverse dec of inUse counter
3263 only if the channel is not auto-congested */
3264 update_call_counter(p, INC_CALL_LIMIT);
3266 } else { /* Incoming call, not up */
3268 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
3269 transmit_response_reliable(p, res, &p->initreq);
3271 transmit_response_reliable(p, "603 Declined", &p->initreq);
3273 } else { /* Call is in UP state, send BYE */
3274 if (!p->pendinginvite) {
3275 char *audioqos = "";
3276 char *videoqos = "";
3278 audioqos = ast_rtp_get_quality(p->rtp);
3280 videoqos = ast_rtp_get_quality(p->vrtp);
3282 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3284 /* Get RTCP quality before end of call */
3285 if (recordhistory) {
3287 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
3289 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
3291 if (p->rtp && oldowner)
3292 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
3293 if (p->vrtp && oldowner)
3294 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
3296 /* Note we will need a BYE when this all settles out
3297 but we can't send one while we have "INVITE" outstanding. */
3298 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
3299 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
3304 ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
3305 ast_mutex_unlock(&p->lock);
3309 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
3310 static void try_suggested_sip_codec(struct sip_pvt *p)
3315 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
3319 fmt = ast_getformatbyname(codec);
3321 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
3322 if (p->jointcapability & fmt) {
3323 p->jointcapability &= fmt;
3324 p->capability &= fmt;
3326 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
3328 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
3332 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
3333 * Part of PBX interface */
3334 static int sip_answer(struct ast_channel *ast)
3337 struct sip_pvt *p = ast->tech_pvt;
3339 ast_mutex_lock(&p->lock);
3340 if (ast->_state != AST_STATE_UP) {
3341 try_suggested_sip_codec(p);
3343 ast_setstate(ast, AST_STATE_UP);
3345 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
3346 if (p->t38.state == T38_PEER_DIRECT) {
3347 p->t38.state = T38_ENABLED;
3348 if (option_debug > 1)
3349 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
3350 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3352 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
3354 ast_mutex_unlock(&p->lock);
3358 /*! \brief Send frame to media channel (rtp) */
3359 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
3361 struct sip_pvt *p = ast->tech_pvt;
3364 switch (frame->frametype) {
3365 case AST_FRAME_VOICE:
3366 if (!(frame->subclass & ast->nativeformats)) {
3367 char s1[512], s2[512], s3[512];
3368 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
3370 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
3371 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
3372 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
3374 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
3379 ast_mutex_lock(&p->lock);
3381 /* If channel is not up, activate early media session */
3382 if ((ast->_state != AST_STATE_UP) &&
3383 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3384 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3385 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3386 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3388 p->lastrtptx = time(NULL);
3389 res = ast_rtp_write(p->rtp, frame);
3391 ast_mutex_unlock(&p->lock);
3394 case AST_FRAME_VIDEO:
3396 ast_mutex_lock(&p->lock);
3398 /* Activate video early media */
3399 if ((ast->_state != AST_STATE_UP) &&
3400 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3401 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3402 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
3403 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
3405 p->lastrtptx = time(NULL);
3406 res = ast_rtp_write(p->vrtp, frame);
3408 ast_mutex_unlock(&p->lock);
3411 case AST_FRAME_IMAGE:
3414 case AST_FRAME_MODEM:
3416 ast_mutex_lock(&p->lock);
3418 if ((ast->_state != AST_STATE_UP) &&
3419 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
3420 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
3421 transmit_response_with_t38_sdp(p, "183 Session Progress", &p->