2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
34 * \todo Better support of forking
36 * \ingroup channel_drivers
38 * \par Overview of the handling of SIP sessions
39 * The SIP channel handles several types of SIP sessions, or dialogs,
40 * not all of them being "telephone calls".
41 * - Incoming calls that will be sent to the PBX core
42 * - Outgoing calls, generated by the PBX
43 * - SIP subscriptions and notifications of states and voicemail messages
44 * - SIP registrations, both inbound and outbound
45 * - SIP peer management (peerpoke, OPTIONS)
48 * In the SIP channel, there's a list of active SIP dialogs, which includes
49 * all of these when they are active. "sip show channels" in the CLI will
50 * show most of these, excluding subscriptions which are shown by
51 * "sip show subscriptions"
53 * \par incoming packets
54 * Incoming packets are received in the monitoring thread, then handled by
55 * sipsock_read(). This function parses the packet and matches an existing
56 * dialog or starts a new SIP dialog.
58 * sipsock_read sends the packet to handle_request(), that parses a bit more.
59 * if it's a response to an outbound request, it's sent to handle_response().
60 * If it is a request, handle_request sends it to one of a list of functions
61 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
63 * A new INVITE is sent to handle_request_invite(), that will end up
64 * starting a new channel in the PBX, the new channel after that executing
65 * in a separate channel thread. This is an incoming "call".
66 * When the call is answered, either by a bridged channel or the PBX itself
67 * the sip_answer() function is called.
69 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
73 * Outbound calls are set up by the PBX through the sip_request_call()
74 * function. After that, they are activated by sip_call().
77 * The PBX issues a hangup on both incoming and outgoing calls through
78 * the sip_hangup() function
87 #include <sys/socket.h>
88 #include <sys/ioctl.h>
95 #include <sys/signal.h>
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <arpa/inet.h>
99 #include <netinet/ip.h>
102 #include "asterisk.h"
104 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
106 #include "asterisk/lock.h"
107 #include "asterisk/channel.h"
108 #include "asterisk/config.h"
109 #include "asterisk/logger.h"
110 #include "asterisk/module.h"
111 #include "asterisk/pbx.h"
112 #include "asterisk/options.h"
113 #include "asterisk/lock.h"
114 #include "asterisk/sched.h"
115 #include "asterisk/io.h"
116 #include "asterisk/rtp.h"
117 #include "asterisk/acl.h"
118 #include "asterisk/manager.h"
119 #include "asterisk/callerid.h"
120 #include "asterisk/cli.h"
121 #include "asterisk/app.h"
122 #include "asterisk/musiconhold.h"
123 #include "asterisk/dsp.h"
124 #include "asterisk/features.h"
125 #include "asterisk/acl.h"
126 #include "asterisk/srv.h"
127 #include "asterisk/astdb.h"
128 #include "asterisk/causes.h"
129 #include "asterisk/utils.h"
130 #include "asterisk/file.h"
131 #include "asterisk/astobj.h"
132 #include "asterisk/dnsmgr.h"
133 #include "asterisk/devicestate.h"
134 #include "asterisk/linkedlists.h"
135 #include "asterisk/stringfields.h"
136 #include "asterisk/monitor.h"
137 #include "asterisk/localtime.h"
147 #define VIDEO_CODEC_MASK 0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
148 #ifndef IPTOS_MINCOST
149 #define IPTOS_MINCOST 0x02
152 /* #define VOCAL_DATA_HACK */
154 #define DEFAULT_DEFAULT_EXPIRY 120
155 #define DEFAULT_MIN_EXPIRY 60
156 #define DEFAULT_MAX_EXPIRY 3600
157 #define DEFAULT_REGISTRATION_TIMEOUT 20
158 #define DEFAULT_MAX_FORWARDS "70"
160 /* guard limit must be larger than guard secs */
161 /* guard min must be < 1000, and should be >= 250 */
162 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
163 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
165 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
166 GUARD_PCT turns out to be lower than this, it
167 will use this time instead.
168 This is in milliseconds. */
169 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
170 below EXPIRY_GUARD_LIMIT */
171 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
173 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
174 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
175 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
176 static int expiry = DEFAULT_EXPIRY;
179 #define MAX(a,b) ((a) > (b) ? (a) : (b))
182 #define CALLERID_UNKNOWN "Unknown"
184 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
185 #define DEFAULT_FREQ_OK 60 * 1000 /*!< Qualification: How often to check for the host to be up */
186 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
188 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
189 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
190 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
192 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
193 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
194 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
196 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
198 static const char desc[] = "Session Initiation Protocol (SIP)";
199 static const char config[] = "sip.conf";
200 static const char notify_config[] = "sip_notify.conf";
201 static int usecnt = 0;
207 /*! \brief Authorization scheme for call transfers
208 \note Not a bitfield flag, since there are plans for other modes,
209 like "only allow transfers for authenticated devices" */
211 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
212 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
216 /* Do _NOT_ make any changes to this enum, or the array following it;
217 if you think you are doing the right thing, you are probably
218 not doing the right thing. If you think there are changes
219 needed, get someone else to review them first _before_
220 submitting a patch. If these two lists do not match properly
221 bad things will happen.
225 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
226 If it fails, it's critical and will cause a teardown of the session */
227 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
228 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
231 enum subscriptiontype {
241 static const struct cfsubscription_types {
242 enum subscriptiontype type;
243 const char * const event;
244 const char * const mediatype;
245 const char * const text;
246 } subscription_types[] = {
247 { NONE, "-", "unknown", "unknown" },
248 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
249 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
250 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
251 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
252 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
253 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* Mailbox notification */
280 /* States for outbound registrations (with register= lines in sip.conf */
281 enum sipregistrystate {
282 REG_STATE_UNREGISTERED = 0, /*!< We are not registred */
283 REG_STATE_REGSENT, /*!< Registration request sent */
284 REG_STATE_AUTHSENT, /*!< We have tried to authenticate */
285 REG_STATE_REGISTERED, /*!< Registred and done */
286 REG_STATE_REJECTED, /*!< Registration rejected */
287 REG_STATE_TIMEOUT, /*!< Registration timed out */
288 REG_STATE_NOAUTH, /*!< We have no accepted credentials */
289 REG_STATE_FAILED, /*!< Registration failed after several tries */
293 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
294 static const struct cfsip_methods {
296 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
299 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
300 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
301 { SIP_REGISTER, NO_RTP, "REGISTER" },
302 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
303 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
304 { SIP_INVITE, RTP, "INVITE" },
305 { SIP_ACK, NO_RTP, "ACK" },
306 { SIP_PRACK, NO_RTP, "PRACK" },
307 { SIP_BYE, NO_RTP, "BYE" },
308 { SIP_REFER, NO_RTP, "REFER" },
309 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
310 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
311 { SIP_UPDATE, NO_RTP, "UPDATE" },
312 { SIP_INFO, NO_RTP, "INFO" },
313 { SIP_CANCEL, NO_RTP, "CANCEL" },
314 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
317 /*! Define SIP option tags, used in Require: and Supported: headers
318 We need to be aware of these properties in the phones to use
319 the replace: header. We should not do that without knowing
320 that the other end supports it...
321 This is nothing we can configure, we learn by the dialog
322 Supported: header on the REGISTER (peer) or the INVITE
324 We are not using many of these today, but will in the future.
325 This is documented in RFC 3261
328 #define NOT_SUPPORTED 0
330 #define SIP_OPT_REPLACES (1 << 0)
331 #define SIP_OPT_100REL (1 << 1)
332 #define SIP_OPT_TIMER (1 << 2)
333 #define SIP_OPT_EARLY_SESSION (1 << 3)
334 #define SIP_OPT_JOIN (1 << 4)
335 #define SIP_OPT_PATH (1 << 5)
336 #define SIP_OPT_PREF (1 << 6)
337 #define SIP_OPT_PRECONDITION (1 << 7)
338 #define SIP_OPT_PRIVACY (1 << 8)
339 #define SIP_OPT_SDP_ANAT (1 << 9)
340 #define SIP_OPT_SEC_AGREE (1 << 10)
341 #define SIP_OPT_EVENTLIST (1 << 11)
342 #define SIP_OPT_GRUU (1 << 12)
343 #define SIP_OPT_TARGET_DIALOG (1 << 13)
345 /*! \brief List of well-known SIP options. If we get this in a require,
346 we should check the list and answer accordingly. */
347 static const struct cfsip_options {
348 int id; /*!< Bitmap ID */
349 int supported; /*!< Supported by Asterisk ? */
350 char * const text; /*!< Text id, as in standard */
351 } sip_options[] = { /* XXX used in 3 places */
352 /* Replaces: header for transfer */
353 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
354 /* One version of Polycom firmware has the wrong label */
355 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
356 /* RFC3262: PRACK 100% reliability */
357 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
358 /* SIP Session Timers */
359 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
360 /* RFC3959: SIP Early session support */
361 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
362 /* SIP Join header support */
363 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
364 /* RFC3327: Path support */
365 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
366 /* RFC3840: Callee preferences */
367 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
368 /* RFC3312: Precondition support */
369 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
370 /* RFC3323: Privacy with proxies*/
371 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
372 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
373 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
374 /* RFC3329: Security agreement mechanism */
375 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
376 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
377 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
378 /* GRUU: Globally Routable User Agent URI's */
379 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
380 /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
381 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
385 /*! \brief SIP Methods we support */
386 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
388 /*! \brief SIP Extensions we support */
389 #define SUPPORTED_EXTENSIONS "replaces"
392 /* Default values, set and reset in reload_config before reading configuration */
393 /* These are default values in the source. There are other recommended values in the
394 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
395 yet encouraging new behaviour on new installations
397 #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */
398 #define DEFAULT_CONTEXT "default"
399 #define DEFAULT_MUSICCLASS "default"
400 #define DEFAULT_VMEXTEN "asterisk"
401 #define DEFAULT_CALLERID "asterisk"
402 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
403 #define DEFAULT_MWITIME 10
404 #define DEFAULT_ALLOWGUEST TRUE
405 #define DEFAULT_SRVLOOKUP FALSE /*!< Recommended setting is ON */
406 #define DEFAULT_COMPACTHEADERS FALSE
407 #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. */
408 #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. */
409 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
410 #define DEFAULT_ALLOW_EXT_DOM TRUE
411 #define DEFAULT_REALM "asterisk"
412 #define DEFAULT_NOTIFYRINGING TRUE
413 #define DEFAULT_PEDANTIC FALSE
414 #define DEFAULT_AUTOCREATEPEER FALSE
415 #define DEFAULT_QUALIFY FALSE
416 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
417 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
418 #ifndef DEFAULT_USERAGENT
419 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
423 /* Default setttings are used as a channel setting and as a default when
424 configuring devices */
425 static char default_context[AST_MAX_CONTEXT];
426 static char default_subscribecontext[AST_MAX_CONTEXT];
427 static char default_language[MAX_LANGUAGE];
428 static char default_callerid[AST_MAX_EXTENSION];
429 static char default_fromdomain[AST_MAX_EXTENSION];
430 static char default_notifymime[AST_MAX_EXTENSION];
431 static int default_qualify; /*!< Default Qualify= setting */
432 static char default_vmexten[AST_MAX_EXTENSION];
433 static char default_musicclass[MAX_MUSICCLASS]; /*!< Global music on hold class */
434 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
435 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
437 /* Global settings only apply to the channel */
438 static int global_rtautoclear;
439 static int global_notifyringing; /*!< Send notifications on ringing */
440 static int srvlookup; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
441 static int pedanticsipchecking; /*!< Extra checking ? Default off */
442 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
443 static int global_relaxdtmf; /*!< Relax DTMF */
444 static int global_rtptimeout; /*!< Time out call if no RTP */
445 static int global_rtpholdtimeout;
446 static int global_rtpkeepalive; /*!< Send RTP keepalives */
447 static int global_reg_timeout;
448 static int global_regattempts_max; /*!< Registration attempts before giving up */
449 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
450 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
451 the global setting is in globals_flags[1] */
452 static int global_mwitime; /*!< Time between MWI checks for peers */
453 static int global_tos_sip; /*!< IP type of service for SIP packets */
454 static int global_tos_audio; /*!< IP type of service for audio RTP packets */
455 static int global_tos_video; /*!< IP type of service for video RTP packets */
456 static int compactheaders; /*!< send compact sip headers */
457 static int recordhistory; /*!< Record SIP history. Off by default */
458 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
459 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
460 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
461 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
462 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
463 static int global_callevents; /*!< Whether we send manager events or not */
464 static int global_t1min; /*!< T1 roundtrip time minimum */
465 enum transfermodes global_allowtransfer; /*! SIP Refer restriction scheme */
467 /*! \brief Codecs that we support by default: */
468 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
469 static int noncodeccapability = AST_RTP_DTMF;
471 /* Object counters */
472 static int suserobjs = 0; /*!< Static users */
473 static int ruserobjs = 0; /*!< Realtime users */
474 static int speerobjs = 0; /*!< Statis peers */
475 static int rpeerobjs = 0; /*!< Realtime peers */
476 static int apeerobjs = 0; /*!< Autocreated peer objects */
477 static int regobjs = 0; /*!< Registry objects */
479 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
481 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
483 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
484 AST_MUTEX_DEFINE_STATIC(iflock);
486 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
487 when it's doing something critical. */
488 AST_MUTEX_DEFINE_STATIC(netlock);
490 AST_MUTEX_DEFINE_STATIC(monlock);
492 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
494 /*! \brief This is the thread for the monitor which checks for input on the channels
495 which are not currently in use. */
496 static pthread_t monitor_thread = AST_PTHREADT_NULL;
498 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
499 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
501 static struct sched_context *sched; /*!< The scheduling context */
502 static struct io_context *io; /*!< The IO context */
504 #define DEC_CALL_LIMIT 0
505 #define INC_CALL_LIMIT 1
508 /*! \brief sip_request: The data grabbed from the UDP socket */
510 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
511 char *rlPart2; /*!< The Request URI or Response Status */
512 int len; /*!< Length */
513 int headers; /*!< # of SIP Headers */
514 int method; /*!< Method of this request */
515 int lines; /*!< SDP Content */
516 unsigned int flags; /*!< SIP_PKT Flags for this packet */
517 char *header[SIP_MAX_HEADERS];
518 char *line[SIP_MAX_LINES];
519 char data[SIP_MAX_PACKET];
523 * A sip packet is stored into the data[] buffer, with the header followed
524 * by an empty line and the body of the message.
525 * On outgoing packets, data is accumulated in data[] with len reflecting
526 * the next available byte, headers and lines count the number of lines
527 * in both parts. There are no '\0' in data[0..len-1].
529 * On received packet, the input read from the socket is copied into data[],
530 * len is set and the string is NUL-terminated. Then a parser fills up
531 * the other fields -header[] and line[] to point to the lines of the
532 * message, rlPart1 and rlPart2 parse the first lnie as below:
534 * Requests have in the first line METHOD URI SIP/2.0
535 * rlPart1 = method; rlPart2 = uri;
536 * Responses have in the first line SIP/2.0 code description
537 * rlPart1 = SIP/2.0; rlPart2 = code + description;
541 /*! \brief structure used in transfers */
543 struct ast_channel *chan1; /*!< First channel involved */
544 struct ast_channel *chan2; /*!< Second channel involved */
545 struct sip_request req; /*!< Request that caused the transfer (REFER) */
546 int seqno; /*!< Sequence number */
551 /*! \brief Parameters to the transmit_invite function */
552 struct sip_invite_param {
553 const char *distinctive_ring; /*!< Distinctive ring header */
554 int addsipheaders; /*!< Add extra SIP headers */
555 const char *uri_options; /*!< URI options to add to the URI */
556 const char *vxml_url; /*!< VXML url for Cisco phones */
557 char *auth; /*!< Authentication */
558 char *authheader; /*!< Auth header */
559 enum sip_auth_type auth_type; /*!< Authentication type */
560 const char *replaces; /*!< Replaces header for call transfers */
561 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
564 /*! \brief Structure to save routing information for a SIP session */
566 struct sip_route *next;
570 /*! \brief Modes for SIP domain handling in the PBX */
572 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
573 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
577 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
578 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
579 enum domain_mode mode; /*!< How did we find this domain? */
580 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
583 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
586 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
588 AST_LIST_ENTRY(sip_history) list;
589 char event[0]; /* actually more, depending on needs */
592 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
594 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
596 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
597 char username[256]; /*!< Username */
598 char secret[256]; /*!< Secret */
599 char md5secret[256]; /*!< MD5Secret */
600 struct sip_auth *next; /*!< Next auth structure in list */
603 /*--- Various flags for the flags field in the pvt structure */
604 #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
605 #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed by the monitor thread */
606 #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */
607 #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */
608 #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */
609 #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */
610 #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */
611 #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */
612 #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */
613 #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */
614 #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */
615 #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */
616 #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */
617 #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */
618 #define SIP_FREEBIT (1 << 14) /*!< Free for session-related use */
619 #define SIP_FREEBIT3 (1 << 15) /*!< Free for session-related use */
620 #define SIP_DTMF (3 << 16) /*!< DTMF Support: four settings, uses two bits */
621 #define SIP_DTMF_RFC2833 (0 << 16) /*!< DTMF Support: RTP DTMF - "rfc2833" */
622 #define SIP_DTMF_INBAND (1 << 16) /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
623 #define SIP_DTMF_INFO (2 << 16) /*!< DTMF Support: SIP Info messages - "info" */
624 #define SIP_DTMF_AUTO (3 << 16) /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
626 #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */
627 #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */
628 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */
629 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */
630 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */
631 /* re-INVITE related settings */
632 #define SIP_REINVITE (3 << 20) /*!< two bits used */
633 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */
634 #define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */
635 /* "insecure" settings */
636 #define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */
637 #define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */
638 /* Sending PROGRESS in-band settings */
639 #define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */
640 #define SIP_PROG_INBAND_NEVER (0 << 24)
641 #define SIP_PROG_INBAND_NO (1 << 24)
642 #define SIP_PROG_INBAND_YES (2 << 24)
643 #define SIP_CALL_ONHOLD (1 << 26) /*!< Call states */
644 #define SIP_CALL_LIMIT (1 << 27) /*!< Call limit enforced for this call */
645 #define SIP_SENDRPID (1 << 28) /*!< Remote Party-ID Support */
646 #define SIP_INC_COUNT (1 << 29) /*!< Did this connection increment the counter of in-use calls? */
648 #define SIP_FLAGS_TO_COPY \
649 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
650 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | \
651 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
653 /* a new page of flags for peers */
654 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
655 #define SIP_PAGE2_RTUPDATE (1 << 1)
656 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
657 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3)
658 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4)
659 #define SIP_PAGE2_DEBUG (3 << 5)
660 #define SIP_PAGE2_DEBUG_CONFIG (1 << 5)
661 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 6)
662 #define SIP_PAGE2_DYNAMIC (1 << 7) /*!< Dynamic Peers register with Asterisk */
663 #define SIP_PAGE2_SELFDESTRUCT (1 << 8) /*!< Automatic peers need to destruct themselves */
664 #define SIP_PAGE2_VIDEOSUPPORT (1 << 9)
665 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 10) /*!< Allow subscriptions from this peer? */
666 #define SIP_PAGE2_ALLOWOVERLAP (1 << 11) /*!< Allow overlap dialing ? */
667 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 12) /*!< Only issue MWI notification if subscribed to */
670 #define SIP_PAGE2_FLAGS_TO_COPY \
671 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT)
673 /* SIP packet flags */
674 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */
675 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
676 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */
677 #define SIP_PKT_IGNORE_RESP (1 << 3) /*!< Resp ignore - ??? */
678 #define SIP_PKT_IGNORE_REQ (1 << 4) /*!< Req ignore - ??? */
680 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
681 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
682 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
684 /*! \brief Parameters to know status of transfer */
686 REFER_IDLE, /*!< No REFER is in progress */
687 REFER_SENT, /*!< Sent REFER to transferee */
688 REFER_RECEIVED, /*!< Received REFER from transferer */
689 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */
690 REFER_ACCEPTED, /*!< Accepted by transferee */
691 REFER_RINGING, /*!< Target Ringing */
692 REFER_200OK, /*!< Answered by transfer target */
693 REFER_FAILED, /*!< REFER declined - go on */
694 REFER_NOAUTH /*!< We had no auth for REFER */
697 static const struct c_referstatusstring {
698 enum referstatus status;
700 } referstatusstrings[] = {
701 { REFER_IDLE, "<none>" },
702 { REFER_SENT, "Request sent" },
703 { REFER_RECEIVED, "Request received" },
704 { REFER_ACCEPTED, "Accepted" },
705 { REFER_RINGING, "Target ringing" },
706 { REFER_200OK, "Done" },
707 { REFER_FAILED, "Failed" },
708 { REFER_NOAUTH, "Failed - auth failure" }
712 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */
713 static struct sip_pvt {
714 ast_mutex_t lock; /*!< Dialog private lock */
715 int method; /*!< SIP method that opened this dialog */
716 AST_DECLARE_STRING_FIELDS(
717 AST_STRING_FIELD(callid); /*!< Global CallID */
718 AST_STRING_FIELD(randdata); /*!< Random data */
719 AST_STRING_FIELD(accountcode); /*!< Account code */
720 AST_STRING_FIELD(realm); /*!< Authorization realm */
721 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
722 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
723 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
724 AST_STRING_FIELD(domain); /*!< Authorization domain */
725 AST_STRING_FIELD(refer_to); /*!< Place to store REFER-TO extension */
726 AST_STRING_FIELD(referred_by); /*!< Place to store REFERRED-BY extension */
727 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
728 AST_STRING_FIELD(from); /*!< The From: header */
729 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
730 AST_STRING_FIELD(exten); /*!< Extension where to start */
731 AST_STRING_FIELD(context); /*!< Context for this call */
732 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
733 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
734 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
735 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
736 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
737 AST_STRING_FIELD(language); /*!< Default language for this call */
738 AST_STRING_FIELD(musicclass); /*!< Music on Hold class */
739 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
740 AST_STRING_FIELD(theirtag); /*!< Their tag */
741 AST_STRING_FIELD(username); /*!< [user] name */
742 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
743 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
744 AST_STRING_FIELD(uri); /*!< Original requested URI */
745 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
746 AST_STRING_FIELD(peersecret); /*!< Password */
747 AST_STRING_FIELD(peermd5secret);
748 AST_STRING_FIELD(cid_num); /*!< Caller*ID */
749 AST_STRING_FIELD(cid_name); /*!< Caller*ID */
750 AST_STRING_FIELD(via); /*!< Via: header */
751 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
752 AST_STRING_FIELD(our_contact); /*!< Our contact header */
753 AST_STRING_FIELD(rpid); /*!< Our RPID header */
754 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
756 struct ast_codec_pref prefs; /*!< codec prefs */
757 unsigned int ocseq; /*!< Current outgoing seqno */
758 unsigned int icseq; /*!< Current incoming seqno */
759 ast_group_t callgroup; /*!< Call group */
760 ast_group_t pickupgroup; /*!< Pickup group */
761 int lastinvite; /*!< Last Cseq of invite */
762 struct ast_flags flags[2]; /*!< SIP_ flags */
763 int timer_t1; /*!< SIP timer T1, ms rtt */
764 unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */
765 int capability; /*!< Special capability (codec) */
766 int jointcapability; /*!< Supported capability at both ends (codecs ) */
767 int peercapability; /*!< Supported peer capability */
768 int prefcodec; /*!< Preferred codec (outbound only) */
769 int noncodeccapability;
770 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
771 int callingpres; /*!< Calling presentation */
772 int authtries; /*!< Times we've tried to authenticate */
773 int expiry; /*!< How long we take to expire */
774 long branch; /*!< One random number */
775 char tag[11]; /*!< Another random number */
776 int sessionid; /*!< SDP Session ID */
777 int sessionversion; /*!< SDP Session Version */
778 struct sockaddr_in sa; /*!< Our peer */
779 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
780 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
781 int redircodecs; /*!< Redirect codecs */
782 struct sockaddr_in recv; /*!< Received as */
783 struct in_addr ourip; /*!< Our IP */
784 struct ast_channel *owner; /*!< Who owns us */
785 struct sip_pvt *refer_call; /*!< Call we are referring */
786 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
787 int route_persistant; /*!< Is this the "real" route? */
788 struct sip_auth *peerauth; /*!< Realm authentication */
789 int noncecount; /*!< Nonce-count */
790 char lastmsg[256]; /*!< Last Message sent/received */
791 int amaflags; /*!< AMA Flags */
792 int pendinginvite; /*!< Any pending invite */
793 struct sip_request initreq; /*!< Initial request that opened the SIP dialog */
795 int maxtime; /*!< Max time for first response */
796 int initid; /*!< Auto-congest ID if appropriate */
797 int autokillid; /*!< Auto-kill ID */
798 time_t lastrtprx; /*!< Last RTP received */
799 time_t lastrtptx; /*!< Last RTP sent */
800 int rtptimeout; /*!< RTP timeout time */
801 int rtpholdtimeout; /*!< RTP timeout when on hold */
802 int rtpkeepalive; /*!< Send RTP packets for keepalive */
803 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
804 enum subscriptiontype subscribed; /*!< Is this dialog a subscription? */
806 int laststate; /*!< Last known extension state */
809 struct ast_dsp *vad; /*!< Voice Activation Detection dsp */
811 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
812 Used in peerpoke, mwi subscriptions */
813 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
814 struct ast_rtp *rtp; /*!< RTP Session */
815 struct ast_rtp *vrtp; /*!< Video RTP session */
816 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
817 struct sip_history_head *history; /*!< History of this SIP dialog */
818 struct ast_variable *chanvars; /*!< Channel variables to set for call */
819 struct sip_pvt *next; /*!< Next dialog in chain */
820 struct sip_invite_param *options; /*!< Options for INVITE */
823 #define FLAG_RESPONSE (1 << 0)
824 #define FLAG_FATAL (1 << 1)
826 /*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
828 struct sip_pkt *next; /*!< Next packet */
829 int retrans; /*!< Retransmission number */
830 int method; /*!< SIP method for this packet */
831 int seqno; /*!< Sequence number */
832 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */
833 struct sip_pvt *owner; /*!< Owner AST call */
834 int retransid; /*!< Retransmission ID */
835 int timer_a; /*!< SIP timer A, retransmission timer */
836 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
837 int packetlen; /*!< Length of packet */
841 /*! \brief Structure for SIP user data. User's place calls to us */
843 /* Users who can access various contexts */
844 ASTOBJ_COMPONENTS(struct sip_user);
845 char secret[80]; /*!< Password */
846 char md5secret[80]; /*!< Password in md5 */
847 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
848 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
849 char cid_num[80]; /*!< Caller ID num */
850 char cid_name[80]; /*!< Caller ID name */
851 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
852 char language[MAX_LANGUAGE]; /*!< Default language for this user */
853 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
854 char useragent[256]; /*!< User agent in SIP request */
855 struct ast_codec_pref prefs; /*!< codec prefs */
856 ast_group_t callgroup; /*!< Call group */
857 ast_group_t pickupgroup; /*!< Pickup Group */
858 unsigned int sipoptions; /*!< Supported SIP options */
859 struct ast_flags flags[2]; /*!< SIP_ flags */
860 int amaflags; /*!< AMA flags for billing */
861 int callingpres; /*!< Calling id presentation */
862 int capability; /*!< Codec capability */
863 int inUse; /*!< Number of calls in use */
864 int call_limit; /*!< Limit of concurrent calls */
865 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
866 struct ast_ha *ha; /*!< ACL setting */
867 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
868 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
871 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
872 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
874 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */
875 /*!< peer->name is the unique name of this object */
876 char secret[80]; /*!< Password */
877 char md5secret[80]; /*!< Password in MD5 */
878 struct sip_auth *auth; /*!< Realm authentication list */
879 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
880 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
881 char username[80]; /*!< Temporary username until registration */
882 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
883 int amaflags; /*!< AMA Flags (for billing) */
884 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
885 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
886 char fromuser[80]; /*!< From: user when calling this peer */
887 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
888 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
889 char cid_num[80]; /*!< Caller ID num */
890 char cid_name[80]; /*!< Caller ID name */
891 int callingpres; /*!< Calling id presentation */
892 int inUse; /*!< Number of calls in use */
893 int call_limit; /*!< Limit of concurrent calls */
894 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
895 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
896 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
897 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
898 char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
899 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
900 struct ast_codec_pref prefs; /*!< codec prefs */
902 time_t lastmsgcheck; /*!< Last time we checked for MWI */
903 unsigned int sipoptions; /*!< Supported SIP options */
904 struct ast_flags flags[2]; /*!< SIP_ flags */
905 int expire; /*!< When to expire this peer registration */
906 int capability; /*!< Codec capability */
907 int rtptimeout; /*!< RTP timeout */
908 int rtpholdtimeout; /*!< RTP Hold Timeout */
909 int rtpkeepalive; /*!< Send RTP packets for keepalive */
910 ast_group_t callgroup; /*!< Call group */
911 ast_group_t pickupgroup; /*!< Pickup group */
912 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
913 struct sockaddr_in addr; /*!< IP address of peer */
914 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
917 struct sip_pvt *call; /*!< Call pointer */
918 int pokeexpire; /*!< When to expire poke (qualify= checking) */
919 int lastms; /*!< How long last response took (in ms), or -1 for no response */
920 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
921 struct timeval ps; /*!< Ping send time */
923 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
924 struct ast_ha *ha; /*!< Access control list */
925 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
926 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
932 /*! \brief Registrations with other SIP proxies */
933 struct sip_registry {
934 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
935 AST_DECLARE_STRING_FIELDS(
936 AST_STRING_FIELD(callid); /*!< Global Call-ID */
937 AST_STRING_FIELD(realm); /*!< Authorization realm */
938 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
939 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
940 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
941 AST_STRING_FIELD(domain); /*!< Authorization domain */
942 AST_STRING_FIELD(username); /*!< Who we are registering as */
943 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
944 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
945 AST_STRING_FIELD(secret); /*!< Password in clear text */
946 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
947 AST_STRING_FIELD(contact); /*!< Contact extension */
948 AST_STRING_FIELD(random);
950 int portno; /*!< Optional port override */
951 int expire; /*!< Sched ID of expiration */
952 int regattempts; /*!< Number of attempts (since the last success) */
953 int timeout; /*!< sched id of sip_reg_timeout */
954 int refresh; /*!< How often to refresh */
955 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
956 enum sipregistrystate regstate; /*!< Registration state (see above) */
957 time_t regtime; /*!< Last succesful registration time */
958 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
959 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
960 struct sockaddr_in us; /*!< Who the server thinks we are */
961 int noncecount; /*!< Nonce-count */
962 char lastmsg[256]; /*!< Last Message sent/received */
965 /* --- Linked lists of various objects --------*/
967 /*! \brief The user list: Users and friends */
968 static struct ast_user_list {
969 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
972 /*! \brief The peer list: Peers and Friends */
973 static struct ast_peer_list {
974 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
977 /*! \brief The register list: Other SIP proxys we register with and place calls to */
978 static struct ast_register_list {
979 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
983 /*! \todo Move the sip_auth list to AST_LIST */
984 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */
987 /* --- Sockets and networking --------------*/
988 static int sipsock = -1; /*!< Main socket for SIP network communication */
989 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
990 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
991 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */
992 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
993 static int externrefresh = 10;
994 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
995 static struct in_addr __ourip;
996 static struct sockaddr_in outboundproxyip;
998 static struct sockaddr_in debugaddr;
1000 struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1004 /*---------------------------- Forward declarations of functions in chan_sip.c */
1005 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
1006 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, enum xmittype reliable);
1007 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *unsupported);
1008 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1009 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1010 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1011 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
1012 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
1013 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
1014 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1015 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1016 static int transmit_refer(struct sip_pvt *p, const char *dest);
1017 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1018 static struct sip_peer *temp_peer(const char *name);
1019 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
1020 static void free_old_route(struct sip_route *route);
1021 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1022 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1023 static int update_call_counter(struct sip_pvt *fup, int event);
1024 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
1025 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1026 static int sip_do_reload(enum channelreloadreason reason);
1027 static int expire_register(void *data);
1028 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1029 static int sip_devicestate(void *data);
1030 static int sip_sendtext(struct ast_channel *ast, const char *text);
1031 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1032 static int sip_hangup(struct ast_channel *ast);
1033 static int sip_answer(struct ast_channel *ast);
1034 static struct ast_frame *sip_read(struct ast_channel *ast);
1035 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1036 static int sip_indicate(struct ast_channel *ast, int condition);
1037 static int sip_transfer(struct ast_channel *ast, const char *dest);
1038 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1039 static int sip_senddigit(struct ast_channel *ast, char digit);
1040 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1041 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
1042 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); /* Find authentication for a specific realm */
1043 static int check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1044 const char *secret, const char *md5secret, int sipmethod,
1045 char *uri, enum xmittype reliable, int ignore);
1046 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1047 static void append_date(struct sip_request *req); /* Append date to SIP packet */
1048 static int determine_firstline_parts(struct sip_request *req);
1049 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1050 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1051 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
1052 static const char *gettag(const struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
1053 static int find_sip_method(const char *msg);
1054 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1055 static void sip_destroy(struct sip_pvt *p);
1056 static void sip_destroy_peer(struct sip_peer *peer);
1057 static void sip_destroy_user(struct sip_user *user);
1058 static void parse_request(struct sip_request *req);
1059 static const char *get_header(const struct sip_request *req, const char *name);
1060 static void copy_request(struct sip_request *dst,struct sip_request *src);
1061 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, struct sip_request *req);
1062 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
1063 static int sip_poke_peer(struct sip_peer *peer);
1064 static int __sip_do_register(struct sip_registry *r);
1065 static int restart_monitor(void);
1066 static void set_peer_defaults(struct sip_peer *peer);
1067 static struct sip_peer *temp_peer(const char *name);
1068 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1069 static int sip_scheddestroy(struct sip_pvt *p, int ms);
1071 /*------Request handling functions */
1072 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);
1073 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
1074 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1075 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1076 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1077 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1078 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1079 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1080 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1082 /*----- RTP interface functions */
1083 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1084 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
1085 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
1086 static int sip_get_codec(struct ast_channel *chan);
1088 /*! \brief Definition of this channel for PBX channel registration */
1089 static const struct ast_channel_tech sip_tech = {
1091 .description = "Session Initiation Protocol (SIP)",
1092 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1093 .properties = AST_CHAN_TP_WANTSJITTER,
1094 .requester = sip_request_call,
1095 .devicestate = sip_devicestate,
1097 .hangup = sip_hangup,
1098 .answer = sip_answer,
1101 .write_video = sip_write,
1102 .indicate = sip_indicate,
1103 .transfer = sip_transfer,
1105 .send_digit = sip_senddigit,
1106 .bridge = ast_rtp_bridge,
1107 .send_text = sip_sendtext,
1110 /*! \brief Interface structure with callbacks used to connect to RTP module */
1111 static struct ast_rtp_protocol sip_rtp = {
1113 get_rtp_info: sip_get_rtp_peer,
1114 get_vrtp_info: sip_get_vrtp_peer,
1115 set_rtp_peer: sip_set_rtp_peer,
1116 get_codec: sip_get_codec,
1119 /*! \brief Convert transfer status to string */
1120 static char *referstatus2str(enum referstatus rstatus)
1122 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1125 for (x = 0; x < i; x++) {
1126 if (referstatusstrings[x].status == rstatus)
1127 return (char *) referstatusstrings[x].text;
1133 /*! \brief returns true if 'name' (with optional trailing whitespace)
1134 * matches the sip method 'id'.
1135 * Strictly speaking, SIP methods are case SENSITIVE, but we do
1136 * a case-insensitive comparison to be more tolerant.
1137 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1139 static int method_match(enum sipmethod id, const char *name)
1141 int len = strlen(sip_methods[id].text);
1142 int l_name = name ? strlen(name) : 0;
1143 /* true if the string is long enough, and ends with whitespace, and matches */
1144 return (l_name >= len && name[len] < 33 &&
1145 !strncasecmp(sip_methods[id].text, name, len));
1148 /*! \brief find_sip_method: Find SIP method from header */
1149 static int find_sip_method(const char *msg)
1153 if (ast_strlen_zero(msg))
1155 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1156 if (method_match(i, msg))
1157 res = sip_methods[i].id;
1162 /*! \brief Parse supported header in incoming packet */
1163 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1166 char *temp = ast_strdupa(supported);
1167 unsigned int profile = 0;
1170 if (!pvt || ast_strlen_zero(supported) )
1173 if (option_debug > 2 && sipdebug)
1174 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1176 for (next = temp; next; next = sep) {
1178 if ( (sep = strchr(next, ',')) != NULL)
1180 next = ast_skip_blanks(next);
1181 if (option_debug > 2 && sipdebug)
1182 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1183 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1184 if (!strcasecmp(next, sip_options[i].text)) {
1185 profile |= sip_options[i].id;
1187 if (option_debug > 2 && sipdebug)
1188 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1192 if (!found && option_debug > 2 && sipdebug)
1193 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1196 pvt->sipoptions = profile;
1200 /*! \brief See if we pass debug IP filter */
1201 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
1205 if (debugaddr.sin_addr.s_addr) {
1206 if (((ntohs(debugaddr.sin_port) != 0)
1207 && (debugaddr.sin_port != addr->sin_port))
1208 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1214 /* The real destination address for a write */
1215 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1217 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1220 static const char *sip_nat_mode(const struct sip_pvt *p)
1222 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1225 /*! \brief Test PVT for debugging output */
1226 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1230 return sip_debug_test_addr(sip_real_dst(p));
1233 /*! \brief Transmit SIP message */
1234 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1237 char iabuf[INET_ADDRSTRLEN];
1238 const struct sockaddr_in *dst = sip_real_dst(p);
1239 res=sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1242 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
1247 /*! \brief Build a Via header for a request */
1248 static void build_via(struct sip_pvt *p)
1250 char iabuf[INET_ADDRSTRLEN];
1251 /* Work around buggy UNIDEN UIP200 firmware */
1252 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1254 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1255 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1256 ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1259 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1260 * Only used for outbound registrations */
1261 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1264 * Using the localaddr structure built up with localnet statements
1265 * apply it to their address to see if we need to substitute our
1266 * externip or can get away with our internal bindaddr
1268 struct sockaddr_in theirs;
1269 theirs.sin_addr = *them;
1271 if (localaddr && externip.sin_addr.s_addr &&
1272 ast_apply_ha(localaddr, &theirs)) {
1273 if (externexpire && time(NULL) >= externexpire) {
1274 struct ast_hostent ahp;
1277 time(&externexpire);
1278 externexpire += externrefresh;
1279 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1280 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1282 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1284 *us = externip.sin_addr;
1286 char iabuf[INET_ADDRSTRLEN];
1287 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1289 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1291 } else if (bindaddr.sin_addr.s_addr)
1292 *us = bindaddr.sin_addr;
1294 return ast_ouraddrfor(them, us);
1298 /*! \brief Append to SIP dialog history
1299 \return Always returns 0 */
1300 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
1302 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1303 __attribute__ ((format (printf, 2, 3)));
1305 /*! \brief Append to SIP dialog history with arg list */
1306 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1308 char buf[80], *c = buf; /* max history length */
1309 struct sip_history *hist;
1312 vsnprintf(buf, sizeof(buf), fmt, ap);
1313 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1314 l = strlen(buf) + 1;
1315 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1317 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1321 memcpy(hist->event, buf, l);
1322 AST_LIST_INSERT_TAIL(p->history, hist, list);
1325 /*! \brief Append to SIP dialog history with arg list */
1326 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1330 if (!recordhistory || !p)
1333 append_history_va(p, fmt, ap);
1339 /*! \brief Retransmit SIP message if no answer */
1340 static int retrans_pkt(void *data)
1342 struct sip_pkt *pkt=data, *prev, *cur = NULL;
1343 char iabuf[INET_ADDRSTRLEN];
1344 int reschedule = DEFAULT_RETRANS;
1347 ast_mutex_lock(&pkt->owner->lock);
1349 if (pkt->retrans < MAX_RETRANS) {
1351 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1352 if (sipdebug && option_debug > 3)
1353 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);
1357 if (sipdebug && option_debug > 3)
1358 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1362 pkt->timer_a = 2 * pkt->timer_a;
1364 /* For non-invites, a maximum of 4 secs */
1365 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1366 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1369 /* Reschedule re-transmit */
1370 reschedule = siptimer_a;
1371 if (option_debug > 3)
1372 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);
1375 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1376 if (ast_test_flag(&pkt->owner->flags[0], SIP_NAT_ROUTE))
1377 ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
1379 ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
1382 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1383 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1384 ast_mutex_unlock(&pkt->owner->lock);
1387 /* Too many retries */
1388 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1389 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1390 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");
1392 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1393 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1395 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1397 pkt->retransid = -1;
1399 if (ast_test_flag(pkt, FLAG_FATAL)) {
1400 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1401 ast_mutex_unlock(&pkt->owner->lock);
1403 ast_mutex_lock(&pkt->owner->lock);
1405 if (pkt->owner->owner) {
1406 ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1407 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1408 ast_queue_hangup(pkt->owner->owner);
1409 ast_mutex_unlock(&pkt->owner->owner->lock);
1411 /* If no channel owner, destroy now */
1412 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);
1415 /* In any case, go ahead and remove the packet */
1416 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1422 prev->next = cur->next;
1424 pkt->owner->packets = cur->next;
1425 ast_mutex_unlock(&pkt->owner->lock);
1429 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1431 ast_mutex_unlock(&pkt->owner->lock);
1435 /*! \brief Transmit packet with retransmits
1436 \return 0 on success, -1 on failure to allocate packet
1438 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1440 struct sip_pkt *pkt;
1441 int siptimer_a = DEFAULT_RETRANS;
1443 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1445 memcpy(pkt->data, data, len);
1446 pkt->method = sipmethod;
1447 pkt->packetlen = len;
1448 pkt->next = p->packets;
1452 pkt->data[len] = '\0';
1453 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1455 ast_set_flag(pkt, FLAG_FATAL);
1457 siptimer_a = pkt->timer_t1 * 2;
1459 /* Schedule retransmission */
1460 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1461 if (option_debug > 3 && sipdebug)
1462 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1463 pkt->next = p->packets;
1466 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1467 if (sipmethod == SIP_INVITE) {
1468 /* Note this is a pending invite */
1469 p->pendinginvite = seqno;
1474 /*! \brief Kill a SIP dialog (called by scheduler) */
1475 static int __sip_autodestruct(void *data)
1477 struct sip_pvt *p = data;
1479 /* If this is a subscription, tell the phone that we got a timeout */
1480 if (p->subscribed) {
1481 p->subscribed = TIMEOUT;
1482 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1483 p->subscribed = NONE;
1484 append_history(p, "Subscribestatus", "timeout");
1485 if (option_debug > 2)
1486 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1487 return 10000; /* Reschedule this destruction so that we know that it's gone */
1490 /* Reset schedule ID */
1494 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1495 append_history(p, "AutoDestroy", "");
1497 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1498 ast_queue_hangup(p->owner);
1505 /*! \brief Schedule destruction of SIP call */
1506 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1508 if (sip_debug_test_pvt(p))
1509 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1511 append_history(p, "SchedDestroy", "%d ms", ms);
1513 if (p->autokillid > -1)
1514 ast_sched_del(sched, p->autokillid);
1515 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1519 /*! \brief Cancel destruction of SIP dialog */
1520 static int sip_cancel_destroy(struct sip_pvt *p)
1522 if (p->autokillid > -1) {
1523 ast_sched_del(sched, p->autokillid);
1524 append_history(p, "CancelDestroy", "");
1530 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1531 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod, int reset)
1533 struct sip_pkt *cur, *prev = NULL;
1536 /* Just in case... */
1539 msg = sip_methods[sipmethod].text;
1541 ast_mutex_lock(&p->lock);
1542 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
1543 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1544 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1545 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1546 if (!resp && (seqno == p->pendinginvite)) {
1547 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1548 p->pendinginvite = 0;
1550 /* this is our baby */
1552 prev->next = cur->next;
1554 p->packets = cur->next;
1555 if (cur->retransid > -1) {
1556 if (sipdebug && option_debug > 3)
1557 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1558 ast_sched_del(sched, cur->retransid);
1566 ast_mutex_unlock(&p->lock);
1568 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1572 /*! \brief Pretend to ack all packets */
1573 static int __sip_pretend_ack(struct sip_pvt *p)
1575 struct sip_pkt *cur = NULL;
1577 while (p->packets) {
1578 if (cur == p->packets) {
1579 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1584 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method, FALSE);
1585 else { /* Unknown packet type */
1589 ast_copy_string(method, p->packets->data, sizeof(method));
1590 c = ast_skip_blanks(method); /* XXX what ? */
1592 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method), FALSE);
1598 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
1599 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1601 struct sip_pkt *cur;
1604 for (cur = p->packets; cur; cur = cur->next) {
1605 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
1606 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
1607 /* this is our baby */
1608 if (cur->retransid > -1) {
1609 if (option_debug > 3 && sipdebug)
1610 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
1611 ast_sched_del(sched, cur->retransid);
1613 cur->retransid = -1;
1619 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");
1624 /*! \brief Copy SIP request, parse it */
1625 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1627 memset(dst, 0, sizeof(*dst));
1628 memcpy(dst->data, src->data, sizeof(dst->data));
1629 dst->len = src->len;
1633 /*! \brief Transmit response on SIP request*/
1634 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1638 if (sip_debug_test_pvt(p)) {
1639 char iabuf[INET_ADDRSTRLEN];
1640 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1641 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1643 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1645 if (recordhistory) {
1646 struct sip_request tmp;
1647 parse_copy(&tmp, req);
1648 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"),
1649 tmp.method == SIP_RESPONSE ? tmp.rlPart2 : sip_methods[tmp.method].text);
1652 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
1653 __sip_xmit(p, req->data, req->len);
1659 /*! \brief Send SIP Request to the other part of the dialogue */
1660 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1664 if (sip_debug_test_pvt(p)) {
1665 char iabuf[INET_ADDRSTRLEN];
1666 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1667 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1669 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1671 if (recordhistory) {
1672 struct sip_request tmp;
1673 parse_copy(&tmp, req);
1674 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
1677 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1678 __sip_xmit(p, req->data, req->len);
1682 /*! \brief Pick out text in brackets from character string
1683 \return pointer to terminated stripped string
1684 \param tmp input string that will be modified */
1685 static char *get_in_brackets(char *tmp)
1689 char *first_bracket;
1690 char *second_bracket;
1695 first_quote = strchr(parse, '"');
1696 first_bracket = strchr(parse, '<');
1697 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1699 for (parse = first_quote + 1; *parse; parse++) {
1700 if ((*parse == '"') && (last_char != '\\'))
1705 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1711 if (first_bracket) {
1712 second_bracket = strchr(first_bracket + 1, '>');
1713 if (second_bracket) {
1714 *second_bracket = '\0';
1715 return first_bracket + 1;
1717 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1725 /*! \brief Send SIP MESSAGE text within a call
1726 Called from PBX core sendtext() application */
1727 static int sip_sendtext(struct ast_channel *ast, const char *text)
1729 struct sip_pvt *p = ast->tech_pvt;
1730 int debug = sip_debug_test_pvt(p);
1733 ast_verbose("Sending text %s on %s\n", text, ast->name);
1736 if (ast_strlen_zero(text))
1739 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1740 transmit_message_with_text(p, text);
1744 /*! \brief Update peer object in realtime storage */
1745 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1749 char regseconds[20];
1751 const char *fc = fullcontact ? "fullcontact" : NULL;
1755 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
1756 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1757 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1759 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
1760 "port", port, "regseconds", regseconds,
1761 "username", username, fc, fullcontact, NULL); /* note fc _can_ be NULL */
1764 /*! \brief Automatically add peer extension to dial plan */
1765 static void register_peer_exten(struct sip_peer *peer, int onoff)
1768 char *stringp, *ext;
1769 if (!ast_strlen_zero(global_regcontext)) {
1771 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
1773 while((ext = strsep(&stringp, "&"))) {
1775 ast_add_extension(global_regcontext, 1, ext, 1, NULL, NULL, "Noop",
1776 ast_strdup(peer->name), free, "SIP");
1778 ast_context_remove_extension(global_regcontext, ext, 1, NULL);
1783 /*! \brief Destroy peer object from memory */
1784 static void sip_destroy_peer(struct sip_peer *peer)
1786 if (option_debug > 2)
1787 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
1789 /* Delete it, it needs to disappear */
1791 sip_destroy(peer->call);
1793 if (peer->mwipvt) { /* We have an active subscription, delete it */
1794 sip_destroy(peer->mwipvt);
1797 if (peer->chanvars) {
1798 ast_variables_destroy(peer->chanvars);
1799 peer->chanvars = NULL;
1801 if (peer->expire > -1)
1802 ast_sched_del(sched, peer->expire);
1803 if (peer->pokeexpire > -1)
1804 ast_sched_del(sched, peer->pokeexpire);
1805 register_peer_exten(peer, FALSE);
1806 ast_free_ha(peer->ha);
1807 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
1809 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
1813 clear_realm_authentication(peer->auth);
1816 ast_dnsmgr_release(peer->dnsmgr);
1820 /*! \brief Update peer data in database (if used) */
1821 static void update_peer(struct sip_peer *p, int expiry)
1823 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
1824 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
1825 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
1826 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
1831 /*! \brief realtime_peer: Get peer from realtime storage
1832 * Checks the "sippeers" realtime family from extconfig.conf
1833 * \todo Consider adding check of port address when matching here to follow the same
1834 * algorithm as for static peers. Will we break anything by adding that?
1836 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1838 struct sip_peer *peer = NULL;
1839 struct ast_variable *var;
1840 struct ast_variable *tmp;
1841 char *newpeername = (char *) peername;
1844 /* First check on peer name */
1846 var = ast_load_realtime("sippeers", "name", peername, NULL);
1847 else if (sin) { /* Then check on IP address for dynamic peers */
1848 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1849 var = ast_load_realtime("sippeers", "host", iabuf, NULL); /* First check for fixed IP hosts */
1851 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */
1859 for (tmp = var; tmp; tmp = tmp->next) {
1860 /* If this is type=user, then skip this object. */
1861 if (!strcasecmp(tmp->name, "type") &&
1862 !strcasecmp(tmp->value, "user")) {
1863 ast_variables_destroy(var);
1865 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1866 newpeername = tmp->value;
1870 if (!newpeername) { /* Did not find peer in realtime */
1871 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1872 ast_variables_destroy(var);
1876 /* Peer found in realtime, now build it in memory */
1877 peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
1879 ast_variables_destroy(var);
1883 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
1885 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1886 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
1887 if (peer->expire > -1) {
1888 ast_sched_del(sched, peer->expire);
1890 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1892 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1894 ast_set_flag(&peer->flags[0], SIP_REALTIME);
1896 ast_variables_destroy(var);
1901 /*! \brief Support routine for find_peer */
1902 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1904 /* We know name is the first field, so we can cast */
1905 struct sip_peer *p = (struct sip_peer *) name;
1906 return !(!inaddrcmp(&p->addr, sin) ||
1907 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
1908 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1911 /*! \brief Locate peer by name or ip address
1912 * This is used on incoming SIP message to find matching peer on ip
1913 or outgoing message to find matching peer on name */
1914 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1916 struct sip_peer *p = NULL;
1919 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1921 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
1923 if (!p && realtime) {
1924 p = realtime_peer(peer, sin);
1929 /*! \brief Remove user object from in-memory storage */
1930 static void sip_destroy_user(struct sip_user *user)
1932 if (option_debug > 2)
1933 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
1934 ast_free_ha(user->ha);
1935 if (user->chanvars) {
1936 ast_variables_destroy(user->chanvars);
1937 user->chanvars = NULL;
1939 if (ast_test_flag(&user->flags[0], SIP_REALTIME))
1946 /*! \brief Load user from realtime storage
1947 * Loads user from "sipusers" category in realtime (extconfig.conf)
1948 * Users are matched on From: user name (the domain in skipped) */
1949 static struct sip_user *realtime_user(const char *username)
1951 struct ast_variable *var;
1952 struct ast_variable *tmp;
1953 struct sip_user *user = NULL;
1955 var = ast_load_realtime("sipusers", "name", username, NULL);
1960 for (tmp = var; tmp; tmp = tmp->next) {
1961 if (!strcasecmp(tmp->name, "type") &&
1962 !strcasecmp(tmp->value, "peer")) {
1963 ast_variables_destroy(var);
1968 user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
1970 if (!user) { /* No user found */
1971 ast_variables_destroy(var);
1975 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
1976 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
1978 ASTOBJ_CONTAINER_LINK(&userl,user);
1980 /* Move counter from s to r... */
1983 ast_set_flag(&user->flags[0], SIP_REALTIME);
1985 ast_variables_destroy(var);
1989 /*! \brief Locate user by name
1990 * Locates user by name (From: sip uri user name part) first
1991 * from in-memory list (static configuration) then from
1992 * realtime storage (defined in extconfig.conf) */
1993 static struct sip_user *find_user(const char *name, int realtime)
1995 struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
1997 u = realtime_user(name);
2001 /*! \brief Create address structure from peer reference */
2002 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
2006 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2007 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
2008 r->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2014 ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2015 ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2016 r->capability = peer->capability;
2017 if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
2018 ast_rtp_destroy(r->vrtp);
2021 r->prefs = peer->prefs;
2022 natflags = ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE;
2025 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", natflags);
2026 ast_rtp_setnat(r->rtp, natflags);
2030 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", natflags);
2031 ast_rtp_setnat(r->vrtp, natflags);
2033 ast_string_field_set(r, peername, peer->username);
2034 ast_string_field_set(r, authname, peer->username);
2035 ast_string_field_set(r, username, peer->username);
2036 ast_string_field_set(r, peersecret, peer->secret);
2037 ast_string_field_set(r, peermd5secret, peer->md5secret);
2038 ast_string_field_set(r, tohost, peer->tohost);
2039 ast_string_field_set(r, fullcontact, peer->fullcontact);
2040 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2043 tmpcall = ast_strdupa(r->callid);
2045 c = strchr(tmpcall, '@');
2048 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
2052 if (ast_strlen_zero(r->tohost)) {
2053 char iabuf[INET_ADDRSTRLEN];
2055 ast_inet_ntoa(iabuf, sizeof(iabuf), r->sa.sin_addr);
2056 ast_string_field_set(r, tohost, iabuf);
2058 if (!ast_strlen_zero(peer->fromdomain))
2059 ast_string_field_set(r, fromdomain, peer->fromdomain);
2060 if (!ast_strlen_zero(peer->fromuser))
2061 ast_string_field_set(r, fromuser, peer->fromuser);
2062 r->maxtime = peer->maxms;
2063 r->callgroup = peer->callgroup;
2064 r->pickupgroup = peer->pickupgroup;
2065 r->allowtransfer = peer->allowtransfer;
2066 /* Set timer T1 to RTT for this peer (if known by qualify=) */
2067 /* Minimum is settable or default to 100 ms */
2068 if (peer->maxms && peer->lastms)
2069 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2070 if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2071 (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2072 r->noncodeccapability |= AST_RTP_DTMF;
2074 r->noncodeccapability &= ~AST_RTP_DTMF;
2075 ast_string_field_set(r, context, peer->context);
2076 r->rtptimeout = peer->rtptimeout;
2077 r->rtpholdtimeout = peer->rtpholdtimeout;
2078 r->rtpkeepalive = peer->rtpkeepalive;
2079 if (peer->call_limit)
2080 ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
2081 r->maxcallbitrate = peer->maxcallbitrate;
2086 /*! \brief create address structure from peer name
2087 * Or, if peer not found, find it in the global DNS
2088 * returns TRUE (-1) on failure, FALSE on success */
2089 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2092 struct ast_hostent ahp;
2097 char host[MAXHOSTNAMELEN], *hostn;
2100 ast_copy_string(peer, opeer, sizeof(peer));
2101 port = strchr(peer, ':');
2104 dialog->sa.sin_family = AF_INET;
2105 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2106 p = find_peer(peer, NULL, 1);
2110 if (create_addr_from_peer(dialog, p))
2111 ASTOBJ_UNREF(p, sip_destroy_peer);
2118 portno = port ? atoi(port) : DEFAULT_SIP_PORT;
2120 char service[MAXHOSTNAMELEN];
2123 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2124 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2130 hp = ast_gethostbyname(hostn, &ahp);
2132 ast_string_field_set(dialog, tohost, peer);
2133 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2134 dialog->sa.sin_port = htons(portno);
2135 dialog->recv = dialog->sa;
2138 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2142 ASTOBJ_UNREF(p, sip_destroy_peer);
2147 /*! \brief Scheduled congestion on a call */
2148 static int auto_congest(void *nothing)
2150 struct sip_pvt *p = nothing;
2152 ast_mutex_lock(&p->lock);
2155 /* XXX fails on possible deadlock */
2156 if (!ast_mutex_trylock(&p->owner->lock)) {
2157 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2158 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2159 ast_mutex_unlock(&p->owner->lock);
2162 ast_mutex_unlock(&p->lock);
2169 /*! \brief Initiate SIP call from PBX
2170 * used from the dial() application */
2171 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2175 struct varshead *headp;
2176 struct ast_var_t *current;
2179 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2180 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2184 /* Check whether there is vxml_url, distinctive ring variables */
2185 headp=&ast->varshead;
2186 AST_LIST_TRAVERSE(headp,current,entries) {
2187 /* Check whether there is a VXML_URL variable */
2188 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2189 p->options->vxml_url = ast_var_value(current);
2190 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2191 p->options->uri_options = ast_var_value(current);
2192 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2193 /* Check whether there is a ALERT_INFO variable */
2194 p->options->distinctive_ring = ast_var_value(current);
2195 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2196 /* Check whether there is a variable with a name starting with SIPADDHEADER */
2197 p->options->addsipheaders = 1;
2202 ast_set_flag(&p->flags[0], SIP_OUTGOING);
2204 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2205 res = update_call_counter(p, INC_CALL_LIMIT);
2207 p->callingpres = ast->cid.cid_pres;
2208 p->jointcapability = p->capability;
2209 transmit_invite(p, SIP_INVITE, 1, 2);
2211 /* Initialize auto-congest time */
2212 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2218 /*! \brief Destroy registry object
2219 Objects created with the register= statement in static configuration */
2220 static void sip_registry_destroy(struct sip_registry *reg)
2223 if (option_debug > 2)
2224 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2227 /* Clear registry before destroying to ensure
2228 we don't get reentered trying to grab the registry lock */
2229 reg->call->registry = NULL;
2230 if (option_debug > 2)
2231 ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2232 sip_destroy(reg->call);
2234 if (reg->expire > -1)
2235 ast_sched_del(sched, reg->expire);
2236 if (reg->timeout > -1)
2237 ast_sched_del(sched, reg->timeout);
2238 ast_string_field_free_all(reg);
2244 /*! \brief Execute destrucion of SIP dialog structure, release memory */
2245 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2247 struct sip_pvt *cur, *prev = NULL;
2250 if (sip_debug_test_pvt(p) || option_debug > 2)
2251 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2253 /* Remove link from peer to subscription of MWI */
2254 if (p->relatedpeer && p->relatedpeer->mwipvt)
2255 p->relatedpeer->mwipvt = NULL;
2258 sip_dump_history(p);
2263 if (p->stateid > -1)
2264 ast_extension_state_del(p->stateid, NULL);
2266 ast_sched_del(sched, p->initid);
2267 if (p->autokillid > -1)
2268 ast_sched_del(sched, p->autokillid);
2271 ast_rtp_destroy(p->rtp);
2273 ast_rtp_destroy(p->vrtp);
2275 free_old_route(p->route);
2279 if (p->registry->call == p)
2280 p->registry->call = NULL;
2281 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2284 /* Unlink us from the owner if we have one */
2287 ast_mutex_lock(&p->owner->lock);
2289 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2290 p->owner->tech_pvt = NULL;
2292 ast_mutex_unlock(&p->owner->lock);
2296 struct sip_history *hist;
2297 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
2303 for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
2306 prev->next = cur->next;
2313 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2317 ast_sched_del(sched, p->initid);
2319 /* remove all current packets in this dialog */
2320 while((cp = p->packets)) {
2321 p->packets = p->packets->next;
2322 if (cp->retransid > -1)
2323 ast_sched_del(sched, cp->retransid);
2327 ast_variables_destroy(p->chanvars);
2330 ast_mutex_destroy(&p->lock);
2332 ast_string_field_free_all(p);
2337 /*! \brief update_call_counter: Handle call_limit for SIP users
2338 * Setting a call-limit will cause calls above the limit not to be accepted.
2340 * Remember that for a type=friend, there's one limit for the user and
2341 * another for the peer, not a combined call limit.
2342 * This will cause unexpected behaviour in subscriptions, since a "friend"
2343 * is *two* devices in Asterisk, not one.
2345 * Thought: For realtime, we should propably update storage with inuse counter...
2347 * \return 0 if call is ok (no call limit, below treshold)
2348 * -1 on rejection of call
2351 static int update_call_counter(struct sip_pvt *fup, int event)
2354 int *inuse, *call_limit;
2355 int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2356 struct sip_user *u = NULL;
2357 struct sip_peer *p = NULL;
2359 if (option_debug > 2)
2360 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2361 /* Test if we need to check call limits, in order to avoid
2362 realtime lookups if we do not need it */
2363 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2366 ast_copy_string(name, fup->username, sizeof(name));
2368 /* Check the list of users */
2369 if (!outgoing) /* Only check users for incoming calls */
2370 u = find_user(name, 1);
2374 call_limit = &u->call_limit;
2377 /* Try to find peer */
2379 p = find_peer(fup->peername, NULL, 1);
2382 call_limit = &p->call_limit;
2383 ast_copy_string(name, fup->peername, sizeof(name));
2385 if (option_debug > 1)
2386 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2391 /* incoming and outgoing affects the inUse counter */
2392 case DEC_CALL_LIMIT:
2394 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2399 if (option_debug > 1 || sipdebug) {
2400 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2403 case INC_CALL_LIMIT:
2404 if (*call_limit > 0 ) {
2405 if (*inuse >= *call_limit) {
2406 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);
2408 ASTOBJ_UNREF(u, sip_destroy_user);
2410 ASTOBJ_UNREF(p, sip_destroy_peer);
2415 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2416 if (option_debug > 1 || sipdebug) {
2417 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2421 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2424 ASTOBJ_UNREF(u, sip_destroy_user);
2426 ASTOBJ_UNREF(p, sip_destroy_peer);
2430 /*! \brief Destroy SIP call structure */
2431 static void sip_destroy(struct sip_pvt *p)
2433 ast_mutex_lock(&iflock);
2434 if (option_debug > 2)
2435 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2436 __sip_destroy(p, 1);
2437 ast_mutex_unlock(&iflock);
2440 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2441 static int hangup_sip2cause(int cause)
2443 /* Possible values taken from causes.h */
2446 case 401: /* Unauthorized */
2447 return AST_CAUSE_CALL_REJECTED;
2448 case 403: /* Not found */
2449 return AST_CAUSE_CALL_REJECTED;
2450 case 404: /* Not found */
2451 return AST_CAUSE_UNALLOCATED;
2452 case 405: /* Method not allowed */
2453 return AST_CAUSE_INTERWORKING;
2454 case 407: /* Proxy authentication required */
2455 return AST_CAUSE_CALL_REJECTED;
2456 case 408: /* No reaction */
2457 return AST_CAUSE_NO_USER_RESPONSE;
2458 case 409: /* Conflict */
2459 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2460 case 410: /* Gone */
2461 return AST_CAUSE_UNALLOCATED;
2462 case 411: /* Length required */
2463 return AST_CAUSE_INTERWORKING;
2464 case 413: /* Request entity too large */
2465 return AST_CAUSE_INTERWORKING;
2466 case 414: /* Request URI too large */
2467 return AST_CAUSE_INTERWORKING;
2468 case 415: /* Unsupported media type */
2469 return AST_CAUSE_INTERWORKING;
2470 case 420: /* Bad extension */
2471 return AST_CAUSE_NO_ROUTE_DESTINATION;
2472 case 480: /* No answer */
2473 return AST_CAUSE_FAILURE;
2474 case 481: /* No answer */
2475 return AST_CAUSE_INTERWORKING;
2476 case 482: /* Loop detected */
2477 return AST_CAUSE_INTERWORKING;
2478 case 483: /* Too many hops */
2479 return AST_CAUSE_NO_ANSWER;
2480 case 484: /* Address incomplete */
2481 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2482 case 485: /* Ambigous */
2483 return AST_CAUSE_UNALLOCATED;
2484 case 486: /* Busy everywhere */
2485 return AST_CAUSE_BUSY;
2486 case 487: /* Request terminated */
2487 return AST_CAUSE_INTERWORKING;
2488 case 488: /* No codecs approved */
2489 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2490 case 491: /* Request pending */
2491 return AST_CAUSE_INTERWORKING;
2492 case 493: /* Undecipherable */
2493 return AST_CAUSE_INTERWORKING;
2494 case 500: /* Server internal failure */
2495 return AST_CAUSE_FAILURE;
2496 case 501: /* Call rejected */
2497 return AST_CAUSE_FACILITY_REJECTED;
2499 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2500 case 503: /* Service unavailable */
2501 return AST_CAUSE_CONGESTION;
2502 case 504: /* Gateway timeout */
2503 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2504 case 505: /* SIP version not supported */
2505 return AST_CAUSE_INTERWORKING;
2506 case 600: /* Busy everywhere */
2507 return AST_CAUSE_USER_BUSY;
2508 case 603: /* Decline */
2509 return AST_CAUSE_CALL_REJECTED;
2510 case 604: /* Does not exist anywhere */
2511 return AST_CAUSE_UNALLOCATED;
2512 case 606: /* Not acceptable */
2513 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2515 return AST_CAUSE_NORMAL;
2521 /*! \brief Convert Asterisk hangup causes to SIP codes
2523 Possible values from causes.h
2524 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
2525 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
2527 In addition to these, a lot of PRI codes is defined in causes.h
2528 ...should we take care of them too ?
2532 ISUP Cause value SIP response
2533 ---------------- ------------
2534 1 unallocated number 404 Not Found
2535 2 no route to network 404 Not found
2536 3 no route to destination 404 Not found
2537 16 normal call clearing --- (*)
2538 17 user busy 486 Busy here
2539 18 no user responding 408 Request Timeout
2540 19 no answer from the user 480 Temporarily unavailable
2541 20 subscriber absent 480 Temporarily unavailable
2542 21 call rejected 403 Forbidden (+)
2543 22 number changed (w/o diagnostic) 410 Gone
2544 22 number changed (w/ diagnostic) 301 Moved Permanently
2545 23 redirection to new destination 410 Gone
2546 26 non-selected user clearing 404 Not Found (=)
2547 27 destination out of order 502 Bad Gateway
2548 28 address incomplete 484 Address incomplete
2549 29 facility rejected 501 Not implemented
2550 31 normal unspecified 480 Temporarily unavailable
2553 static const char *hangup_cause2sip(int cause)
2556 case AST_CAUSE_UNALLOCATED: /* 1 */
2557 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
2558 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
2559 return "404 Not Found";
2560 case AST_CAUSE_CONGESTION: /* 34 */
2561 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
2562 return "503 Service Unavailable";
2563 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
2564 return "408 Request Timeout";
2565 case AST_CAUSE_NO_ANSWER: /* 19 */
2566 return "480 Temporarily unavailable";
2567 case AST_CAUSE_CALL_REJECTED: /* 21 */
2568 return "403 Forbidden";
2569 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
2571 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
2572 return "480 Temporarily unavailable";
2573 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2574 return "484 Address incomplete";
2575 case AST_CAUSE_USER_BUSY:
2576 return "486 Busy here";
2577 case AST_CAUSE_FAILURE:
2578 return "500 Server internal failure";
2579 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
2580 return "501 Not Implemented";
2581 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2582 return "503 Service Unavailable";
2583 /* Used in chan_iax2 */
2584 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2585 return "502 Bad Gateway";
2586 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2587 return "488 Not Acceptable Here";
2589 case AST_CAUSE_NOTDEFINED:
2591 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2600 /*! \brief sip_hangup: Hangup SIP call
2601 * Part of PBX interface, called from ast_hangup */
2602 static int sip_hangup(struct ast_channel *ast)
2604 struct sip_pvt *p = ast->tech_pvt;
2605 int needcancel = FALSE;
2606 struct ast_flags locflags = {0};
2609 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
2612 if (option_debug && sipdebug)
2613 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2615 ast_mutex_lock(&p->lock);
2616 if (option_debug && sipdebug)
2617 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2618 update_call_counter(p, DEC_CALL_LIMIT);
2619 /* Determine how to disconnect */
2620 if (p->owner != ast) {
2621 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
2622 ast_mutex_unlock(&p->lock);
2625 /* If the call is not UP, we need to send CANCEL instead of BYE */
2626 if (ast->_state != AST_STATE_UP)
2632 ast_dsp_free(p->vad);
2635 ast->tech_pvt = NULL;
2637 ast_mutex_lock(&usecnt_lock);
2639 ast_mutex_unlock(&usecnt_lock);
2640 ast_update_use_count();
2642 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2644 /* Start the process if it's not already started */
2645 if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2646 if (needcancel) { /* Outgoing call, not up */
2647 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2648 /* stop retransmitting an INVITE that has not received a response */
2649 __sip_pretend_ack(p);
2651 /* Send a new request: CANCEL */
2652 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, 0);
2653 /* Actually don't destroy us yet, wait for the 487 on our original
2654 INVITE, but do set an autodestruct just in case we never get it. */
2655 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2657 sip_scheddestroy(p, 32000);
2658 if ( p->initid != -1 ) {
2659 /* channel still up - reverse dec of inUse counter
2660 only if the channel is not auto-congested */
2661 update_call_counter(p, INC_CALL_LIMIT);
2663 } else { /* Incoming call, not up */
2665 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
2666 transmit_response_reliable(p, res, &p->initreq);
2668 transmit_response_reliable(p, "603 Declined", &p->initreq);
2670 } else { /* Call is in UP state, send BYE */
2671 if (!p->pendinginvite) {
2673 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2675 /* Note we will need a BYE when this all settles out
2676 but we can't send one while we have "INVITE" outstanding. */
2677 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
2678 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
2682 ast_copy_flags(&p->flags[0], &locflags, SIP_NEEDDESTROY);
2683 ast_mutex_unlock(&p->lock);
2687 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
2688 static void try_suggested_sip_codec(struct sip_pvt *p)
2693 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
2697 fmt = ast_getformatbyname(codec);
2699 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n", codec);
2700 if (p->jointcapability & fmt) {
2701 p->jointcapability &= fmt;
2702 p->capability &= fmt;
2704 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2706 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
2710 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
2711 * Part of PBX interface */
2712 static int sip_answer(struct ast_channel *ast)
2715 struct sip_pvt *p = ast->tech_pvt;
2717 ast_mutex_lock(&p->lock);
2718 if (ast->_state != AST_STATE_UP) {
2719 try_suggested_sip_codec(p);
2721 ast_setstate(ast, AST_STATE_UP);
2723 ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
2724 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_RELIABLE);
2726 ast_mutex_unlock(&p->lock);
2730 /*! \brief Send frame to media channel (rtp) */
2731 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2733 struct sip_pvt *p = ast->tech_pvt;
2736 switch (frame->frametype) {
2737 case AST_FRAME_VOICE:
2738 if (!(frame->subclass & ast->nativeformats)) {
2739 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2740 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2744 ast_mutex_lock(&p->lock);
2746 /* If channel is not up, activate early media session */
2747 if ((ast->_state != AST_STATE_UP) &&
2748 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2749 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2750 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2751 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
2753 time(&p->lastrtptx);
2754 res = ast_rtp_write(p->rtp, frame);
2756 ast_mutex_unlock(&p->lock);
2759 case AST_FRAME_VIDEO:
2761 ast_mutex_lock(&p->lock);
2763 /* Activate video early media */
2764 if ((ast->_state != AST_STATE_UP) &&
2765 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2766 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2767 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2768 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
2770 time(&p->lastrtptx);
2771 res = ast_rtp_write(p->vrtp, frame);
2773 ast_mutex_unlock(&p->lock);
2776 case AST_FRAME_IMAGE:
2780 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2787 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2788 Basically update any ->owner links */
2789 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2794 if (!newchan || !newchan->tech_pvt) {
2795 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
2798 p = newchan->tech_pvt;
2800 ast_mutex_lock(&p->lock);
2801 if (p->owner != oldchan)
2802 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2805 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
2808 ast_mutex_unlock(&p->lock);
2812 /*! \brief Send DTMF character on SIP channel
2813 within one call, we're able to transmit in many methods simultaneously */
2814 static int sip_senddigit(struct ast_channel *ast, char digit)
2816 struct sip_pvt *p = ast->tech_pvt;
2819 ast_mutex_lock(&p->lock);
2820 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
2822 transmit_info_with_digit(p, digit);
2824 case SIP_DTMF_RFC2833:
2826 ast_rtp_senddigit(p->rtp, digit);
2828 case SIP_DTMF_INBAND:
2832 ast_mutex_unlock(&p->lock);
2836 /*! \brief Transfer SIP call */
2837 static int sip_transfer(struct ast_channel *ast, const char *dest)
2839 struct sip_pvt *p = ast->tech_pvt;
2842 ast_mutex_lock(&p->lock);
2843 if (ast->_state == AST_STATE_RING)
2844 res = sip_sipredirect(p, dest);
2846 res = transmit_refer(p, dest);
2847 ast_mutex_unlock(&p->lock);
2851 /*! \brief Play indication to user
2852 * With SIP a lot of indications is sent as messages, letting the device play
2853 the indication - busy signal, congestion etc
2854 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
2856 static int sip_indicate(struct ast_channel *ast, int condition)
2858 struct sip_pvt *p = ast->tech_pvt;
2861 ast_mutex_lock(&p->lock);
2863 case AST_CONTROL_RINGING:
2864 if (ast->_state == AST_STATE_RING) {
2865 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
2866 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2867 /* Send 180 ringing if out-of-band seems reasonable */
2868 transmit_response(p, "180 Ringing", &p->initreq);
2869 ast_set_flag(&p->flags[0], SIP_RINGING);
2870 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2873 /* Well, if it's not reasonable, just send in-band */
2878 case AST_CONTROL_BUSY:
2879 if (ast->_state != AST_STATE_UP) {
2880 transmit_response(p, "486 Busy Here", &p->initreq);
2881 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
2882 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2887 case AST_CONTROL_CONGESTION:
2888 if (ast->_state != AST_STATE_UP) {
2889 transmit_response(p, "503 Service Unavailable", &p->initreq);
2890 ast_set_flag(&p->flags[0], SIP_ALREADYGONE);
2891 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2896 case AST_CONTROL_PROCEEDING:
2897 if ((ast->_state != AST_STATE_UP) &&
2898 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2899 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2900 transmit_response(p, "100 Trying", &p->initreq);
2905 case AST_CONTROL_PROGRESS:
2906 if ((ast->_state != AST_STATE_UP) &&
2907 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2908 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2909 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2910 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
2915 case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
2917 ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
2920 case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
2922 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2925 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
2926 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
2927 transmit_info_with_vidupdate(p);
2928 /* ast_rtcp_send_h261fur(p->vrtp); */
2937 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2941 ast_mutex_unlock(&p->lock);
2947 /*! \brief Initiate a call in the SIP channel
2948 called from sip_request_call (calls from the pbx ) */
2949 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
2951 struct ast_channel *tmp;
2952 struct ast_variable *v = NULL;
2956 ast_mutex_unlock(&i->lock);
2957 /* Don't hold a sip pvt lock while we allocate a channel */
2958 tmp = ast_channel_alloc(1);
2959 ast_mutex_lock(&i->lock);
2961 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2964 tmp->tech = &sip_tech;
2965 /* Select our native format based on codec preference until we receive
2966 something from another device to the contrary. */
2967 if (i->jointcapability)
2968 what = i->jointcapability;
2969 else if (i->capability)
2970 what = i->capability;
2972 what = global_capability;
2973 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
2974 fmt = ast_best_codec(tmp->nativeformats);
2977 ast_string_field_build(tmp, name, "SIP/%s-%04lx", title, ast_random() & 0xffff);
2978 else if (strchr(i->fromdomain,':'))
2979 ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2981 ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2983 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
2984 i->vad = ast_dsp_new();
2985 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2986 if (global_relaxdtmf)
2987 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2990 tmp->fds[0] = ast_rtp_fd(i->rtp);
2991 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2994 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2995 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2997 if (state == AST_STATE_RING)
2999 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3000 tmp->writeformat = fmt;
3001 tmp->rawwriteformat = fmt;
3002 tmp->readformat = fmt;
3003 tmp->rawreadformat = fmt;
3006 tmp->callgroup = i->callgroup;
3007 tmp->pickupgroup = i->pickupgroup;
3008 tmp->cid.cid_pres = i->callingpres;
3009 if (!ast_strlen_zero(i->accountcode))
3010 ast_string_field_set(tmp, accountcode, i->accountcode);
3012 tmp->amaflags = i->amaflags;
3013 if (!ast_strlen_zero(i->language))
3014 ast_string_field_set(tmp, language, i->language);
3015 if (!ast_strlen_zero(i->musicclass))
3016 ast_string_field_set(tmp, musicclass, i->musicclass);
3018 ast_mutex_lock(&usecnt_lock);
3020 ast_mutex_unlock(&usecnt_lock);
3021 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3022 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3023 if (!ast_strlen_zero(i->cid_num))
3024 tmp->cid.cid_num = ast_strdup(i->cid_num);
3025 if (!ast_strlen_zero(i->cid_name))
3026 tmp->cid.cid_name = ast_strdup(i->cid_name);
3027 if (!ast_strlen_zero(i->rdnis))