As pointed out on the -dev list, actually use the result of find_peer() so that
[asterisk-bristuff.git] / channels / chan_sip.c
blob83b9a7ebb3a1f5d6c3620290733e3eac35d6299f
1 /*
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.
19 /*!
20 * \file
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
25 * See Also:
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
31 * ********** IMPORTANT *
32 * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33 * settings, dialplan commands and dialplans apps/functions
36 * TODO:s
37 * \todo Better support of forking
38 * \todo VIA branch tag transaction checking
39 * \todo Transaction support
40 * \todo We need to test TCP sessions with SIP proxies and in regards
41 * to the SIP outbound specs.
42 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
43 * \todo Save TCP/TLS sessions in registry
44 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
46 * \ingroup channel_drivers
48 * \par Overview of the handling of SIP sessions
49 * The SIP channel handles several types of SIP sessions, or dialogs,
50 * not all of them being "telephone calls".
51 * - Incoming calls that will be sent to the PBX core
52 * - Outgoing calls, generated by the PBX
53 * - SIP subscriptions and notifications of states and voicemail messages
54 * - SIP registrations, both inbound and outbound
55 * - SIP peer management (peerpoke, OPTIONS)
56 * - SIP text messages
58 * In the SIP channel, there's a list of active SIP dialogs, which includes
59 * all of these when they are active. "sip show channels" in the CLI will
60 * show most of these, excluding subscriptions which are shown by
61 * "sip show subscriptions"
63 * \par incoming packets
64 * Incoming packets are received in the monitoring thread, then handled by
65 * sipsock_read(). This function parses the packet and matches an existing
66 * dialog or starts a new SIP dialog.
68 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
69 * If it is a response to an outbound request, the packet is sent to handle_response().
70 * If it is a request, handle_incoming() sends it to one of a list of functions
71 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
72 * sipsock_read locks the ast_channel if it exists (an active call) and
73 * unlocks it after we have processed the SIP message.
75 * A new INVITE is sent to handle_request_invite(), that will end up
76 * starting a new channel in the PBX, the new channel after that executing
77 * in a separate channel thread. This is an incoming "call".
78 * When the call is answered, either by a bridged channel or the PBX itself
79 * the sip_answer() function is called.
81 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
82 * in rtp.c
84 * \par Outbound calls
85 * Outbound calls are set up by the PBX through the sip_request_call()
86 * function. After that, they are activated by sip_call().
88 * \par Hanging up
89 * The PBX issues a hangup on both incoming and outgoing calls through
90 * the sip_hangup() function
93 /*** MODULEINFO
94 <depend>chan_local</depend>
95 ***/
97 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
99 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
100 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
101 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
102 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
103 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
104 that do not support Session-Timers).
106 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
107 per-peer settings override the global settings. The following new parameters have been
108 added to the sip.conf file.
109 session-timers=["accept", "originate", "refuse"]
110 session-expires=[integer]
111 session-minse=[integer]
112 session-refresher=["uas", "uac"]
114 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
115 Asterisk. The Asterisk can be configured in one of the following three modes:
117 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
118 made by remote end-points. A remote end-point can request Asterisk to engage
119 session-timers by either sending it an INVITE request with a "Supported: timer"
120 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
121 Session-Expires: header in it. In this mode, the Asterisk server does not
122 request session-timers from remote end-points. This is the default mode.
123 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
124 end-points to activate session-timers in addition to honoring such requests
125 made by the remote end-pints. In order to get as much protection as possible
126 against hanging SIP channels due to network or end-point failures, Asterisk
127 resends periodic re-INVITEs even if a remote end-point does not support
128 the session-timers feature.
129 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
130 timers for inbound or outbound requests. If a remote end-point requests
131 session-timers in a dialog, then Asterisk ignores that request unless it's
132 noted as a requirement (Require: header), in which case the INVITE is
133 rejected with a 420 Bad Extension response.
137 #include "asterisk.h"
139 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
141 #include <ctype.h>
142 #include <sys/ioctl.h>
143 #include <fcntl.h>
144 #include <signal.h>
145 #include <sys/signal.h>
146 #include <regex.h>
147 #include <time.h>
149 #include "asterisk/network.h"
150 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
152 #include "asterisk/lock.h"
153 #include "asterisk/channel.h"
154 #include "asterisk/config.h"
155 #include "asterisk/module.h"
156 #include "asterisk/pbx.h"
157 #include "asterisk/sched.h"
158 #include "asterisk/io.h"
159 #include "asterisk/rtp.h"
160 #include "asterisk/udptl.h"
161 #include "asterisk/acl.h"
162 #include "asterisk/manager.h"
163 #include "asterisk/callerid.h"
164 #include "asterisk/cli.h"
165 #include "asterisk/app.h"
166 #include "asterisk/musiconhold.h"
167 #include "asterisk/dsp.h"
168 #include "asterisk/features.h"
169 #include "asterisk/srv.h"
170 #include "asterisk/astdb.h"
171 #include "asterisk/causes.h"
172 #include "asterisk/utils.h"
173 #include "asterisk/file.h"
174 #include "asterisk/astobj.h"
176 Uncomment the define below, if you are having refcount related memory leaks.
177 With this uncommented, this module will generate a file, /tmp/refs, which contains
178 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
179 be modified to ao2_t_* calls, and include a tag describing what is happening with
180 enough detail, to make pairing up a reference count increment with its corresponding decrement.
181 The refcounter program in utils/ can be invaluable in highlighting objects that are not
182 balanced, along with the complete history for that object.
183 In normal operation, the macros defined will throw away the tags, so they do not
184 affect the speed of the program at all. They can be considered to be documentation.
186 /* #define REF_DEBUG 1 */
187 #include "asterisk/astobj2.h"
188 #include "asterisk/dnsmgr.h"
189 #include "asterisk/devicestate.h"
190 #include "asterisk/linkedlists.h"
191 #include "asterisk/stringfields.h"
192 #include "asterisk/monitor.h"
193 #include "asterisk/netsock.h"
194 #include "asterisk/localtime.h"
195 #include "asterisk/abstract_jb.h"
196 #include "asterisk/threadstorage.h"
197 #include "asterisk/translate.h"
198 #include "asterisk/ast_version.h"
199 #include "asterisk/event.h"
200 #include "asterisk/tcptls.h"
202 #ifndef FALSE
203 #define FALSE 0
204 #endif
206 #ifndef TRUE
207 #define TRUE 1
208 #endif
210 #define SIPBUFSIZE 512
212 #define XMIT_ERROR -2
214 /* #define VOCAL_DATA_HACK */
216 #define DEFAULT_DEFAULT_EXPIRY 120
217 #define DEFAULT_MIN_EXPIRY 60
218 #define DEFAULT_MAX_EXPIRY 3600
219 #define DEFAULT_REGISTRATION_TIMEOUT 20
220 #define DEFAULT_MAX_FORWARDS "70"
222 /* guard limit must be larger than guard secs */
223 /* guard min must be < 1000, and should be >= 250 */
224 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
225 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
226 EXPIRY_GUARD_SECS */
227 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
228 GUARD_PCT turns out to be lower than this, it
229 will use this time instead.
230 This is in milliseconds. */
231 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
232 below EXPIRY_GUARD_LIMIT */
233 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
235 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
236 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
237 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
239 #ifndef MAX
240 #define MAX(a,b) ((a) > (b) ? (a) : (b))
241 #endif
243 #define CALLERID_UNKNOWN "Unknown"
245 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
246 #define DEFAULT_QUALIFYFREQ 60 * 1000 /*!< Qualification: How often to check for the host to be up */
247 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
249 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
250 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
251 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
252 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1
253 \todo Use known T1 for timeout (peerpoke)
255 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
256 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
258 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
259 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
260 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
261 #define SIP_MIN_PACKET 1024 /*!< Initialize size of memory to allocate for packets */
263 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
265 #define DEFAULT_MAX_SE 1800 /*!< Session-Timer Default Session-Expires period (RFC 4028) */
266 #define DEFAULT_MIN_SE 90 /*!< Session-Timer Default Min-SE period (RFC 4028) */
268 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
270 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
271 static struct ast_jb_conf default_jbconf =
273 .flags = 0,
274 .max_size = -1,
275 .resync_threshold = -1,
276 .impl = ""
278 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
280 static const char config[] = "sip.conf"; /*!< Main configuration file */
281 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
283 #define RTP 1
284 #define NO_RTP 0
286 /*! \brief Authorization scheme for call transfers
287 \note Not a bitfield flag, since there are plans for other modes,
288 like "only allow transfers for authenticated devices" */
289 enum transfermodes {
290 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
291 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
295 /*! \brief The result of a lot of functions */
296 enum sip_result {
297 AST_SUCCESS = 0, /*! FALSE means success, funny enough */
298 AST_FAILURE = -1,
301 /*! \brief States for the INVITE transaction, not the dialog
302 \note this is for the INVITE that sets up the dialog
304 enum invitestates {
305 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
306 INV_CALLING = 1, /*!< Invite sent, no answer */
307 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
308 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
309 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
310 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
311 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
312 The only way out of this is a BYE from one side */
313 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
316 /*! \brief Readable descriptions of device states.
317 \note Should be aligned to above table as index */
318 static const struct invstate2stringtable {
319 const enum invitestates state;
320 const char *desc;
321 } invitestate2string[] = {
322 {INV_NONE, "None" },
323 {INV_CALLING, "Calling (Trying)"},
324 {INV_PROCEEDING, "Proceeding "},
325 {INV_EARLY_MEDIA, "Early media"},
326 {INV_COMPLETED, "Completed (done)"},
327 {INV_CONFIRMED, "Confirmed (up)"},
328 {INV_TERMINATED, "Done"},
329 {INV_CANCELLED, "Cancelled"}
332 /*! \brief When sending a SIP message, we can send with a few options, depending on
333 type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
334 where the original response would be sent RELIABLE in an INVITE transaction */
335 enum xmittype {
336 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
337 If it fails, it's critical and will cause a teardown of the session */
338 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
339 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
342 enum parse_register_result {
343 PARSE_REGISTER_FAILED,
344 PARSE_REGISTER_UPDATE,
345 PARSE_REGISTER_QUERY,
348 /*! \brief Type of subscription, based on the packages we do support */
349 enum subscriptiontype {
350 NONE = 0,
351 XPIDF_XML,
352 DIALOG_INFO_XML,
353 CPIM_PIDF_XML,
354 PIDF_XML,
355 MWI_NOTIFICATION
358 /*! \brief Subscription types that we support. We support
359 - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
360 - SIMPLE presence used for device status
361 - Voicemail notification subscriptions
363 static const struct cfsubscription_types {
364 enum subscriptiontype type;
365 const char * const event;
366 const char * const mediatype;
367 const char * const text;
368 } subscription_types[] = {
369 { NONE, "-", "unknown", "unknown" },
370 /* RFC 4235: SIP Dialog event package */
371 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
372 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
373 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
374 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
375 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
379 /*! \brief Authentication types - proxy or www authentication
380 \note Endpoints, like Asterisk, should always use WWW authentication to
381 allow multiple authentications in the same call - to the proxy and
382 to the end point.
384 enum sip_auth_type {
385 PROXY_AUTH = 407,
386 WWW_AUTH = 401,
389 /*! \brief Authentication result from check_auth* functions */
390 enum check_auth_result {
391 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
392 /* XXX maybe this is the same as AUTH_NOT_FOUND */
394 AUTH_SUCCESSFUL = 0,
395 AUTH_CHALLENGE_SENT = 1,
396 AUTH_SECRET_FAILED = -1,
397 AUTH_USERNAME_MISMATCH = -2,
398 AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
399 AUTH_FAKE_AUTH = -4,
400 AUTH_UNKNOWN_DOMAIN = -5,
401 AUTH_PEER_NOT_DYNAMIC = -6,
402 AUTH_ACL_FAILED = -7,
403 AUTH_BAD_TRANSPORT = -8,
406 /*! \brief States for outbound registrations (with register= lines in sip.conf */
407 enum sipregistrystate {
408 REG_STATE_UNREGISTERED = 0, /*!< We are not registred
409 * \note Initial state. We should have a timeout scheduled for the initial
410 * (or next) registration transmission, calling sip_reregister
413 REG_STATE_REGSENT, /*!< Registration request sent
414 * \note sent initial request, waiting for an ack or a timeout to
415 * retransmit the initial request.
418 REG_STATE_AUTHSENT, /*!< We have tried to authenticate
419 * \note entered after transmit_register with auth info,
420 * waiting for an ack.
423 REG_STATE_REGISTERED, /*!< Registered and done */
425 REG_STATE_REJECTED, /*!< Registration rejected *
426 * \note only used when the remote party has an expire larger than
427 * our max-expire. This is a final state from which we do not
428 * recover (not sure how correctly).
431 REG_STATE_TIMEOUT, /*!< Registration timed out *
432 * \note XXX unused */
434 REG_STATE_NOAUTH, /*!< We have no accepted credentials
435 * \note fatal - no chance to proceed */
437 REG_STATE_FAILED, /*!< Registration failed after several tries
438 * \note fatal - no chance to proceed */
441 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
442 enum st_mode {
443 SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */
444 SESSION_TIMER_MODE_ACCEPT, /*!< Honor inbound Session-Timer requests */
445 SESSION_TIMER_MODE_ORIGINATE, /*!< Originate outbound and honor inbound requests */
446 SESSION_TIMER_MODE_REFUSE /*!< Ignore inbound Session-Timers requests */
449 /*! \brief The entity playing the refresher role for Session-Timers */
450 enum st_refresher {
451 SESSION_TIMER_REFRESHER_AUTO, /*!< Negotiated */
452 SESSION_TIMER_REFRESHER_UAC, /*!< Session is refreshed by the UAC */
453 SESSION_TIMER_REFRESHER_UAS /*!< Session is refreshed by the UAS */
456 /*! \brief Define some implemented SIP transports
457 \note Asterisk does not support SCTP or UDP/DTLS
459 enum sip_transport {
460 SIP_TRANSPORT_UDP = 1, /*!< Unreliable transport for SIP, needs retransmissions */
461 SIP_TRANSPORT_TCP = 1 << 1, /*!< Reliable, but unsecure */
462 SIP_TRANSPORT_TLS = 1 << 2, /*!< TCP/TLS - reliable and secure transport for signalling */
465 /*! \brief definition of a sip proxy server
467 * For outbound proxies, this is allocated in the SIP peer dynamically or
468 * statically as the global_outboundproxy. The pointer in a SIP message is just
469 * a pointer and should *not* be de-allocated.
471 struct sip_proxy {
472 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
473 struct sockaddr_in ip; /*!< Currently used IP address and port */
474 time_t last_dnsupdate; /*!< When this was resolved */
475 enum sip_transport transport;
476 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
477 /* Room for a SRV record chain based on the name */
480 /*! \brief argument for the 'show channels|subscriptions' callback. */
481 struct __show_chan_arg {
482 int fd;
483 int subscriptions;
484 int numchans; /* return value */
488 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
489 enum can_create_dialog {
490 CAN_NOT_CREATE_DIALOG,
491 CAN_CREATE_DIALOG,
492 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
495 /*! \brief SIP Request methods known by Asterisk
497 \note Do _NOT_ make any changes to this enum, or the array following it;
498 if you think you are doing the right thing, you are probably
499 not doing the right thing. If you think there are changes
500 needed, get someone else to review them first _before_
501 submitting a patch. If these two lists do not match properly
502 bad things will happen.
505 enum sipmethod {
506 SIP_UNKNOWN, /*!< Unknown response */
507 SIP_RESPONSE, /*!< Not request, response to outbound request */
508 SIP_REGISTER, /*!< Registration to the mothership, tell us where you are located */
509 SIP_OPTIONS, /*!< Check capabilities of a device, used for "ping" too */
510 SIP_NOTIFY, /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
511 SIP_INVITE, /*!< Set up a session */
512 SIP_ACK, /*!< End of a three-way handshake started with INVITE. */
513 SIP_PRACK, /*!< Reliable pre-call signalling. Not supported in Asterisk. */
514 SIP_BYE, /*!< End of a session */
515 SIP_REFER, /*!< Refer to another URI (transfer) */
516 SIP_SUBSCRIBE, /*!< Subscribe for updates (voicemail, session status, device status, presence) */
517 SIP_MESSAGE, /*!< Text messaging */
518 SIP_UPDATE, /*!< Update a dialog. We can send UPDATE; but not accept it */
519 SIP_INFO, /*!< Information updates during a session */
520 SIP_CANCEL, /*!< Cancel an INVITE */
521 SIP_PUBLISH, /*!< Not supported in Asterisk */
522 SIP_PING, /*!< Not supported at all, no standard but still implemented out there */
525 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
526 structure and then route the messages according to the type.
528 \note Note that sip_methods[i].id == i must hold or the code breaks */
529 static const struct cfsip_methods {
530 enum sipmethod id;
531 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
532 char * const text;
533 enum can_create_dialog can_create;
534 } sip_methods[] = {
535 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
536 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
537 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
538 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
539 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
540 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
541 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
542 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
543 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
544 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
545 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
546 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
547 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
548 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
549 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
550 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
551 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
554 /*! Define SIP option tags, used in Require: and Supported: headers
555 We need to be aware of these properties in the phones to use
556 the replace: header. We should not do that without knowing
557 that the other end supports it...
558 This is nothing we can configure, we learn by the dialog
559 Supported: header on the REGISTER (peer) or the INVITE
560 (other devices)
561 We are not using many of these today, but will in the future.
562 This is documented in RFC 3261
564 #define SUPPORTED 1
565 #define NOT_SUPPORTED 0
567 /* SIP options */
568 #define SIP_OPT_REPLACES (1 << 0)
569 #define SIP_OPT_100REL (1 << 1)
570 #define SIP_OPT_TIMER (1 << 2)
571 #define SIP_OPT_EARLY_SESSION (1 << 3)
572 #define SIP_OPT_JOIN (1 << 4)
573 #define SIP_OPT_PATH (1 << 5)
574 #define SIP_OPT_PREF (1 << 6)
575 #define SIP_OPT_PRECONDITION (1 << 7)
576 #define SIP_OPT_PRIVACY (1 << 8)
577 #define SIP_OPT_SDP_ANAT (1 << 9)
578 #define SIP_OPT_SEC_AGREE (1 << 10)
579 #define SIP_OPT_EVENTLIST (1 << 11)
580 #define SIP_OPT_GRUU (1 << 12)
581 #define SIP_OPT_TARGET_DIALOG (1 << 13)
582 #define SIP_OPT_NOREFERSUB (1 << 14)
583 #define SIP_OPT_HISTINFO (1 << 15)
584 #define SIP_OPT_RESPRIORITY (1 << 16)
585 #define SIP_OPT_FROMCHANGE (1 << 17)
586 #define SIP_OPT_RECLISTINV (1 << 18)
587 #define SIP_OPT_RECLISTSUB (1 << 19)
588 #define SIP_OPT_UNKNOWN (1 << 20)
591 /*! \brief List of well-known SIP options. If we get this in a require,
592 we should check the list and answer accordingly. */
593 static const struct cfsip_options {
594 int id; /*!< Bitmap ID */
595 int supported; /*!< Supported by Asterisk ? */
596 char * const text; /*!< Text id, as in standard */
597 } sip_options[] = { /* XXX used in 3 places */
598 /* RFC3262: PRACK 100% reliability */
599 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
600 /* RFC3959: SIP Early session support */
601 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
602 /* SIMPLE events: RFC4662 */
603 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
604 /* RFC 4916- Connected line ID updates */
605 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
606 /* GRUU: Globally Routable User Agent URI's */
607 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
608 /* RFC4244 History info */
609 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
610 /* RFC3911: SIP Join header support */
611 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
612 /* Disable the REFER subscription, RFC 4488 */
613 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
614 /* RFC3327: Path support */
615 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
616 /* RFC3840: Callee preferences */
617 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
618 /* RFC3312: Precondition support */
619 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
620 /* RFC3323: Privacy with proxies*/
621 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
622 /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
623 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
624 /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
625 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
626 /* RFC3891: Replaces: header for transfer */
627 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
628 /* One version of Polycom firmware has the wrong label */
629 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
630 /* RFC4412 Resource priorities */
631 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
632 /* RFC3329: Security agreement mechanism */
633 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
634 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
635 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
636 /* RFC4028: SIP Session-Timers */
637 { SIP_OPT_TIMER, SUPPORTED, "timer" },
638 /* RFC4538: Target-dialog */
639 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
643 /*! \brief SIP Methods we support
644 \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
645 allowsubscribe and allowrefer on in sip.conf.
647 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
649 /*! \brief SIP Extensions we support
650 \note This should be generated based on the previous array
651 in combination with settings.
652 \todo We should not have "timer" if it's disabled in the configuration file.
654 #define SUPPORTED_EXTENSIONS "replaces, timer"
656 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
657 #define STANDARD_SIP_PORT 5060
658 /*! \brief Standard SIP TLS port for sips: from RFC 3261. DO NOT CHANGE THIS */
659 #define STANDARD_TLS_PORT 5061
661 /*! \note in many SIP headers, absence of a port number implies port 5060,
662 * and this is why we cannot change the above constant.
663 * There is a limited number of places in asterisk where we could,
664 * in principle, use a different "default" port number, but
665 * we do not support this feature at the moment.
666 * You can run Asterisk with SIP on a different port with a configuration
667 * option. If you change this value, the signalling will be incorrect.
670 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
672 These are default values in the source. There are other recommended values in the
673 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
674 yet encouraging new behaviour on new installations
676 /*@{*/
677 #define DEFAULT_CONTEXT "default"
678 #define DEFAULT_MOHINTERPRET "default"
679 #define DEFAULT_MOHSUGGEST ""
680 #define DEFAULT_VMEXTEN "asterisk"
681 #define DEFAULT_CALLERID "asterisk"
682 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
683 #define DEFAULT_ALLOWGUEST TRUE
684 #define DEFAULT_CALLCOUNTER FALSE
685 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
686 #define DEFAULT_COMPACTHEADERS FALSE
687 #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. */
688 #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. */
689 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
690 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
691 #define DEFAULT_COS_SIP 4 /*!< Level 2 class of service for SIP signalling */
692 #define DEFAULT_COS_AUDIO 5 /*!< Level 2 class of service for audio media */
693 #define DEFAULT_COS_VIDEO 6 /*!< Level 2 class of service for video media */
694 #define DEFAULT_COS_TEXT 5 /*!< Level 2 class of service for text media (T.140) */
695 #define DEFAULT_ALLOW_EXT_DOM TRUE /*!< Allow external domains */
696 #define DEFAULT_REALM "asterisk" /*!< Realm for HTTP digest authentication */
697 #define DEFAULT_NOTIFYRINGING TRUE
698 #define DEFAULT_PEDANTIC FALSE
699 #define DEFAULT_AUTOCREATEPEER FALSE
700 #define DEFAULT_QUALIFY FALSE
701 #define DEFAULT_REGEXTENONQUALIFY FALSE
702 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
703 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
704 #ifndef DEFAULT_USERAGENT
705 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
706 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
707 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
708 #endif
709 /*@}*/
711 /*! \name DefaultSettings
712 Default setttings are used as a channel setting and as a default when
713 configuring devices
715 /*@{*/
716 static char default_context[AST_MAX_CONTEXT];
717 static char default_subscribecontext[AST_MAX_CONTEXT];
718 static char default_language[MAX_LANGUAGE];
719 static char default_callerid[AST_MAX_EXTENSION];
720 static char default_fromdomain[AST_MAX_EXTENSION];
721 static char default_notifymime[AST_MAX_EXTENSION];
722 static int default_qualify; /*!< Default Qualify= setting */
723 static char default_vmexten[AST_MAX_EXTENSION];
724 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
725 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
726 * a bridged channel on hold */
727 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
728 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
729 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
731 /*! \brief a place to store all global settings for the sip channel driver */
732 struct sip_settings {
733 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
734 int rtsave_sysname; /*!< G: Save system name at registration? */
735 int ignore_regexpire; /*!< G: Ignore expiration of peer */
738 static struct sip_settings sip_cfg;
739 /*@}*/
741 /*! \name GlobalSettings
742 Global settings apply to the channel (often settings you can change in the general section
743 of sip.conf
745 /*@{*/
746 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
747 static int global_rtautoclear; /*!< Realtime ?? */
748 static int global_notifyringing; /*!< Send notifications on ringing */
749 static int global_notifyhold; /*!< Send notifications on hold */
750 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
751 static int global_srvlookup; /*!< SRV Lookup on or off. Default is on */
752 static int pedanticsipchecking; /*!< Extra checking ? Default off */
753 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
754 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
755 static int global_relaxdtmf; /*!< Relax DTMF */
756 static int global_rtptimeout; /*!< Time out call if no RTP */
757 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
758 static int global_rtpkeepalive; /*!< Send RTP keepalives */
759 static int global_reg_timeout;
760 static int global_regattempts_max; /*!< Registration attempts before giving up */
761 static int global_allowguest; /*!< allow unauthenticated peers to connect? */
762 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
763 call-limit to 999. When we remove the call-limit from the code, we can make it
764 with just a boolean flag in the device structure */
765 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
766 the global setting is in globals_flags[1] */
767 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
768 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
769 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
770 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
771 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
772 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
773 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
774 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
775 static int compactheaders; /*!< send compact sip headers */
776 static int recordhistory; /*!< Record SIP history. Off by default */
777 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
778 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
779 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
780 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
781 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
782 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
783 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
784 static int global_callevents; /*!< Whether we send manager events or not */
785 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
786 static int global_t1; /*!< T1 time */
787 static int global_t1min; /*!< T1 roundtrip time minimum */
788 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
789 static int global_regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
790 static int global_autoframing; /*!< Turn autoframing on or off. */
791 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
792 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
793 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
794 static int global_qualifyfreq; /*!< Qualify frequency */
797 /*! \brief Codecs that we support by default: */
798 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
800 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
801 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
802 static int global_min_se; /*!< Lowest threshold for session refresh interval */
803 static int global_max_se; /*!< Highest threshold for session refresh interval */
805 /*@}*/
807 /*! \name Object counters @{
808 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
809 * should be used to modify these values. */
810 static int speerobjs = 0; /*!< Static peers */
811 static int rpeerobjs = 0; /*!< Realtime peers */
812 static int apeerobjs = 0; /*!< Autocreated peer objects */
813 static int regobjs = 0; /*!< Registry objects */
814 /* }@ */
816 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
817 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
820 AST_MUTEX_DEFINE_STATIC(netlock);
822 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
823 when it's doing something critical. */
824 AST_MUTEX_DEFINE_STATIC(monlock);
826 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
828 /*! \brief This is the thread for the monitor which checks for input on the channels
829 which are not currently in use. */
830 static pthread_t monitor_thread = AST_PTHREADT_NULL;
832 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
833 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
835 static struct sched_context *sched; /*!< The scheduling context */
836 static struct io_context *io; /*!< The IO context */
837 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
839 #define DEC_CALL_LIMIT 0
840 #define INC_CALL_LIMIT 1
841 #define DEC_CALL_RINGING 2
842 #define INC_CALL_RINGING 3
844 /*! \brief The SIP socket definition */
845 struct sip_socket {
846 enum sip_transport type; /*!< UDP, TCP or TLS */
847 int fd; /*!< Filed descriptor, the actual socket */
848 uint16_t port;
849 struct ast_tcptls_session_instance *ser; /* If tcp or tls, a socket manager */
852 /*! \brief sip_request: The data grabbed from the UDP socket
854 * \verbatim
855 * Incoming messages: we first store the data from the socket in data[],
856 * adding a trailing \0 to make string parsing routines happy.
857 * Then call parse_request() and req.method = find_sip_method();
858 * to initialize the other fields. The \r\n at the end of each line is
859 * replaced by \0, so that data[] is not a conforming SIP message anymore.
860 * After this processing, rlPart1 is set to non-NULL to remember
861 * that we can run get_header() on this kind of packet.
863 * parse_request() splits the first line as follows:
864 * Requests have in the first line method uri SIP/2.0
865 * rlPart1 = method; rlPart2 = uri;
866 * Responses have in the first line SIP/2.0 NNN description
867 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
869 * For outgoing packets, we initialize the fields with init_req() or init_resp()
870 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
871 * and then fill the rest with add_header() and add_line().
872 * The \r\n at the end of the line are still there, so the get_header()
873 * and similar functions don't work on these packets.
874 * \endverbatim
876 struct sip_request {
877 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
878 char *rlPart2; /*!< The Request URI or Response Status */
879 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
880 int headers; /*!< # of SIP Headers */
881 int method; /*!< Method of this request */
882 int lines; /*!< Body Content */
883 unsigned int sdp_start; /*!< the line number where the SDP begins */
884 unsigned int sdp_end; /*!< the line number where the SDP ends */
885 char debug; /*!< print extra debugging if non zero */
886 char has_to_tag; /*!< non-zero if packet has To: tag */
887 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
888 char *header[SIP_MAX_HEADERS];
889 char *line[SIP_MAX_LINES];
890 struct ast_str *data;
891 /* XXX Do we need to unref socket.ser when the request goes away? */
892 struct sip_socket socket; /*!< The socket used for this request */
895 /*! \brief structure used in transfers */
896 struct sip_dual {
897 struct ast_channel *chan1; /*!< First channel involved */
898 struct ast_channel *chan2; /*!< Second channel involved */
899 struct sip_request req; /*!< Request that caused the transfer (REFER) */
900 int seqno; /*!< Sequence number */
903 struct sip_pkt;
905 /*! \brief Parameters to the transmit_invite function */
906 struct sip_invite_param {
907 int addsipheaders; /*!< Add extra SIP headers */
908 const char *uri_options; /*!< URI options to add to the URI */
909 const char *vxml_url; /*!< VXML url for Cisco phones */
910 char *auth; /*!< Authentication */
911 char *authheader; /*!< Auth header */
912 enum sip_auth_type auth_type; /*!< Authentication type */
913 const char *replaces; /*!< Replaces header for call transfers */
914 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
917 /*! \brief Structure to save routing information for a SIP session */
918 struct sip_route {
919 struct sip_route *next;
920 char hop[0];
923 /*! \brief Modes for SIP domain handling in the PBX */
924 enum domain_mode {
925 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
926 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
929 /*! \brief Domain data structure.
930 \note In the future, we will connect this to a configuration tree specific
931 for this domain
933 struct domain {
934 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
935 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
936 enum domain_mode mode; /*!< How did we find this domain? */
937 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
940 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
943 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
944 struct sip_history {
945 AST_LIST_ENTRY(sip_history) list;
946 char event[0]; /* actually more, depending on needs */
949 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
951 /*! \brief sip_auth: Credentials for authentication to other SIP services */
952 struct sip_auth {
953 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
954 char username[256]; /*!< Username */
955 char secret[256]; /*!< Secret */
956 char md5secret[256]; /*!< MD5Secret */
957 struct sip_auth *next; /*!< Next auth structure in list */
960 /*! \name SIPflags
961 Various flags for the flags field in the pvt structure
962 Trying to sort these up (one or more of the following):
963 D: Dialog
964 P: Peer/user
965 G: Global flag
966 When flags are used by multiple structures, it is important that
967 they have a common layout so it is easy to copy them.
969 /*@{*/
970 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
971 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
972 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
973 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
974 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
975 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
976 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
977 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
978 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
979 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10) /*!< D: Do not hangup at first ast_hangup */
981 #define SIP_PROMISCREDIR (1 << 11) /*!< DP: Promiscuous redirection */
982 #define SIP_TRUSTRPID (1 << 12) /*!< DP: Trust RPID headers? */
983 #define SIP_USEREQPHONE (1 << 13) /*!< DP: Add user=phone to numeric URI. Default off */
984 #define SIP_USECLIENTCODE (1 << 14) /*!< DP: Trust X-ClientCode info message */
986 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
987 #define SIP_DTMF (7 << 15) /*!< DP: DTMF Support: five settings, uses three bits */
988 #define SIP_DTMF_RFC2833 (0 << 15) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
989 #define SIP_DTMF_INBAND (1 << 15) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
990 #define SIP_DTMF_INFO (2 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" */
991 #define SIP_DTMF_AUTO (3 << 15) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
992 #define SIP_DTMF_SHORTINFO (4 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
994 /* NAT settings - see nat2str() */
995 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
996 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
997 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
998 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
999 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
1001 /* re-INVITE related settings */
1002 #define SIP_REINVITE (7 << 20) /*!< DP: four settings, uses three bits */
1003 #define SIP_REINVITE_NONE (0 << 20) /*!< DP: no reinvite allowed */
1004 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
1005 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
1006 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
1008 /* "insecure" settings - see insecure2str() */
1009 #define SIP_INSECURE (3 << 23) /*!< DP: three settings, uses two bits */
1010 #define SIP_INSECURE_NONE (0 << 23) /*!< DP: secure mode */
1011 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
1012 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
1014 /* Sending PROGRESS in-band settings */
1015 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
1016 #define SIP_PROG_INBAND_NEVER (0 << 25)
1017 #define SIP_PROG_INBAND_NO (1 << 25)
1018 #define SIP_PROG_INBAND_YES (2 << 25)
1020 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
1021 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
1023 /*! \brief Flags to copy from peer/user to dialog */
1024 #define SIP_FLAGS_TO_COPY \
1025 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
1026 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
1027 SIP_USEREQPHONE | SIP_INSECURE)
1028 /*@}*/
1030 /*! \name SIPflags2
1031 a second page of flags (for flags[1] */
1032 /*@{*/
1033 /* realtime flags */
1034 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
1035 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
1036 /* Space for addition of other realtime flags in the future */
1037 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
1039 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14) /*!< DP: Video supported if offered? */
1040 #define SIP_PAGE2_TEXTSUPPORT (1 << 15) /*!< GDP: Global text enable */
1041 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
1042 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
1043 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
1045 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
1046 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
1047 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1048 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1050 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
1051 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
1052 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
1053 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
1055 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
1056 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
1057 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
1058 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30) /*!< DP: Use source IP of RTP as destination if NAT is enabled */
1060 #define SIP_PAGE2_FLAGS_TO_COPY \
1061 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
1062 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
1063 SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_UDPTL_DESTINATION)
1065 /*@}*/
1067 /*! \name SIPflagsT38
1068 T.38 set of flags */
1070 /*@{*/
1071 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
1072 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
1073 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
1074 /* Rate management */
1075 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
1076 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
1077 /* UDP Error correction */
1078 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
1079 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
1080 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
1081 /* T38 Spec version */
1082 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
1083 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
1084 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
1085 /* Maximum Fax Rate */
1086 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
1087 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
1088 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
1089 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
1090 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
1091 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
1093 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
1094 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
1095 /*@}*/
1097 /*! \brief debugging state
1098 * We store separately the debugging requests from the config file
1099 * and requests from the CLI. Debugging is enabled if either is set
1100 * (which means that if sipdebug is set in the config file, we can
1101 * only turn it off by reloading the config).
1103 enum sip_debug_e {
1104 sip_debug_none = 0,
1105 sip_debug_config = 1,
1106 sip_debug_console = 2,
1109 static enum sip_debug_e sipdebug;
1111 /*! \brief extra debugging for 'text' related events.
1112 * At the moment this is set together with sip_debug_console.
1113 * \note It should either go away or be implemented properly.
1115 static int sipdebug_text;
1117 /*! \brief T38 States for a call */
1118 enum t38state {
1119 T38_DISABLED = 0, /*!< Not enabled */
1120 T38_LOCAL_DIRECT, /*!< Offered from local */
1121 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
1122 T38_PEER_DIRECT, /*!< Offered from peer */
1123 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
1124 T38_ENABLED /*!< Negotiated (enabled) */
1127 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
1128 struct t38properties {
1129 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
1130 int capability; /*!< Our T38 capability */
1131 int peercapability; /*!< Peers T38 capability */
1132 int jointcapability; /*!< Supported T38 capability at both ends */
1133 enum t38state state; /*!< T.38 state */
1136 /*! \brief Parameters to know status of transfer */
1137 enum referstatus {
1138 REFER_IDLE, /*!< No REFER is in progress */
1139 REFER_SENT, /*!< Sent REFER to transferee */
1140 REFER_RECEIVED, /*!< Received REFER from transferrer */
1141 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
1142 REFER_ACCEPTED, /*!< Accepted by transferee */
1143 REFER_RINGING, /*!< Target Ringing */
1144 REFER_200OK, /*!< Answered by transfer target */
1145 REFER_FAILED, /*!< REFER declined - go on */
1146 REFER_NOAUTH /*!< We had no auth for REFER */
1149 /*! \brief generic struct to map between strings and integers.
1150 * Fill it with x-s pairs, terminate with an entry with s = NULL;
1151 * Then you can call map_x_s(...) to map an integer to a string,
1152 * and map_s_x() for the string -> integer mapping.
1154 struct _map_x_s {
1155 int x;
1156 const char *s;
1159 static const struct _map_x_s referstatusstrings[] = {
1160 { REFER_IDLE, "<none>" },
1161 { REFER_SENT, "Request sent" },
1162 { REFER_RECEIVED, "Request received" },
1163 { REFER_CONFIRMED, "Confirmed" },
1164 { REFER_ACCEPTED, "Accepted" },
1165 { REFER_RINGING, "Target ringing" },
1166 { REFER_200OK, "Done" },
1167 { REFER_FAILED, "Failed" },
1168 { REFER_NOAUTH, "Failed - auth failure" },
1169 { -1, NULL} /* terminator */
1172 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1173 \note OEJ: Should be moved to string fields */
1174 struct sip_refer {
1175 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
1176 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
1177 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
1178 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
1179 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1180 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1181 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
1182 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
1183 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
1184 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
1185 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
1186 * dialog owned by someone else, so we should not destroy
1187 * it when the sip_refer object goes.
1189 int attendedtransfer; /*!< Attended or blind transfer? */
1190 int localtransfer; /*!< Transfer to local domain? */
1191 enum referstatus status; /*!< REFER status */
1195 /*! \brief Structure that encapsulates all attributes related to running
1196 * SIP Session-Timers feature on a per dialog basis.
1198 struct sip_st_dlg {
1199 int st_active; /*!< Session-Timers on/off */
1200 int st_interval; /*!< Session-Timers negotiated session refresh interval */
1201 int st_schedid; /*!< Session-Timers ast_sched scheduler id */
1202 enum st_refresher st_ref; /*!< Session-Timers session refresher */
1203 int st_expirys; /*!< Session-Timers number of expirys */
1204 int st_active_peer_ua; /*!< Session-Timers on/off in peer UA */
1205 int st_cached_min_se; /*!< Session-Timers cached Min-SE */
1206 int st_cached_max_se; /*!< Session-Timers cached Session-Expires */
1207 enum st_mode st_cached_mode; /*!< Session-Timers cached M.O. */
1208 enum st_refresher st_cached_ref; /*!< Session-Timers cached refresher */
1212 /*! \brief Structure that encapsulates all attributes related to configuration
1213 * of SIP Session-Timers feature on a per user/peer basis.
1215 struct sip_st_cfg {
1216 enum st_mode st_mode_oper; /*!< Mode of operation for Session-Timers */
1217 enum st_refresher st_ref; /*!< Session-Timer refresher */
1218 int st_min_se; /*!< Lowest threshold for session refresh interval */
1219 int st_max_se; /*!< Highest threshold for session refresh interval */
1225 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
1226 * Created and initialized by sip_alloc(), the descriptor goes into the list of
1227 * descriptors (dialoglist).
1229 struct sip_pvt {
1230 struct sip_pvt *next; /*!< Next dialog in chain */
1231 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
1232 int method; /*!< SIP method that opened this dialog */
1233 AST_DECLARE_STRING_FIELDS(
1234 AST_STRING_FIELD(callid); /*!< Global CallID */
1235 AST_STRING_FIELD(randdata); /*!< Random data */
1236 AST_STRING_FIELD(accountcode); /*!< Account code */
1237 AST_STRING_FIELD(realm); /*!< Authorization realm */
1238 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1239 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1240 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1241 AST_STRING_FIELD(domain); /*!< Authorization domain */
1242 AST_STRING_FIELD(from); /*!< The From: header */
1243 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1244 AST_STRING_FIELD(exten); /*!< Extension where to start */
1245 AST_STRING_FIELD(context); /*!< Context for this call */
1246 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1247 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1248 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1249 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1250 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1251 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1252 AST_STRING_FIELD(todnid); /*!< DNID of this call (overrides host) */
1253 AST_STRING_FIELD(language); /*!< Default language for this call */
1254 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1255 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1256 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1257 AST_STRING_FIELD(redircause); /*!< Referring cause */
1258 AST_STRING_FIELD(theirtag); /*!< Their tag */
1259 AST_STRING_FIELD(username); /*!< [user] name */
1260 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1261 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1262 AST_STRING_FIELD(uri); /*!< Original requested URI */
1263 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1264 AST_STRING_FIELD(peersecret); /*!< Password */
1265 AST_STRING_FIELD(peermd5secret);
1266 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1267 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1268 AST_STRING_FIELD(via); /*!< Via: header */
1269 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1270 /* we only store the part in <brackets> in this field. */
1271 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1272 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1273 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1274 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1275 AST_STRING_FIELD(parkinglot); /*!< Parkinglot */
1277 struct sip_socket socket; /*!< The socket used for this dialog */
1278 unsigned int ocseq; /*!< Current outgoing seqno */
1279 unsigned int icseq; /*!< Current incoming seqno */
1280 ast_group_t callgroup; /*!< Call group */
1281 ast_group_t pickupgroup; /*!< Pickup group */
1282 int lastinvite; /*!< Last Cseq of invite */
1283 int lastnoninvite; /*!< Last Cseq of non-invite */
1284 struct ast_flags flags[2]; /*!< SIP_ flags */
1286 /* boolean or small integers that don't belong in flags */
1287 char do_history; /*!< Set if we want to record history */
1288 char alreadygone; /*!< already destroyed by our peer */
1289 char needdestroy; /*!< need to be destroyed by the monitor thread */
1290 char outgoing_call; /*!< this is an outgoing call */
1291 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1292 char novideo; /*!< Didn't get video in invite, don't offer */
1293 char notext; /*!< Text not supported (?) */
1295 int timer_t1; /*!< SIP timer T1, ms rtt */
1296 int timer_b; /*!< SIP timer B, ms */
1297 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1298 unsigned int reqsipoptions; /*!< Required SIP options on the other end */
1299 struct ast_codec_pref prefs; /*!< codec prefs */
1300 int capability; /*!< Special capability (codec) */
1301 int jointcapability; /*!< Supported capability at both ends (codecs) */
1302 int peercapability; /*!< Supported peer capability */
1303 int prefcodec; /*!< Preferred codec (outbound only) */
1304 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1305 int jointnoncodeccapability; /*!< Joint Non codec capability */
1306 int redircodecs; /*!< Redirect codecs */
1307 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1308 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
1309 struct t38properties t38; /*!< T38 settings */
1310 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1311 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1312 int callingpres; /*!< Calling presentation */
1313 int authtries; /*!< Times we've tried to authenticate */
1314 int expiry; /*!< How long we take to expire */
1315 long branch; /*!< The branch identifier of this session */
1316 char tag[11]; /*!< Our tag for this session */
1317 int sessionid; /*!< SDP Session ID */
1318 int sessionversion; /*!< SDP Session Version */
1319 int sessionversion_remote; /*!< Remote UA's SDP Session Version */
1320 int session_modify; /*!< Session modification request true/false */
1321 struct sockaddr_in sa; /*!< Our peer */
1322 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1323 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1324 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1325 time_t lastrtprx; /*!< Last RTP received */
1326 time_t lastrtptx; /*!< Last RTP sent */
1327 int rtptimeout; /*!< RTP timeout time */
1328 struct sockaddr_in recv; /*!< Received as */
1329 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1330 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1331 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1332 int route_persistant; /*!< Is this the "real" route? */
1333 struct ast_variable *notify_headers; /*!< Custom notify type */
1334 struct sip_auth *peerauth; /*!< Realm authentication */
1335 int noncecount; /*!< Nonce-count */
1336 char lastmsg[256]; /*!< Last Message sent/received */
1337 int amaflags; /*!< AMA Flags */
1338 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1339 struct sip_request initreq; /*!< Latest request that opened a new transaction
1340 within this dialog.
1341 NOT the request that opened the dialog
1344 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1345 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1346 int autokillid; /*!< Auto-kill ID (scheduler) */
1347 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1348 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1349 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1350 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1351 int laststate; /*!< SUBSCRIBE: Last known extension state */
1352 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1354 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1356 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1357 Used in peerpoke, mwi subscriptions */
1358 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1359 struct ast_rtp *rtp; /*!< RTP Session */
1360 struct ast_rtp *vrtp; /*!< Video RTP session */
1361 struct ast_rtp *trtp; /*!< Text RTP session */
1362 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1363 struct sip_history_head *history; /*!< History of this SIP dialog */
1364 size_t history_entries; /*!< Number of entires in the history */
1365 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1366 struct sip_invite_param *options; /*!< Options for INVITE */
1367 int autoframing; /*!< The number of Asters we group in a Pyroflax
1368 before strolling to the Grokyzpå
1369 (A bit unsure of this, please correct if
1370 you know more) */
1371 struct sip_st_dlg *stimer; /*!< SIP Session-Timers */
1373 int red;
1376 /*! Max entires in the history list for a sip_pvt */
1377 #define MAX_HISTORY_ENTRIES 50
1379 /*! \brief
1380 * Here we implement the container for dialogs (sip_pvt), defining
1381 * generic wrapper functions to ease the transition from the current
1382 * implementation (a single linked list) to a different container.
1383 * In addition to a reference to the container, we need functions to lock/unlock
1384 * the container and individual items, and functions to add/remove
1385 * references to the individual items.
1387 struct ao2_container *dialogs;
1389 #define sip_pvt_lock(x) ao2_lock(x)
1390 #define sip_pvt_trylock(x) ao2_trylock(x)
1391 #define sip_pvt_unlock(x) ao2_unlock(x)
1393 /*! \brief
1394 * when we create or delete references, make sure to use these
1395 * functions so we keep track of the refcounts.
1396 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1398 #ifdef REF_DEBUG
1399 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1400 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1402 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1404 if (p)
1405 _ao2_ref_debug(p, 1, tag, file, line, func);
1406 else
1407 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1408 return p;
1411 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1413 if (p)
1414 _ao2_ref_debug(p, -1, tag, file, line, func);
1415 return NULL;
1417 #else
1418 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
1420 if (p)
1421 ao2_ref(p, 1);
1422 else
1423 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1424 return p;
1427 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
1429 if (p)
1430 ao2_ref(p, -1);
1431 return NULL;
1433 #endif
1435 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1436 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1437 * Each packet holds a reference to the parent struct sip_pvt.
1438 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1439 * require retransmissions.
1441 struct sip_pkt {
1442 struct sip_pkt *next; /*!< Next packet in linked list */
1443 int retrans; /*!< Retransmission number */
1444 int method; /*!< SIP method for this packet */
1445 int seqno; /*!< Sequence number */
1446 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1447 char is_fatal; /*!< non-zero if there is a fatal error */
1448 struct sip_pvt *owner; /*!< Owner AST call */
1449 int retransid; /*!< Retransmission ID */
1450 int timer_a; /*!< SIP timer A, retransmission timer */
1451 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1452 int packetlen; /*!< Length of packet */
1453 struct ast_str *data;
1457 * \brief A peer's mailbox
1459 * We could use STRINGFIELDS here, but for only two strings, it seems like
1460 * too much effort ...
1462 struct sip_mailbox {
1463 char *mailbox;
1464 char *context;
1465 /*! Associated MWI subscription */
1466 struct ast_event_sub *event_sub;
1467 AST_LIST_ENTRY(sip_mailbox) entry;
1470 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1471 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1472 struct sip_peer {
1473 char name[80]; /*!< peer->name is the unique name of this object */
1474 struct sip_socket socket; /*!< Socket used for this peer */
1475 unsigned int transports:3; /*!< Transports (enum sip_transport) that are acceptable for this peer */
1476 char secret[80]; /*!< Password */
1477 char md5secret[80]; /*!< Password in MD5 */
1478 struct sip_auth *auth; /*!< Realm authentication list */
1479 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1480 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1481 char username[80]; /*!< Temporary username until registration */
1482 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1483 int amaflags; /*!< AMA Flags (for billing) */
1484 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1485 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1486 char fromuser[80]; /*!< From: user when calling this peer */
1487 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1488 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1489 char cid_num[80]; /*!< Caller ID num */
1490 char cid_name[80]; /*!< Caller ID name */
1491 int callingpres; /*!< Calling id presentation */
1492 int inUse; /*!< Number of calls in use */
1493 int inRinging; /*!< Number of calls ringing */
1494 int onHold; /*!< Peer has someone on hold */
1495 int call_limit; /*!< Limit of concurrent calls */
1496 int busy_level; /*!< Level of active channels where we signal busy */
1497 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1498 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1499 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1500 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1501 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1502 char parkinglot[AST_MAX_CONTEXT];/*!< Parkinglot */
1503 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1504 struct ast_codec_pref prefs; /*!< codec prefs */
1505 int lastmsgssent;
1506 unsigned int sipoptions; /*!< Supported SIP options */
1507 struct ast_flags flags[2]; /*!< SIP_ flags */
1509 /*! Mailboxes that this peer cares about */
1510 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1512 /* things that don't belong in flags */
1513 char is_realtime; /*!< this is a 'realtime' peer */
1514 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1515 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1516 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1517 char onlymatchonip; /*!< P: Only match on IP for incoming calls (old type=peer) */
1518 char the_mark; /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
1520 int expire; /*!< When to expire this peer registration */
1521 int capability; /*!< Codec capability */
1522 int rtptimeout; /*!< RTP timeout */
1523 int rtpholdtimeout; /*!< RTP Hold Timeout */
1524 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1525 ast_group_t callgroup; /*!< Call group */
1526 ast_group_t pickupgroup; /*!< Pickup group */
1527 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1528 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1529 struct sockaddr_in addr; /*!< IP address of peer */
1530 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1532 /* Qualification */
1533 struct sip_pvt *call; /*!< Call pointer */
1534 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1535 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1536 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1537 int qualifyfreq; /*!< Qualification: How often to check for the host to be up */
1538 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1539 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1540 struct ast_ha *ha; /*!< Access control list */
1541 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1542 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1543 int autoframing;
1544 struct sip_st_cfg stimer; /*!< SIP Session-Timers */
1545 int timer_t1; /*!< The maximum T1 value for the peer */
1546 int timer_b; /*!< The maximum timer B (transaction timeouts) */
1547 int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1551 /*! \brief Registrations with other SIP proxies
1552 * Created by sip_register(), the entry is linked in the 'regl' list,
1553 * and never deleted (other than at 'sip reload' or module unload times).
1554 * The entry always has a pending timeout, either waiting for an ACK to
1555 * the REGISTER message (in which case we have to retransmit the request),
1556 * or waiting for the next REGISTER message to be sent (either the initial one,
1557 * or once the previously completed registration one expires).
1558 * The registration can be in one of many states, though at the moment
1559 * the handling is a bit mixed.
1560 * Note that the entire evolution of sip_registry (transmissions,
1561 * incoming packets and timeouts) is driven by one single thread,
1562 * do_monitor(), so there is almost no synchronization issue.
1563 * The only exception is the sip_pvt creation/lookup,
1564 * as the dialoglist is also manipulated by other threads.
1566 struct sip_registry {
1567 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1568 AST_DECLARE_STRING_FIELDS(
1569 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1570 AST_STRING_FIELD(realm); /*!< Authorization realm */
1571 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1572 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1573 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1574 AST_STRING_FIELD(domain); /*!< Authorization domain */
1575 AST_STRING_FIELD(username); /*!< Who we are registering as */
1576 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1577 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1578 AST_STRING_FIELD(secret); /*!< Password in clear text */
1579 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1580 AST_STRING_FIELD(callback); /*!< Contact extension */
1581 AST_STRING_FIELD(random);
1583 enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
1584 int portno; /*!< Optional port override */
1585 int expire; /*!< Sched ID of expiration */
1586 int expiry; /*!< Value to use for the Expires header */
1587 int regattempts; /*!< Number of attempts (since the last success) */
1588 int timeout; /*!< sched id of sip_reg_timeout */
1589 int refresh; /*!< How often to refresh */
1590 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1591 enum sipregistrystate regstate; /*!< Registration state (see above) */
1592 struct timeval regtime; /*!< Last successful registration time */
1593 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1594 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1595 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for register */
1596 struct sockaddr_in us; /*!< Who the server thinks we are */
1597 int noncecount; /*!< Nonce-count */
1598 char lastmsg[256]; /*!< Last Message sent/received */
1601 /*! \brief Definition of a thread that handles a socket */
1602 struct sip_threadinfo {
1603 int stop;
1604 pthread_t threadid;
1605 struct ast_tcptls_session_instance *ser;
1606 enum sip_transport type; /*!< We keep a copy of the type here so we can display it in the connection list */
1607 AST_LIST_ENTRY(sip_threadinfo) list;
1610 /* --- Hash tables of various objects --------*/
1612 #ifdef LOW_MEMORY
1613 static int hash_peer_size = 17;
1614 static int hash_dialog_size = 17;
1615 static int hash_user_size = 17;
1616 #else
1617 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
1618 static int hash_dialog_size = 563;
1619 static int hash_user_size = 563;
1620 #endif
1622 /*! \brief The thread list of TCP threads */
1623 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
1625 /*! \brief The peer list: Users, Peers and Friends */
1626 struct ao2_container *peers;
1627 struct ao2_container *peers_by_ip;
1629 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1630 static struct ast_register_list {
1631 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1632 int recheck;
1633 } regl;
1635 /*! \brief
1636 * \note The only member of the peer used here is the name field
1638 static int peer_hash_cb(const void *obj, const int flags)
1640 const struct sip_peer *peer = obj;
1642 return ast_str_hash(peer->name);
1646 * \note The only member of the peer used here is the name field
1648 static int peer_cmp_cb(void *obj, void *arg, int flags)
1650 struct sip_peer *peer = obj, *peer2 = arg;
1652 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1656 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1658 static int peer_iphash_cb(const void *obj, const int flags)
1660 const struct sip_peer *peer = obj;
1661 int ret1 = peer->addr.sin_addr.s_addr;
1662 if (ret1 < 0)
1663 ret1 = -ret1;
1665 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
1666 return ret1;
1667 } else {
1668 return ret1 + peer->addr.sin_port;
1673 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1675 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
1677 struct sip_peer *peer = obj, *peer2 = arg;
1679 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr)
1680 return 0;
1682 if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
1683 if (peer->addr.sin_port == peer2->addr.sin_port)
1684 return CMP_MATCH;
1685 else
1686 return 0;
1688 return CMP_MATCH;
1692 * \note The only member of the dialog used here callid string
1694 static int dialog_hash_cb(const void *obj, const int flags)
1696 const struct sip_pvt *pvt = obj;
1698 return ast_str_hash(pvt->callid);
1702 * \note The only member of the dialog used here callid string
1704 static int dialog_cmp_cb(void *obj, void *arg, int flags)
1706 struct sip_pvt *pvt = obj, *pvt2 = arg;
1708 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
1711 static int temp_pvt_init(void *);
1712 static void temp_pvt_cleanup(void *);
1714 /*! \brief A per-thread temporary pvt structure */
1715 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1717 #ifdef LOW_MEMORY
1718 static void ts_ast_rtp_destroy(void *);
1720 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
1721 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
1722 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
1723 #endif
1725 /*! \brief Authentication list for realm authentication
1726 * \todo Move the sip_auth list to AST_LIST */
1727 static struct sip_auth *authl = NULL;
1730 /* --- Sockets and networking --------------*/
1732 /*! \brief Main socket for SIP communication.
1734 * sipsock is shared between the SIP manager thread (which handles reload
1735 * requests), the io handler (sipsock_read()) and the user routines that
1736 * issue writes (using __sip_xmit()).
1737 * The socket is -1 only when opening fails (this is a permanent condition),
1738 * or when we are handling a reload() that changes its address (this is
1739 * a transient situation during which we might have a harmless race, see
1740 * below). Because the conditions for the race to be possible are extremely
1741 * rare, we don't want to pay the cost of locking on every I/O.
1742 * Rather, we remember that when the race may occur, communication is
1743 * bound to fail anyways, so we just live with this event and let
1744 * the protocol handle this above us.
1746 static int sipsock = -1;
1748 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
1750 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1751 * internip is initialized picking a suitable address from one of the
1752 * interfaces, and the same port number we bind to. It is used as the
1753 * default address/port in SIP messages, and as the default address
1754 * (but not port) in SDP messages.
1756 static struct sockaddr_in internip;
1758 /*! \brief our external IP address/port for SIP sessions.
1759 * externip.sin_addr is only set when we know we might be behind
1760 * a NAT, and this is done using a variety of (mutually exclusive)
1761 * ways from the config file:
1763 * + with "externip = host[:port]" we specify the address/port explicitly.
1764 * The address is looked up only once when (re)loading the config file;
1766 * + with "externhost = host[:port]" we do a similar thing, but the
1767 * hostname is stored in externhost, and the hostname->IP mapping
1768 * is refreshed every 'externrefresh' seconds;
1770 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1771 * to the specified server, and store the result in externip.
1773 * Other variables (externhost, externexpire, externrefresh) are used
1774 * to support the above functions.
1776 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1778 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1779 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1780 static int externrefresh = 10;
1781 static struct sockaddr_in stunaddr; /*!< stun server address */
1783 /*! \brief List of local networks
1784 * We store "localnet" addresses from the config file into an access list,
1785 * marked as 'DENY', so the call to ast_apply_ha() will return
1786 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1787 * (i.e. presumably public) addresses.
1789 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1791 static int ourport_tcp; /*!< The port used for TCP connections */
1792 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1793 static struct sockaddr_in debugaddr;
1795 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1797 /*! some list management macros. */
1799 #define UNLINK(element, head, prev) do { \
1800 if (prev) \
1801 (prev)->next = (element)->next; \
1802 else \
1803 (head) = (element)->next; \
1804 } while (0)
1806 enum t38_action_flag {
1807 SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
1808 SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
1809 SDP_T38_ACCEPT, /*!< Remote side accepted our T38 request */
1812 /*---------------------------- Forward declarations of functions in chan_sip.c */
1813 /* Note: This is added to help splitting up chan_sip.c into several files
1814 in coming releases. */
1816 /*--- PBX interface functions */
1817 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1818 static int sip_devicestate(void *data);
1819 static int sip_sendtext(struct ast_channel *ast, const char *text);
1820 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1821 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1822 static int sip_hangup(struct ast_channel *ast);
1823 static int sip_answer(struct ast_channel *ast);
1824 static struct ast_frame *sip_read(struct ast_channel *ast);
1825 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1826 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1827 static int sip_transfer(struct ast_channel *ast, const char *dest);
1828 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1829 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1830 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1831 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1832 static const char *sip_get_callid(struct ast_channel *chan);
1834 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1835 static int sip_standard_port(struct sip_socket s);
1836 static int sip_prepare_socket(struct sip_pvt *p);
1837 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
1839 /*--- Transmitting responses and requests */
1840 static int sipsock_read(int *id, int fd, short events, void *ignore);
1841 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1842 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1843 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1844 static int retrans_pkt(const void *data);
1845 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1846 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1847 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1848 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1849 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
1850 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1851 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1852 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1853 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1854 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1855 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1856 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1857 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1858 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1859 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1860 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1861 static int transmit_refer(struct sip_pvt *p, const char *dest);
1862 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1863 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1864 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
1865 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1866 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1867 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1868 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1869 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1870 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1871 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1873 /*--- Dialog management */
1874 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1875 int useglobal_nat, const int intended_method);
1876 static int __sip_autodestruct(const void *data);
1877 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1878 static int sip_cancel_destroy(struct sip_pvt *p);
1879 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1880 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
1881 static void *registry_unref(struct sip_registry *reg, char *tag);
1882 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1883 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1884 static void __sip_pretend_ack(struct sip_pvt *p);
1885 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1886 static int auto_congest(const void *arg);
1887 static int update_call_counter(struct sip_pvt *fup, int event);
1888 static int hangup_sip2cause(int cause);
1889 static const char *hangup_cause2sip(int cause);
1890 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1891 static void free_old_route(struct sip_route *route);
1892 static void list_route(struct sip_route *route);
1893 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1894 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1895 struct sip_request *req, char *uri);
1896 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1897 static void check_pendings(struct sip_pvt *p);
1898 static void *sip_park_thread(void *stuff);
1899 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1900 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1902 /*--- Codec handling / SDP */
1903 static void try_suggested_sip_codec(struct sip_pvt *p);
1904 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1905 static const char *get_sdp(struct sip_request *req, const char *name);
1906 static int find_sdp(struct sip_request *req);
1907 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1908 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1909 struct ast_str **m_buf, struct ast_str **a_buf,
1910 int debug, int *min_packet_size);
1911 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1912 struct ast_str **m_buf, struct ast_str **a_buf,
1913 int debug);
1914 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp);
1915 static void do_setnat(struct sip_pvt *p, int natflags);
1916 static void stop_media_flows(struct sip_pvt *p);
1918 /*--- Authentication stuff */
1919 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1920 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1921 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1922 const char *secret, const char *md5secret, int sipmethod,
1923 char *uri, enum xmittype reliable, int ignore);
1924 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1925 int sipmethod, char *uri, enum xmittype reliable,
1926 struct sockaddr_in *sin, struct sip_peer **authpeer);
1927 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1929 /*--- Domain handling */
1930 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1931 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1932 static void clear_sip_domains(void);
1934 /*--- SIP realm authentication */
1935 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1936 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1937 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1939 /*--- Misc functions */
1940 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1941 static int sip_do_reload(enum channelreloadreason reason);
1942 static int reload_config(enum channelreloadreason reason);
1943 static int expire_register(const void *data);
1944 static void *do_monitor(void *data);
1945 static int restart_monitor(void);
1946 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1947 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1948 static int sip_refer_allocate(struct sip_pvt *p);
1949 static void ast_quiet_chan(struct ast_channel *chan);
1950 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1952 /*--- Device monitoring and Device/extension state/event handling */
1953 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1954 static int sip_devicestate(void *data);
1955 static int sip_poke_noanswer(const void *data);
1956 static int sip_poke_peer(struct sip_peer *peer, int force);
1957 static void sip_poke_all_peers(void);
1958 static void sip_peer_hold(struct sip_pvt *p, int hold);
1959 static void mwi_event_cb(const struct ast_event *, void *);
1961 /*--- Applications, functions, CLI and manager command helpers */
1962 static const char *sip_nat_mode(const struct sip_pvt *p);
1963 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1964 static char *transfermode2str(enum transfermodes mode) attribute_const;
1965 static const char *nat2str(int nat) attribute_const;
1966 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1967 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1968 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1969 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1970 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1971 static void print_group(int fd, ast_group_t group, int crlf);
1972 static const char *dtmfmode2str(int mode) attribute_const;
1973 static int str2dtmfmode(const char *str) attribute_unused;
1974 static const char *insecure2str(int mode) attribute_const;
1975 static void cleanup_stale_contexts(char *new, char *old);
1976 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1977 static const char *domain_mode_to_text(const enum domain_mode mode);
1978 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1979 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1980 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1981 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1982 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1983 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1984 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1985 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1986 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1987 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1988 static char *complete_sip_peer(const char *word, int state, int flags2);
1989 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1990 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1991 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1992 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1993 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1994 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1995 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1996 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1997 static char *sip_do_debug_ip(int fd, char *arg);
1998 static char *sip_do_debug_peer(int fd, char *arg);
1999 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2000 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2001 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2002 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2003 static int sip_dtmfmode(struct ast_channel *chan, void *data);
2004 static int sip_addheader(struct ast_channel *chan, void *data);
2005 static int sip_do_reload(enum channelreloadreason reason);
2006 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2007 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
2009 /*--- Debugging
2010 Functions for enabling debug per IP or fully, or enabling history logging for
2011 a SIP dialog
2013 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
2014 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
2015 static inline int sip_debug_test_pvt(struct sip_pvt *p);
2018 /*! \brief Append to SIP dialog history
2019 \return Always returns 0 */
2020 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2021 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
2022 static void sip_dump_history(struct sip_pvt *dialog);
2024 /*--- Device object handling */
2025 static struct sip_peer *temp_peer(const char *name);
2026 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int ispeer);
2027 static int update_call_counter(struct sip_pvt *fup, int event);
2028 static void sip_destroy_peer(struct sip_peer *peer);
2029 static void sip_destroy_peer_fn(void *peer);
2030 static void set_peer_defaults(struct sip_peer *peer);
2031 static struct sip_peer *temp_peer(const char *name);
2032 static void register_peer_exten(struct sip_peer *peer, int onoff);
2033 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch);
2034 static int sip_poke_peer_s(const void *data);
2035 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
2036 static void reg_source_db(struct sip_peer *peer);
2037 static void destroy_association(struct sip_peer *peer);
2038 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
2039 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
2041 /* Realtime device support */
2042 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username);
2043 static void update_peer(struct sip_peer *p, int expiry);
2044 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
2045 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
2046 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
2047 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2049 /*--- Internal UA client handling (outbound registrations) */
2050 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
2051 static void sip_registry_destroy(struct sip_registry *reg);
2052 static int sip_register(const char *value, int lineno);
2053 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
2054 static int sip_reregister(const void *data);
2055 static int __sip_do_register(struct sip_registry *r);
2056 static int sip_reg_timeout(const void *data);
2057 static void sip_send_all_registers(void);
2058 static int sip_reinvite_retry(const void *data);
2060 /*--- Parsing SIP requests and responses */
2061 static void append_date(struct sip_request *req); /* Append date to SIP packet */
2062 static int determine_firstline_parts(struct sip_request *req);
2063 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2064 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
2065 static int find_sip_method(const char *msg);
2066 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
2067 static int parse_request(struct sip_request *req);
2068 static const char *get_header(const struct sip_request *req, const char *name);
2069 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
2070 static int method_match(enum sipmethod id, const char *name);
2071 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
2072 static char *get_in_brackets(char *tmp);
2073 static const char *find_alias(const char *name, const char *_default);
2074 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
2075 static int lws2sws(char *msgbuf, int len);
2076 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
2077 static char *remove_uri_parameters(char *uri);
2078 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
2079 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
2080 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
2081 static int set_address_from_contact(struct sip_pvt *pvt);
2082 static void check_via(struct sip_pvt *p, struct sip_request *req);
2083 static char *get_calleridname(const char *input, char *output, size_t outputsize);
2084 static int get_rpid_num(const char *input, char *output, int maxlen);
2085 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
2086 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
2087 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
2088 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
2090 /*-- TCP connection handling ---*/
2091 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser);
2092 static void *sip_tcp_worker_fn(void *);
2094 /*--- Constructing requests and responses */
2095 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
2096 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
2097 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
2098 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
2099 static int init_resp(struct sip_request *resp, const char *msg);
2100 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
2101 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
2102 static void build_via(struct sip_pvt *p);
2103 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
2104 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin);
2105 static char *generate_random_string(char *buf, size_t size);
2106 static void build_callid_pvt(struct sip_pvt *pvt);
2107 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
2108 static void make_our_tag(char *tagbuf, size_t len);
2109 static int add_header(struct sip_request *req, const char *var, const char *value);
2110 static int add_header_contentLength(struct sip_request *req, int len);
2111 static int add_line(struct sip_request *req, const char *line);
2112 static int add_text(struct sip_request *req, const char *text);
2113 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
2114 static int add_vidupdate(struct sip_request *req);
2115 static void add_route(struct sip_request *req, struct sip_route *route);
2116 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2117 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2118 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
2119 static void set_destination(struct sip_pvt *p, char *uri);
2120 static void append_date(struct sip_request *req);
2121 static void build_contact(struct sip_pvt *p);
2122 static void build_rpid(struct sip_pvt *p);
2124 /*------Request handling functions */
2125 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
2126 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, int *nounlock);
2127 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
2128 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
2129 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
2130 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
2131 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
2132 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2133 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
2134 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
2135 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
2136 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2137 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
2139 /*------Response handling functions */
2140 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2141 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2142 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2143 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2144 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2146 /*----- RTP interface functions */
2147 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
2148 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2149 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2150 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2151 static int sip_get_codec(struct ast_channel *chan);
2152 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
2154 /*------ T38 Support --------- */
2155 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
2156 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
2157 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
2158 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
2159 static void change_t38_state(struct sip_pvt *p, int state);
2161 /*------ Session-Timers functions --------- */
2162 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
2163 static int proc_session_timer(const void *vp);
2164 static void stop_session_timer(struct sip_pvt *p);
2165 static void start_session_timer(struct sip_pvt *p);
2166 static void restart_session_timer(struct sip_pvt *p);
2167 static const char *strefresher2str(enum st_refresher r);
2168 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
2169 static int parse_minse(const char *p_hdrval, int *const p_interval);
2170 static int st_get_se(struct sip_pvt *, int max);
2171 static enum st_refresher st_get_refresher(struct sip_pvt *);
2172 static enum st_mode st_get_mode(struct sip_pvt *);
2173 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
2176 /*! \brief Definition of this channel for PBX channel registration */
2177 static const struct ast_channel_tech sip_tech = {
2178 .type = "SIP",
2179 .description = "Session Initiation Protocol (SIP)",
2180 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
2181 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
2182 .requester = sip_request_call, /* called with chan unlocked */
2183 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
2184 .call = sip_call, /* called with chan locked */
2185 .send_html = sip_sendhtml,
2186 .hangup = sip_hangup, /* called with chan locked */
2187 .answer = sip_answer, /* called with chan locked */
2188 .read = sip_read, /* called with chan locked */
2189 .write = sip_write, /* called with chan locked */
2190 .write_video = sip_write, /* called with chan locked */
2191 .write_text = sip_write,
2192 .indicate = sip_indicate, /* called with chan locked */
2193 .transfer = sip_transfer, /* called with chan locked */
2194 .fixup = sip_fixup, /* called with chan locked */
2195 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
2196 .send_digit_end = sip_senddigit_end,
2197 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
2198 .early_bridge = ast_rtp_early_bridge,
2199 .send_text = sip_sendtext, /* called with chan locked */
2200 .func_channel_read = acf_channel_read,
2201 .queryoption = sip_queryoption,
2202 .get_pvt_uniqueid = sip_get_callid,
2205 /*! \brief This version of the sip channel tech has no send_digit_begin
2206 * callback so that the core knows that the channel does not want
2207 * DTMF BEGIN frames.
2208 * The struct is initialized just before registering the channel driver,
2209 * and is for use with channels using SIP INFO DTMF.
2211 static struct ast_channel_tech sip_tech_info;
2214 /*! \brief Working TLS connection configuration */
2215 static struct ast_tls_config sip_tls_cfg;
2217 /*! \brief Default TLS connection configuration */
2218 static struct ast_tls_config default_tls_cfg;
2220 /*! \brief The TCP server definition */
2221 static struct server_args sip_tcp_desc = {
2222 .accept_fd = -1,
2223 .master = AST_PTHREADT_NULL,
2224 .tls_cfg = NULL,
2225 .poll_timeout = -1,
2226 .name = "sip tcp server",
2227 .accept_fn = ast_tcptls_server_root,
2228 .worker_fn = sip_tcp_worker_fn,
2231 /*! \brief The TCP/TLS server definition */
2232 static struct server_args sip_tls_desc = {
2233 .accept_fd = -1,
2234 .master = AST_PTHREADT_NULL,
2235 .tls_cfg = &sip_tls_cfg,
2236 .poll_timeout = -1,
2237 .name = "sip tls server",
2238 .accept_fn = ast_tcptls_server_root,
2239 .worker_fn = sip_tcp_worker_fn,
2242 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
2243 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
2245 /*! \brief map from an integer value to a string.
2246 * If no match is found, return errorstring
2248 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2250 const struct _map_x_s *cur;
2252 for (cur = table; cur->s; cur++)
2253 if (cur->x == x)
2254 return cur->s;
2255 return errorstring;
2258 /*! \brief map from a string to an integer value, case insensitive.
2259 * If no match is found, return errorvalue.
2261 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2263 const struct _map_x_s *cur;
2265 for (cur = table; cur->s; cur++)
2266 if (!strcasecmp(cur->s, s))
2267 return cur->x;
2268 return errorvalue;
2272 /*! \brief Interface structure with callbacks used to connect to RTP module */
2273 static struct ast_rtp_protocol sip_rtp = {
2274 .type = "SIP",
2275 .get_rtp_info = sip_get_rtp_peer,
2276 .get_vrtp_info = sip_get_vrtp_peer,
2277 .get_trtp_info = sip_get_trtp_peer,
2278 .set_rtp_peer = sip_set_rtp_peer,
2279 .get_codec = sip_get_codec,
2283 /*! \brief SIP TCP connection handler */
2284 static void *sip_tcp_worker_fn(void *data)
2286 struct ast_tcptls_session_instance *ser = data;
2288 return _sip_tcp_helper_thread(NULL, ser);
2291 /*! \brief SIP TCP thread management function */
2292 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser)
2294 int res, cl;
2295 struct sip_request req = { 0, } , reqcpy = { 0, };
2296 struct sip_threadinfo *me;
2297 char buf[1024] = "";
2299 me = ast_calloc(1, sizeof(*me));
2301 if (!me)
2302 goto cleanup2;
2304 me->threadid = pthread_self();
2305 me->ser = ser;
2306 if (ser->ssl)
2307 me->type = SIP_TRANSPORT_TLS;
2308 else
2309 me->type = SIP_TRANSPORT_TCP;
2311 AST_LIST_LOCK(&threadl);
2312 AST_LIST_INSERT_TAIL(&threadl, me, list);
2313 AST_LIST_UNLOCK(&threadl);
2315 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2316 goto cleanup;
2317 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2318 goto cleanup;
2320 for (;;) {
2321 ast_str_reset(req.data);
2322 ast_str_reset(reqcpy.data);
2323 req.len = 0;
2324 req.ignore = 0;
2325 req.debug = 0;
2327 req.socket.fd = ser->fd;
2328 if (ser->ssl) {
2329 req.socket.type = SIP_TRANSPORT_TLS;
2330 req.socket.port = htons(ourport_tls);
2331 } else {
2332 req.socket.type = SIP_TRANSPORT_TCP;
2333 req.socket.port = htons(ourport_tcp);
2335 res = ast_wait_for_input(ser->fd, -1);
2336 if (res < 0) {
2337 ast_debug(1, "ast_wait_for_input returned %d\n", res);
2338 goto cleanup;
2341 /* Read in headers one line at a time */
2342 while (req.len < 4 || strncmp((char *)&req.data->str + req.len - 4, "\r\n\r\n", 4)) {
2343 ast_mutex_lock(&ser->lock);
2344 if (!fgets(buf, sizeof(buf), ser->f)) {
2345 ast_mutex_unlock(&ser->lock);
2346 goto cleanup;
2348 ast_mutex_unlock(&ser->lock);
2349 if (me->stop)
2350 goto cleanup;
2351 ast_str_append(&req.data, 0, "%s", buf);
2352 req.len = req.data->used;
2354 copy_request(&reqcpy, &req);
2355 parse_request(&reqcpy);
2356 if (sscanf(get_header(&reqcpy, "Content-Length"), "%d", &cl)) {
2357 while (cl > 0) {
2358 ast_mutex_lock(&ser->lock);
2359 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, ser->f)) {
2360 ast_mutex_unlock(&ser->lock);
2361 goto cleanup;
2363 ast_mutex_unlock(&ser->lock);
2364 if (me->stop)
2365 goto cleanup;
2366 cl -= strlen(buf);
2367 ast_str_append(&req.data, 0, "%s", buf);
2368 req.len = req.data->used;
2371 req.socket.ser = ser;
2372 handle_request_do(&req, &ser->requestor);
2375 cleanup:
2376 AST_LIST_LOCK(&threadl);
2377 AST_LIST_REMOVE(&threadl, me, list);
2378 AST_LIST_UNLOCK(&threadl);
2379 ast_free(me);
2380 cleanup2:
2381 fclose(ser->f);
2382 ser->f = NULL;
2383 ser->fd = -1;
2384 if (reqcpy.data) {
2385 ast_free(reqcpy.data);
2388 if (req.data) {
2389 ast_free(req.data);
2390 req.data = NULL;
2394 ao2_ref(ser, -1);
2395 ser = NULL;
2397 return NULL;
2402 * helper functions to unreference various types of objects.
2403 * By handling them this way, we don't have to declare the
2404 * destructor on each call, which removes the chance of errors.
2406 static void *unref_peer(struct sip_peer *peer, char *tag)
2408 ao2_t_ref(peer, -1, tag);
2409 return NULL;
2412 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2414 ao2_t_ref(peer, 1,tag);
2415 return peer;
2419 * \brief Unlink a dialog from the dialogs container, as well as any other places
2420 * that it may be currently stored.
2422 * \note A reference to the dialog must be held before calling this function, and this
2423 * function does not release that reference.
2425 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2427 struct sip_pkt *cp;
2429 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2431 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2433 /* Unlink us from the owner (channel) if we have one */
2434 if (dialog->owner) {
2435 if (lockowner)
2436 ast_channel_lock(dialog->owner);
2437 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2438 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2439 if (lockowner)
2440 ast_channel_unlock(dialog->owner);
2442 if (dialog->registry) {
2443 if (dialog->registry->call == dialog)
2444 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2445 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2447 if (dialog->stateid > -1) {
2448 ast_extension_state_del(dialog->stateid, NULL);
2449 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2450 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2452 /* Remove link from peer to subscription of MWI */
2453 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2454 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2455 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2456 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2458 /* remove all current packets in this dialog */
2459 while((cp = dialog->packets)) {
2460 dialog->packets = dialog->packets->next;
2461 AST_SCHED_DEL(sched, cp->retransid);
2462 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2463 ast_free(cp);
2466 AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
2468 AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
2470 if (dialog->autokillid > -1)
2471 AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
2473 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2474 return NULL;
2477 static void *registry_unref(struct sip_registry *reg, char *tag)
2479 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2480 ASTOBJ_UNREF(reg, sip_registry_destroy);
2481 return NULL;
2484 /*! \brief Add object reference to SIP registry */
2485 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2487 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2488 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2491 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2492 static struct ast_udptl_protocol sip_udptl = {
2493 type: "SIP",
2494 get_udptl_info: sip_get_udptl_peer,
2495 set_udptl_peer: sip_set_udptl_peer,
2498 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2499 __attribute__ ((format (printf, 2, 3)));
2502 /*! \brief Convert transfer status to string */
2503 static const char *referstatus2str(enum referstatus rstatus)
2505 return map_x_s(referstatusstrings, rstatus, "");
2508 /*! \brief Initialize the initital request packet in the pvt structure.
2509 This packet is used for creating replies and future requests in
2510 a dialog */
2511 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2513 if (p->initreq.headers)
2514 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2515 else
2516 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2517 /* Use this as the basis */
2518 copy_request(&p->initreq, req);
2519 parse_request(&p->initreq);
2520 if (req->debug)
2521 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2524 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2525 static void sip_alreadygone(struct sip_pvt *dialog)
2527 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2528 dialog->alreadygone = 1;
2531 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2532 static int proxy_update(struct sip_proxy *proxy)
2534 /* if it's actually an IP address and not a name,
2535 there's no need for a managed lookup */
2536 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2537 /* Ok, not an IP address, then let's check if it's a domain or host */
2538 /* XXX Todo - if we have proxy port, don't do SRV */
2539 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
2540 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2541 return FALSE;
2544 proxy->last_dnsupdate = time(NULL);
2545 return TRUE;
2548 /*! \brief Allocate and initialize sip proxy */
2549 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2551 struct sip_proxy *proxy;
2552 proxy = ast_calloc(1, sizeof(*proxy));
2553 if (!proxy)
2554 return NULL;
2555 proxy->force = force;
2556 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2557 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2558 proxy_update(proxy);
2559 return proxy;
2562 /*! \brief Get default outbound proxy or global proxy */
2563 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2565 if (peer && peer->outboundproxy) {
2566 if (sipdebug)
2567 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2568 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2569 return peer->outboundproxy;
2571 if (global_outboundproxy.name[0]) {
2572 if (sipdebug)
2573 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2574 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2575 return &global_outboundproxy;
2577 if (sipdebug)
2578 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2579 return NULL;
2582 /*! \brief returns true if 'name' (with optional trailing whitespace)
2583 * matches the sip method 'id'.
2584 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2585 * a case-insensitive comparison to be more tolerant.
2586 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2588 static int method_match(enum sipmethod id, const char *name)
2590 int len = strlen(sip_methods[id].text);
2591 int l_name = name ? strlen(name) : 0;
2592 /* true if the string is long enough, and ends with whitespace, and matches */
2593 return (l_name >= len && name[len] < 33 &&
2594 !strncasecmp(sip_methods[id].text, name, len));
2597 /*! \brief find_sip_method: Find SIP method from header */
2598 static int find_sip_method(const char *msg)
2600 int i, res = 0;
2602 if (ast_strlen_zero(msg))
2603 return 0;
2604 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
2605 if (method_match(i, msg))
2606 res = sip_methods[i].id;
2608 return res;
2611 /*! \brief Parse supported header in incoming packet */
2612 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2614 char *next, *sep;
2615 char *temp;
2616 unsigned int profile = 0;
2617 int i, found;
2619 if (ast_strlen_zero(supported) )
2620 return 0;
2621 temp = ast_strdupa(supported);
2623 if (sipdebug)
2624 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2626 for (next = temp; next; next = sep) {
2627 found = FALSE;
2628 if ( (sep = strchr(next, ',')) != NULL)
2629 *sep++ = '\0';
2630 next = ast_skip_blanks(next);
2631 if (sipdebug)
2632 ast_debug(3, "Found SIP option: -%s-\n", next);
2633 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
2634 if (!strcasecmp(next, sip_options[i].text)) {
2635 profile |= sip_options[i].id;
2636 found = TRUE;
2637 if (sipdebug)
2638 ast_debug(3, "Matched SIP option: %s\n", next);
2639 break;
2643 /* This function is used to parse both Suported: and Require: headers.
2644 Let the caller of this function know that an unknown option tag was
2645 encountered, so that if the UAC requires it then the request can be
2646 rejected with a 420 response. */
2647 if (!found)
2648 profile |= SIP_OPT_UNKNOWN;
2650 if (!found && sipdebug) {
2651 if (!strncasecmp(next, "x-", 2))
2652 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2653 else
2654 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2658 if (pvt)
2659 pvt->sipoptions = profile;
2660 return profile;
2663 /*! \brief See if we pass debug IP filter */
2664 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2666 if (!sipdebug)
2667 return 0;
2668 if (debugaddr.sin_addr.s_addr) {
2669 if (((ntohs(debugaddr.sin_port) != 0)
2670 && (debugaddr.sin_port != addr->sin_port))
2671 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2672 return 0;
2674 return 1;
2677 /*! \brief The real destination address for a write */
2678 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2680 if (p->outboundproxy)
2681 return &p->outboundproxy->ip;
2683 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2686 /*! \brief Display SIP nat mode */
2687 static const char *sip_nat_mode(const struct sip_pvt *p)
2689 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2692 /*! \brief Test PVT for debugging output */
2693 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2695 if (!sipdebug)
2696 return 0;
2697 return sip_debug_test_addr(sip_real_dst(p));
2700 static inline const char *get_transport_list(struct sip_peer *peer) {
2701 switch (peer->transports) {
2702 case SIP_TRANSPORT_UDP:
2703 return "UDP";
2704 case SIP_TRANSPORT_TCP:
2705 return "TCP";
2706 case SIP_TRANSPORT_TLS:
2707 return "TLS";
2708 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
2709 return "TCP,UDP";
2710 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
2711 return "TLS,UDP";
2712 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
2713 return "TLS,TCP";
2714 default:
2715 return peer->transports ?
2716 "TLS,TCP,UDP" : "UNKNOWN";
2720 static inline const char *get_transport(enum sip_transport t)
2722 switch (t) {
2723 case SIP_TRANSPORT_UDP:
2724 return "UDP";
2725 case SIP_TRANSPORT_TCP:
2726 return "TCP";
2727 case SIP_TRANSPORT_TLS:
2728 return "TLS";
2731 return "UNKNOWN";
2734 static inline const char *get_transport_pvt(struct sip_pvt *p)
2736 if (p->outboundproxy && p->outboundproxy->transport)
2737 p->socket.type = p->outboundproxy->transport;
2739 return get_transport(p->socket.type);
2742 /*! \brief Transmit SIP message
2743 Sends a SIP request or response on a given socket (in the pvt)
2744 Called by retrans_pkt, send_request, send_response and
2745 __sip_reliable_xmit
2747 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2749 int res = 0;
2750 const struct sockaddr_in *dst = sip_real_dst(p);
2752 ast_debug(1, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
2754 if (sip_prepare_socket(p) < 0)
2755 return XMIT_ERROR;
2757 if (p->socket.ser)
2758 ast_mutex_lock(&p->socket.ser->lock);
2760 if (p->socket.type & SIP_TRANSPORT_UDP)
2761 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2762 else {
2763 if (p->socket.ser->f)
2764 res = ast_tcptls_server_write(p->socket.ser, data->str, len);
2765 else
2766 ast_debug(1, "No p->socket.ser->f len=%d\n", len);
2769 if (p->socket.ser)
2770 ast_mutex_unlock(&p->socket.ser->lock);
2772 if (res == -1) {
2773 switch (errno) {
2774 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2775 case EHOSTUNREACH: /* Host can't be reached */
2776 case ENETDOWN: /* Inteface down */
2777 case ENETUNREACH: /* Network failure */
2778 case ECONNREFUSED: /* ICMP port unreachable */
2779 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2782 if (res != len)
2783 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
2785 return res;
2788 /*! \brief Build a Via header for a request */
2789 static void build_via(struct sip_pvt *p)
2791 /* Work around buggy UNIDEN UIP200 firmware */
2792 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2794 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2795 ast_string_field_build(p, via, "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
2796 get_transport_pvt(p),
2797 ast_inet_ntoa(p->ourip.sin_addr),
2798 ntohs(p->ourip.sin_port), p->branch, rport);
2801 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2803 * Using the localaddr structure built up with localnet statements in sip.conf
2804 * apply it to their address to see if we need to substitute our
2805 * externip or can get away with our internal bindaddr
2806 * 'us' is always overwritten.
2808 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2810 struct sockaddr_in theirs;
2811 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2812 * reachable IP address and port. This is done if:
2813 * 1. we have a localaddr list (containing 'internal' addresses marked
2814 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2815 * and AST_SENSE_ALLOW on 'external' ones);
2816 * 2. either stunaddr or externip is set, so we know what to use as the
2817 * externally visible address;
2818 * 3. the remote address, 'them', is external;
2819 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2820 * when passed to ast_apply_ha() so it does need to be remapped.
2821 * This fourth condition is checked later.
2823 int want_remap;
2825 *us = internip; /* starting guess for the internal address */
2826 /* now ask the system what would it use to talk to 'them' */
2827 ast_ouraddrfor(them, &us->sin_addr);
2828 theirs.sin_addr = *them;
2830 want_remap = localaddr &&
2831 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2832 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2834 if (want_remap &&
2835 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2836 /* if we used externhost or stun, see if it is time to refresh the info */
2837 if (externexpire && time(NULL) >= externexpire) {
2838 if (stunaddr.sin_addr.s_addr) {
2839 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2840 } else {
2841 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2842 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2844 externexpire = time(NULL) + externrefresh;
2846 if (externip.sin_addr.s_addr)
2847 *us = externip;
2848 else
2849 ast_log(LOG_WARNING, "stun failed\n");
2850 ast_debug(1, "Target address %s is not local, substituting externip\n",
2851 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2852 } else if (bindaddr.sin_addr.s_addr) {
2853 /* no remapping, but we bind to a specific address, so use it. */
2854 *us = bindaddr;
2858 /*! \brief Append to SIP dialog history with arg list */
2859 static __attribute__((format (printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2861 char buf[80], *c = buf; /* max history length */
2862 struct sip_history *hist;
2863 int l;
2865 vsnprintf(buf, sizeof(buf), fmt, ap);
2866 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2867 l = strlen(buf) + 1;
2868 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2869 return;
2870 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2871 ast_free(hist);
2872 return;
2874 memcpy(hist->event, buf, l);
2875 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2876 struct sip_history *oldest;
2877 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2878 p->history_entries--;
2879 ast_free(oldest);
2881 AST_LIST_INSERT_TAIL(p->history, hist, list);
2882 p->history_entries++;
2885 /*! \brief Append to SIP dialog history with arg list */
2886 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2888 va_list ap;
2890 if (!p)
2891 return;
2893 if (!p->do_history && !recordhistory && !dumphistory)
2894 return;
2896 va_start(ap, fmt);
2897 append_history_va(p, fmt, ap);
2898 va_end(ap);
2900 return;
2903 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2904 static int retrans_pkt(const void *data)
2906 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2907 int reschedule = DEFAULT_RETRANS;
2908 int xmitres = 0;
2910 /* Lock channel PVT */
2911 sip_pvt_lock(pkt->owner);
2913 if (pkt->retrans < MAX_RETRANS) {
2914 pkt->retrans++;
2915 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2916 if (sipdebug)
2917 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
2918 } else {
2919 int siptimer_a;
2921 if (sipdebug)
2922 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2923 if (!pkt->timer_a)
2924 pkt->timer_a = 2 ;
2925 else
2926 pkt->timer_a = 2 * pkt->timer_a;
2928 /* For non-invites, a maximum of 4 secs */
2929 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2930 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2931 siptimer_a = 4000;
2933 /* Reschedule re-transmit */
2934 reschedule = siptimer_a;
2935 ast_debug(4, "** 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);
2938 if (sip_debug_test_pvt(pkt->owner)) {
2939 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2940 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2941 pkt->retrans, sip_nat_mode(pkt->owner),
2942 ast_inet_ntoa(dst->sin_addr),
2943 ntohs(dst->sin_port), pkt->data->str);
2946 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
2947 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2948 sip_pvt_unlock(pkt->owner);
2949 if (xmitres == XMIT_ERROR)
2950 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2951 else
2952 return reschedule;
2954 /* Too many retries */
2955 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2956 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2957 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n",
2958 pkt->owner->callid, pkt->seqno,
2959 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2960 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2961 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2964 if (xmitres == XMIT_ERROR) {
2965 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2966 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2967 } else
2968 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2970 pkt->retransid = -1;
2972 if (pkt->is_fatal) {
2973 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2974 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2975 usleep(1);
2976 sip_pvt_lock(pkt->owner);
2979 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
2980 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2982 if (pkt->owner->owner) {
2983 sip_alreadygone(pkt->owner);
2984 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2985 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
2986 ast_channel_unlock(pkt->owner->owner);
2987 } else {
2988 /* If no channel owner, destroy now */
2990 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2991 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2992 pkt->owner->needdestroy = 1;
2993 sip_alreadygone(pkt->owner);
2994 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2999 if (pkt->method == SIP_BYE) {
3000 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
3001 if (pkt->owner->owner)
3002 ast_channel_unlock(pkt->owner->owner);
3003 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3004 pkt->owner->needdestroy = 1;
3007 /* Remove the packet */
3008 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3009 if (cur == pkt) {
3010 UNLINK(cur, pkt->owner->packets, prev);
3011 sip_pvt_unlock(pkt->owner);
3012 if (pkt->owner)
3013 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3014 if (pkt->data)
3015 ast_free(pkt->data);
3016 pkt->data = NULL;
3017 ast_free(pkt);
3018 return 0;
3021 /* error case */
3022 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3023 sip_pvt_unlock(pkt->owner);
3024 return 0;
3027 /*! \brief Transmit packet with retransmits
3028 \return 0 on success, -1 on failure to allocate packet
3030 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
3032 struct sip_pkt *pkt = NULL;
3033 int siptimer_a = DEFAULT_RETRANS;
3034 int xmitres = 0;
3036 if (sipmethod == SIP_INVITE) {
3037 /* Note this is a pending invite */
3038 p->pendinginvite = seqno;
3041 /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3042 /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3043 /* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3044 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3045 xmitres = __sip_xmit(dialog_ref(p, "pasing dialog ptr into callback..."), data, len); /* Send packet */
3046 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3047 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3048 return AST_FAILURE;
3049 } else
3050 return AST_SUCCESS;
3053 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3054 return AST_FAILURE;
3055 /* copy data, add a terminator and save length */
3056 if (!(pkt->data = ast_str_create(len))) {
3057 ast_free(pkt);
3058 return AST_FAILURE;
3060 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3061 pkt->packetlen = len;
3062 /* copy other parameters from the caller */
3063 pkt->method = sipmethod;
3064 pkt->seqno = seqno;
3065 pkt->is_resp = resp;
3066 pkt->is_fatal = fatal;
3067 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3068 pkt->next = p->packets;
3069 p->packets = pkt; /* Add it to the queue */
3070 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
3071 pkt->retransid = -1;
3072 if (pkt->timer_t1)
3073 siptimer_a = pkt->timer_t1 * 2;
3075 /* Schedule retransmission */
3076 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3077 if (sipdebug)
3078 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
3080 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
3082 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3083 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3084 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3085 if (pkt->data)
3086 ast_free(pkt->data);
3087 return AST_FAILURE;
3088 } else {
3089 return AST_SUCCESS;
3093 /*! \brief Kill a SIP dialog (called only by the scheduler)
3094 * The scheduler has a reference to this dialog when p->autokillid != -1,
3095 * and we are called using that reference. So if the event is not
3096 * rescheduled, we need to call dialog_unref().
3098 static int __sip_autodestruct(const void *data)
3100 struct sip_pvt *p = (struct sip_pvt *)data;
3102 /* If this is a subscription, tell the phone that we got a timeout */
3103 if (p->subscribed) {
3104 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
3105 p->subscribed = NONE;
3106 append_history(p, "Subscribestatus", "timeout");
3107 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3108 return 10000; /* Reschedule this destruction so that we know that it's gone */
3111 /* If there are packets still waiting for delivery, delay the destruction */
3112 if (p->packets) {
3113 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3114 append_history(p, "ReliableXmit", "timeout");
3115 return 10000;
3118 if (p->subscribed == MWI_NOTIFICATION)
3119 if (p->relatedpeer)
3120 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer"); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
3122 /* Reset schedule ID */
3123 p->autokillid = -1;
3125 if (p->owner) {
3126 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3127 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3128 } else if (p->refer && !p->alreadygone) {
3129 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3130 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3131 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3132 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3133 } else {
3134 append_history(p, "AutoDestroy", "%s", p->callid);
3135 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3136 dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3137 /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3138 /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
3139 /* sip_destroy also absorbs the reference */
3141 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3142 return 0;
3145 /*! \brief Schedule destruction of SIP dialog */
3146 static void sip_scheddestroy(struct sip_pvt *p, int ms)
3148 if (ms < 0) {
3149 if (p->timer_t1 == 0) {
3150 p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
3151 p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
3153 ms = p->timer_t1 * 64;
3155 if (sip_debug_test_pvt(p))
3156 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3157 if (sip_cancel_destroy(p))
3158 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3160 if (p->do_history)
3161 append_history(p, "SchedDestroy", "%d ms", ms);
3162 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3164 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
3165 stop_session_timer(p);
3168 /*! \brief Cancel destruction of SIP dialog.
3169 * Be careful as this also absorbs the reference - if you call it
3170 * from within the scheduler, this might be the last reference.
3172 static int sip_cancel_destroy(struct sip_pvt *p)
3174 int res = 0;
3175 if (p->autokillid > -1) {
3176 int res3;
3178 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3179 append_history(p, "CancelDestroy", "");
3180 p->autokillid = -1;
3181 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3184 return res;
3187 /*! \brief Acknowledges receipt of a packet and stops retransmission
3188 * called with p locked*/
3189 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3191 struct sip_pkt *cur, *prev = NULL;
3192 const char *msg = "Not Found"; /* used only for debugging */
3194 /* If we have an outbound proxy for this dialog, then delete it now since
3195 the rest of the requests in this dialog needs to follow the routing.
3196 If obforcing is set, we will keep the outbound proxy during the whole
3197 dialog, regardless of what the SIP rfc says
3199 if (p->outboundproxy && !p->outboundproxy->force)
3200 p->outboundproxy = NULL;
3202 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3203 if (cur->seqno != seqno || cur->is_resp != resp)
3204 continue;
3205 if (cur->is_resp || cur->method == sipmethod) {
3206 msg = "Found";
3207 if (!resp && (seqno == p->pendinginvite)) {
3208 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3209 p->pendinginvite = 0;
3211 if (cur->retransid > -1) {
3212 if (sipdebug)
3213 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3215 /* This odd section is designed to thwart a
3216 * race condition in the packet scheduler. There are
3217 * two conditions under which deleting the packet from the
3218 * scheduler can fail.
3220 * 1. The packet has been removed from the scheduler because retransmission
3221 * is being attempted. The problem is that if the packet is currently attempting
3222 * retransmission and we are at this point in the code, then that MUST mean
3223 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3224 * lock temporarily to allow retransmission.
3226 * 2. The packet has reached its maximum number of retransmissions and has
3227 * been permanently removed from the packet scheduler. If this is the case, then
3228 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3229 * of the retransid to -1 is ensured since in both cases p's lock is held.
3231 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3232 sip_pvt_unlock(p);
3233 usleep(1);
3234 sip_pvt_lock(p);
3236 UNLINK(cur, p->packets, prev);
3237 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3238 if (cur->data)
3239 ast_free(cur->data);
3240 ast_free(cur);
3241 break;
3244 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3245 p->callid, resp ? "Response" : "Request", seqno, msg);
3248 /*! \brief Pretend to ack all packets
3249 * called with p locked */
3250 static void __sip_pretend_ack(struct sip_pvt *p)
3252 struct sip_pkt *cur = NULL;
3254 while (p->packets) {
3255 int method;
3256 if (cur == p->packets) {
3257 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
3258 return;
3260 cur = p->packets;
3261 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
3262 __sip_ack(p, cur->seqno, cur->is_resp, method);
3266 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
3267 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3269 struct sip_pkt *cur;
3270 int res = -1;
3272 for (cur = p->packets; cur; cur = cur->next) {
3273 if (cur->seqno == seqno && cur->is_resp == resp &&
3274 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
3275 /* this is our baby */
3276 if (cur->retransid > -1) {
3277 if (sipdebug)
3278 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
3280 AST_SCHED_DEL(sched, cur->retransid);
3281 res = 0;
3282 break;
3285 ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
3286 return res;
3290 /*! \brief Copy SIP request, parse it */
3291 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3293 copy_request(dst, src);
3294 parse_request(dst);
3297 /*! \brief add a blank line if no body */
3298 static void add_blank(struct sip_request *req)
3300 if (!req->lines) {
3301 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3302 ast_str_append(&req->data, 0, "\r\n");
3303 req->len = req->data->used;
3307 /*! \brief Transmit response on SIP request*/
3308 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3310 int res;
3312 add_blank(req);
3313 if (sip_debug_test_pvt(p)) {
3314 const struct sockaddr_in *dst = sip_real_dst(p);
3316 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
3317 reliable ? "Reliably " : "", sip_nat_mode(p),
3318 ast_inet_ntoa(dst->sin_addr),
3319 ntohs(dst->sin_port), req->data->str);
3321 if (p->do_history) {
3322 struct sip_request tmp = { .rlPart1 = NULL, };
3323 parse_copy(&tmp, req);
3324 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
3325 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
3326 ast_free(tmp.data);
3328 res = (reliable) ?
3329 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3330 __sip_xmit(p, req->data, req->len);
3331 ast_free(req->data);
3332 req->data = NULL;
3333 if (res > 0)
3334 return 0;
3335 return res;
3338 /*! \brief Send SIP Request to the other part of the dialogue */
3339 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3341 int res;
3343 /* If we have an outbound proxy, reset peer address
3344 Only do this once.
3346 if (p->outboundproxy) {
3347 p->sa = p->outboundproxy->ip;
3350 add_blank(req);
3351 if (sip_debug_test_pvt(p)) {
3352 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
3353 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
3354 else
3355 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
3357 if (p->do_history) {
3358 struct sip_request tmp = { .rlPart1 = NULL, };
3359 parse_copy(&tmp, req);
3360 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3361 ast_free(tmp.data);
3363 res = (reliable) ?
3364 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3365 __sip_xmit(p, req->data, req->len);
3366 if (req->data) {
3367 ast_free(req->data);
3368 req->data = NULL;
3370 return res;
3373 /*! \brief Query an option on a SIP dialog */
3374 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3376 int res = -1;
3377 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
3378 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
3380 switch (option) {
3381 case AST_OPTION_T38_STATE:
3382 /* Make sure we got an ast_t38_state enum passed in */
3383 if (*datalen != sizeof(enum ast_t38_state)) {
3384 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
3385 return -1;
3388 sip_pvt_lock(p);
3390 /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
3391 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT)) {
3392 switch (p->t38.state) {
3393 case T38_LOCAL_DIRECT:
3394 case T38_LOCAL_REINVITE:
3395 case T38_PEER_DIRECT:
3396 case T38_PEER_REINVITE:
3397 state = T38_STATE_NEGOTIATING;
3398 break;
3399 case T38_ENABLED:
3400 state = T38_STATE_NEGOTIATED;
3401 break;
3402 default:
3403 state = T38_STATE_UNKNOWN;
3407 sip_pvt_unlock(p);
3409 *((enum ast_t38_state *) data) = state;
3410 res = 0;
3412 break;
3413 default:
3414 break;
3417 return res;
3420 /*! \brief Locate closing quote in a string, skipping escaped quotes.
3421 * optionally with a limit on the search.
3422 * start must be past the first quote.
3424 static const char *find_closing_quote(const char *start, const char *lim)
3426 char last_char = '\0';
3427 const char *s;
3428 for (s = start; *s && s != lim; last_char = *s++) {
3429 if (*s == '"' && last_char != '\\')
3430 break;
3432 return s;
3435 /*! \brief Pick out text in brackets from character string
3436 \return pointer to terminated stripped string
3437 \param tmp input string that will be modified
3438 Examples:
3439 \verbatim
3440 "foo" <bar> valid input, returns bar
3441 foo returns the whole string
3442 < "foo ... > returns the string between brackets
3443 < "foo... bogus (missing closing bracket), returns the whole string
3444 XXX maybe should still skip the opening bracket
3445 \endverbatim
3447 static char *get_in_brackets(char *tmp)
3449 const char *parse = tmp;
3450 char *first_bracket;
3453 * Skip any quoted text until we find the part in brackets.
3454 * On any error give up and return the full string.
3456 while ( (first_bracket = strchr(parse, '<')) ) {
3457 char *first_quote = strchr(parse, '"');
3459 if (!first_quote || first_quote > first_bracket)
3460 break; /* no need to look at quoted part */
3461 /* the bracket is within quotes, so ignore it */
3462 parse = find_closing_quote(first_quote + 1, NULL);
3463 if (!*parse) { /* not found, return full string ? */
3464 /* XXX or be robust and return in-bracket part ? */
3465 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
3466 break;
3468 parse++;
3470 if (first_bracket) {
3471 char *second_bracket = strchr(first_bracket + 1, '>');
3472 if (second_bracket) {
3473 *second_bracket = '\0';
3474 tmp = first_bracket + 1;
3475 } else {
3476 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
3480 return tmp;
3483 /*! \brief * parses a URI in its components.
3485 * \note
3486 * - If scheme is specified, drop it from the top.
3487 * - If a component is not requested, do not split around it.
3489 * This means that if we don't have domain, we cannot split
3490 * name:pass and domain:port.
3491 * It is safe to call with ret_name, pass, domain, port
3492 * pointing all to the same place.
3493 * Init pointers to empty string so we never get NULL dereferencing.
3494 * Overwrites the string.
3495 * return 0 on success, other values on error.
3496 * \verbatim
3497 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
3498 * \endverbatim
3500 static int parse_uri(char *uri, char *scheme,
3501 char **ret_name, char **pass, char **domain, char **port, char **options)
3503 char *name = NULL;
3504 int error = 0;
3506 /* init field as required */
3507 if (pass)
3508 *pass = "";
3509 if (port)
3510 *port = "";
3511 if (scheme) {
3512 int l = strlen(scheme);
3513 if (!strncasecmp(uri, scheme, l))
3514 uri += l;
3515 else {
3516 ast_debug(1, "Missing scheme '%s' in '%s'\n", scheme, uri);
3517 error = -1;
3520 if (!domain) {
3521 /* if we don't want to split around domain, keep everything as a name,
3522 * so we need to do nothing here, except remember why.
3524 } else {
3525 /* store the result in a temp. variable to avoid it being
3526 * overwritten if arguments point to the same place.
3528 char *c, *dom = "";
3530 if ((c = strchr(uri, '@')) == NULL) {
3531 /* domain-only URI, according to the SIP RFC. */
3532 dom = uri;
3533 name = "";
3534 } else {
3535 *c++ = '\0';
3536 dom = c;
3537 name = uri;
3540 /* Remove options in domain and name */
3541 dom = strsep(&dom, ";");
3542 name = strsep(&name, ";");
3544 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
3545 *c++ = '\0';
3546 *port = c;
3548 if (pass && (c = strchr(name, ':'))) { /* user:password */
3549 *c++ = '\0';
3550 *pass = c;
3552 *domain = dom;
3554 if (ret_name) /* same as for domain, store the result only at the end */
3555 *ret_name = name;
3556 if (options)
3557 *options = uri ? uri : "";
3559 return error;
3562 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
3563 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3565 struct sip_pvt *p = chan->tech_pvt;
3567 if (subclass != AST_HTML_URL)
3568 return -1;
3570 ast_string_field_build(p, url, "<%s>;mode=active", data);
3572 if (sip_debug_test_pvt(p))
3573 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
3575 switch (chan->_state) {
3576 case AST_STATE_RING:
3577 transmit_response(p, "100 Trying", &p->initreq);
3578 break;
3579 case AST_STATE_RINGING:
3580 transmit_response(p, "180 Ringing", &p->initreq);
3581 break;
3582 case AST_STATE_UP:
3583 if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
3584 transmit_reinvite_with_sdp(p, FALSE, FALSE);
3585 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
3586 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
3588 break;
3589 default:
3590 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
3593 return 0;
3596 /*! \brief Deliver SIP call ID for the call */
3597 static const char *sip_get_callid(struct ast_channel *chan)
3599 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
3602 /*! \brief Send SIP MESSAGE text within a call
3603 Called from PBX core sendtext() application */
3604 static int sip_sendtext(struct ast_channel *ast, const char *text)
3606 struct sip_pvt *p = ast->tech_pvt;
3607 int debug = sip_debug_test_pvt(p);
3609 if (debug)
3610 ast_verbose("Sending text %s on %s\n", text, ast->name);
3611 if (!p)
3612 return -1;
3613 if (ast_strlen_zero(text))
3614 return 0;
3615 if (debug)
3616 ast_verbose("Really sending text %s on %s\n", text, ast->name);
3617 transmit_message_with_text(p, text);
3618 return 0;
3621 /*! \brief Update peer object in realtime storage
3622 If the Asterisk system name is set in asterisk.conf, we will use
3623 that name and store that in the "regserver" field in the sippeers
3624 table to facilitate multi-server setups.
3626 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, int deprecated_username)
3628 char port[10];
3629 char ipaddr[INET_ADDRSTRLEN];
3630 char regseconds[20];
3631 char *tablename = NULL;
3633 const char *sysname = ast_config_AST_SYSTEM_NAME;
3634 char *syslabel = NULL;
3636 time_t nowtime = time(NULL) + expirey;
3637 const char *fc = fullcontact ? "fullcontact" : NULL;
3639 int realtimeregs = ast_check_realtime("sipregs");
3641 tablename = realtimeregs ? "sipregs" : "sippeers";
3643 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
3644 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3645 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3647 if (ast_strlen_zero(sysname)) /* No system name, disable this */
3648 sysname = NULL;
3649 else if (sip_cfg.rtsave_sysname)
3650 syslabel = "regserver";
3652 if (fc) {
3653 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3654 "port", port, "regseconds", regseconds,
3655 deprecated_username ? "username" : "defaultuser", defaultuser,
3656 "useragent", useragent,
3657 fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
3658 } else {
3659 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3660 "port", port, "regseconds", regseconds,
3661 "useragent", useragent,
3662 deprecated_username ? "username" : "defaultuser", defaultuser,
3663 syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
3667 /*! \brief Automatically add peer extension to dial plan */
3668 static void register_peer_exten(struct sip_peer *peer, int onoff)
3670 char multi[256];
3671 char *stringp, *ext, *context;
3672 struct pbx_find_info q = { .stacklen = 0 };
3674 /* XXX note that global_regcontext is both a global 'enable' flag and
3675 * the name of the global regexten context, if not specified
3676 * individually.
3678 if (ast_strlen_zero(global_regcontext))
3679 return;
3681 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
3682 stringp = multi;
3683 while ((ext = strsep(&stringp, "&"))) {
3684 if ((context = strchr(ext, '@'))) {
3685 *context++ = '\0'; /* split ext@context */
3686 if (!ast_context_find(context)) {
3687 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
3688 continue;
3690 } else {
3691 context = global_regcontext;
3693 if (onoff) {
3694 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
3695 ast_strdup(peer->name), ast_free_ptr, "SIP");
3696 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
3697 ast_context_remove_extension(context, ext, 1, NULL);
3702 /*! Destroy mailbox subscriptions */
3703 static void destroy_mailbox(struct sip_mailbox *mailbox)
3705 if (mailbox->mailbox)
3706 ast_free(mailbox->mailbox);
3707 if (mailbox->context)
3708 ast_free(mailbox->context);
3709 if (mailbox->event_sub)
3710 ast_event_unsubscribe(mailbox->event_sub);
3711 ast_free(mailbox);
3714 /*! Destroy all peer-related mailbox subscriptions */
3715 static void clear_peer_mailboxes(struct sip_peer *peer)
3717 struct sip_mailbox *mailbox;
3719 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
3720 destroy_mailbox(mailbox);
3723 static void sip_destroy_peer_fn(void *peer)
3725 sip_destroy_peer(peer);
3728 /*! \brief Destroy peer object from memory */
3729 static void sip_destroy_peer(struct sip_peer *peer)
3731 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
3732 if (peer->outboundproxy)
3733 ast_free(peer->outboundproxy);
3734 peer->outboundproxy = NULL;
3736 /* Delete it, it needs to disappear */
3737 if (peer->call) {
3738 dialog_unlink_all(peer->call, TRUE, TRUE);
3739 peer->call = dialog_unref(peer->call, "peer->call is being unset");
3743 if (peer->mwipvt) { /* We have an active subscription, delete it */
3744 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
3745 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
3748 if (peer->chanvars) {
3749 ast_variables_destroy(peer->chanvars);
3750 peer->chanvars = NULL;
3753 /* If the schedule delete fails, that means the schedule is currently
3754 * running, which means we should wait for that thread to complete.
3755 * Otherwise, there's a crashable race condition.
3757 * NOTE: once peer is refcounted, this probably is no longer necessary.
3759 AST_SCHED_DEL(sched, peer->expire);
3760 AST_SCHED_DEL(sched, peer->pokeexpire);
3762 register_peer_exten(peer, FALSE);
3763 ast_free_ha(peer->ha);
3764 if (peer->selfdestruct)
3765 ast_atomic_fetchadd_int(&apeerobjs, -1);
3766 else if (peer->is_realtime) {
3767 ast_atomic_fetchadd_int(&rpeerobjs, -1);
3768 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
3769 } else
3770 ast_atomic_fetchadd_int(&speerobjs, -1);
3771 clear_realm_authentication(peer->auth);
3772 peer->auth = NULL;
3773 if (peer->dnsmgr)
3774 ast_dnsmgr_release(peer->dnsmgr);
3775 clear_peer_mailboxes(peer);
3777 if (peer->socket.ser) {
3778 ao2_ref(peer->socket.ser, -1);
3779 peer->socket.ser = NULL;
3783 /*! \brief Update peer data in database (if used) */
3784 static void update_peer(struct sip_peer *p, int expiry)
3786 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
3787 if (sip_cfg.peer_rtupdate &&
3788 (p->is_realtime || rtcachefriends)) {
3789 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expiry, p->deprecated_username);
3793 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config)
3795 struct ast_variable *var = NULL;
3796 struct ast_flags flags = {0};
3797 char *cat = NULL;
3798 const char *insecure;
3799 while ((cat = ast_category_browse(config, cat))) {
3800 insecure = ast_variable_retrieve(config, cat, "insecure");
3801 set_insecure_flags(&flags, insecure, -1);
3802 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
3803 var = ast_category_root(config, cat);
3804 break;
3807 return var;
3810 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
3812 struct ast_variable *tmp;
3813 for (tmp = var; tmp; tmp = tmp->next) {
3814 if (!newpeername && !strcasecmp(tmp->name, "name"))
3815 newpeername = tmp->value;
3817 return newpeername;
3820 /*! \brief realtime_peer: Get peer from realtime storage
3821 * Checks the "sippeers" realtime family from extconfig.conf
3822 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
3823 * This returns a pointer to a peer and because we use build_peer, we can rest
3824 * assured that the refcount is bumped.
3826 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
3828 struct sip_peer *peer;
3829 struct ast_variable *var = NULL;
3830 struct ast_variable *varregs = NULL;
3831 struct ast_variable *tmp;
3832 struct ast_config *peerlist = NULL;
3833 char ipaddr[INET_ADDRSTRLEN];
3834 char portstring[6]; /*up to 5 digits plus null terminator*/
3835 char *cat = NULL;
3836 unsigned short portnum;
3837 int realtimeregs = ast_check_realtime("sipregs");
3839 /* First check on peer name */
3840 if (newpeername) {
3841 if (realtimeregs)
3842 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3844 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
3845 if (!var && sin)
3846 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
3847 if (!var) {
3848 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
3849 /*!\note
3850 * If this one loaded something, then we need to ensure that the host
3851 * field matched. The only reason why we can't have this as a criteria
3852 * is because we only have the IP address and the host field might be
3853 * set as a name (and the reverse PTR might not match).
3855 if (var && sin) {
3856 for (tmp = var; tmp; tmp = tmp->next) {
3857 if (!strcasecmp(tmp->name, "host")) {
3858 struct hostent *hp;
3859 struct ast_hostent ahp;
3860 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3861 /* No match */
3862 ast_variables_destroy(var);
3863 var = NULL;
3865 break;
3872 if (!var && sin) { /* Then check on IP address for dynamic peers */
3873 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3874 portnum = ntohs(sin->sin_port);
3875 sprintf(portstring, "%u", portnum);
3876 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL); /* First check for fixed IP hosts */
3877 if (var) {
3878 if (realtimeregs) {
3879 newpeername = get_name_from_variable(var, newpeername);
3880 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3882 } else {
3883 if (realtimeregs)
3884 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
3885 else
3886 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
3887 if (varregs) {
3888 newpeername = get_name_from_variable(varregs, newpeername);
3889 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
3892 if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
3893 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
3894 if (peerlist) {
3895 var = get_insecure_variable_from_config(peerlist);
3896 if(var) {
3897 if (realtimeregs) {
3898 newpeername = get_name_from_variable(var, newpeername);
3899 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3901 } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
3902 peerlist = NULL;
3903 cat = NULL;
3904 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
3905 if(peerlist) {
3906 var = get_insecure_variable_from_config(peerlist);
3907 if(var) {
3908 if (realtimeregs) {
3909 newpeername = get_name_from_variable(var, newpeername);
3910 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3915 } else {
3916 if (realtimeregs) {
3917 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
3918 if (peerlist) {
3919 varregs = get_insecure_variable_from_config(peerlist);
3920 if (varregs) {
3921 newpeername = get_name_from_variable(varregs, newpeername);
3922 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
3925 } else {
3926 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
3927 if (peerlist) {
3928 var = get_insecure_variable_from_config(peerlist);
3929 if (var) {
3930 newpeername = get_name_from_variable(var, newpeername);
3931 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3939 if (!var) {
3940 if (peerlist)
3941 ast_config_destroy(peerlist);
3942 return NULL;
3945 for (tmp = var; tmp; tmp = tmp->next) {
3946 /* If this is type=user, then skip this object. */
3947 if (!strcasecmp(tmp->name, "type") &&
3948 !strcasecmp(tmp->value, "user")) {
3949 if(peerlist)
3950 ast_config_destroy(peerlist);
3951 else {
3952 ast_variables_destroy(var);
3953 ast_variables_destroy(varregs);
3955 return NULL;
3956 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
3957 newpeername = tmp->value;
3961 if (!newpeername) { /* Did not find peer in realtime */
3962 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
3963 if(peerlist)
3964 ast_config_destroy(peerlist);
3965 else
3966 ast_variables_destroy(var);
3967 return NULL;
3971 /* Peer found in realtime, now build it in memory */
3972 peer = build_peer(newpeername, var, varregs, TRUE, FALSE);
3973 if (!peer) {
3974 if(peerlist)
3975 ast_config_destroy(peerlist);
3976 else {
3977 ast_variables_destroy(var);
3978 ast_variables_destroy(varregs);
3980 return NULL;
3983 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
3985 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
3986 /* Cache peer */
3987 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
3988 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
3989 AST_SCHED_REPLACE(peer->expire, sched, global_rtautoclear * 1000, expire_register, (void *) peer);
3990 /* we could be incr. its refcount right here, but I guess, since
3991 peers hang around until module unload time anyway, it's not worth the trouble */
3993 ao2_t_link(peers, peer, "link peer into peers table");
3994 if (peer->addr.sin_addr.s_addr) {
3995 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
3998 } else {
3999 peer->is_realtime = 1;
4001 if (peerlist)
4002 ast_config_destroy(peerlist);
4003 else {
4004 ast_variables_destroy(var);
4005 ast_variables_destroy(varregs);
4008 return peer;
4011 /*! \brief Locate device by name or ip address
4012 * This is used on find matching device on name or ip/port.
4013 If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
4015 \note Avoid using this function in new functions if there is a way to avoid it, i
4016 since it might cause a database lookup.
4018 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch)
4020 struct sip_peer *p = NULL;
4021 struct sip_peer tmp_peer;
4023 if (peer) {
4024 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
4025 p = ao2_t_find(peers, &tmp_peer, OBJ_POINTER, "ao2_find in peers table");
4026 } else if (sin) { /* search by addr? */
4027 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
4028 tmp_peer.addr.sin_port = sin->sin_port;
4029 tmp_peer.flags[0].flags = 0;
4030 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS: p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
4031 if (!p) {
4032 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
4033 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS: p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
4034 if (p) {
4035 return p;
4040 if (!p && realtime)
4041 p = realtime_peer(peer, sin);
4043 return p;
4046 /*! \brief Set nat mode on the various data sockets */
4047 static void do_setnat(struct sip_pvt *p, int natflags)
4049 const char *mode = natflags ? "On" : "Off";
4051 if (p->rtp) {
4052 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
4053 ast_rtp_setnat(p->rtp, natflags);
4055 if (p->vrtp) {
4056 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
4057 ast_rtp_setnat(p->vrtp, natflags);
4059 if (p->udptl) {
4060 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
4061 ast_udptl_setnat(p->udptl, natflags);
4063 if (p->trtp) {
4064 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
4065 ast_rtp_setnat(p->trtp, natflags);
4069 /*! \brief Change the T38 state on a SIP dialog */
4070 static void change_t38_state(struct sip_pvt *p, int state)
4072 int old = p->t38.state;
4073 struct ast_channel *chan = p->owner;
4074 enum ast_control_t38 message = 0;
4076 /* Don't bother changing if we are already in the state wanted */
4077 if (old == state)
4078 return;
4080 p->t38.state = state;
4081 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
4083 /* If no channel was provided we can't send off a control frame */
4084 if (!chan)
4085 return;
4087 /* Given the state requested and old state determine what control frame we want to queue up */
4088 if (state == T38_ENABLED)
4089 message = AST_T38_NEGOTIATED;
4090 else if (state == T38_DISABLED && old == T38_ENABLED)
4091 message = AST_T38_TERMINATED;
4092 else if (state == T38_DISABLED && old == T38_LOCAL_REINVITE)
4093 message = AST_T38_REFUSED;
4095 /* Woot we got a message, create a control frame and send it on! */
4096 if (message)
4097 ast_queue_control_data(chan, AST_CONTROL_T38, &message, sizeof(message));
4100 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
4101 static void set_t38_capabilities(struct sip_pvt *p)
4103 p->t38.capability = global_t38_capability;
4104 if (p->udptl) {
4105 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC )
4106 p->t38.capability |= T38FAX_UDP_EC_FEC;
4107 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
4108 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4109 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE )
4110 p->t38.capability |= T38FAX_UDP_EC_NONE;
4111 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4115 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
4117 if (to_sock->ser) {
4118 ao2_ref(to_sock->ser, -1);
4119 to_sock->ser = NULL;
4122 if (from_sock->ser) {
4123 ao2_ref(from_sock->ser, +1);
4126 *to_sock = *from_sock;
4129 /*! \brief Create address structure from peer reference.
4130 * This function copies data from peer to the dialog, so we don't have to look up the peer
4131 * again from memory or database during the life time of the dialog.
4133 * \return -1 on error, 0 on success.
4136 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
4138 copy_socket_data(&dialog->socket, &peer->socket);
4140 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
4141 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
4142 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
4143 dialog->recv = dialog->sa;
4144 } else
4145 return -1;
4147 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
4148 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4149 dialog->capability = peer->capability;
4150 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
4151 ast_rtp_destroy(dialog->vrtp);
4152 dialog->vrtp = NULL;
4154 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
4155 ast_rtp_destroy(dialog->trtp);
4156 dialog->trtp = NULL;
4158 dialog->prefs = peer->prefs;
4159 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
4160 ast_copy_flags(&dialog->t38.t38support, &peer->flags[1], SIP_PAGE2_T38SUPPORT);
4161 set_t38_capabilities(dialog);
4162 dialog->t38.jointcapability = dialog->t38.capability;
4163 } else if (dialog->udptl) {
4164 ast_udptl_destroy(dialog->udptl);
4165 dialog->udptl = NULL;
4167 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4169 if (dialog->rtp) { /* Audio */
4170 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4171 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4172 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
4173 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
4174 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
4175 /* Set Frame packetization */
4176 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
4177 dialog->autoframing = peer->autoframing;
4179 if (dialog->vrtp) { /* Video */
4180 ast_rtp_setdtmf(dialog->vrtp, 0);
4181 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
4182 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
4183 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
4184 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
4186 if (dialog->trtp) { /* Realtime text */
4187 ast_rtp_setdtmf(dialog->trtp, 0);
4188 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
4189 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
4190 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
4191 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
4194 ast_string_field_set(dialog, peername, peer->name);
4195 ast_string_field_set(dialog, authname, peer->username);
4196 ast_string_field_set(dialog, username, peer->username);
4197 ast_string_field_set(dialog, peersecret, peer->secret);
4198 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
4199 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
4200 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
4201 ast_string_field_set(dialog, tohost, peer->tohost);
4202 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
4203 ast_string_field_set(dialog, context, peer->context);
4204 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
4205 dialog->outboundproxy = obproxy_get(dialog, peer);
4206 dialog->callgroup = peer->callgroup;
4207 dialog->pickupgroup = peer->pickupgroup;
4208 dialog->allowtransfer = peer->allowtransfer;
4209 dialog->jointnoncodeccapability = dialog->noncodeccapability;
4210 dialog->rtptimeout = peer->rtptimeout;
4211 dialog->peerauth = peer->auth;
4212 dialog->maxcallbitrate = peer->maxcallbitrate;
4213 if (ast_strlen_zero(dialog->tohost))
4214 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
4215 if (!ast_strlen_zero(peer->fromdomain)) {
4216 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
4217 if (!dialog->initreq.headers) {
4218 char *c;
4219 char *tmpcall = ast_strdupa(dialog->callid);
4220 /* this sure looks to me like we are going to change the callid on this dialog!! */
4221 c = strchr(tmpcall, '@');
4222 if (c) {
4223 *c = '\0';
4224 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
4225 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
4226 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
4230 if (!ast_strlen_zero(peer->fromuser))
4231 ast_string_field_set(dialog, fromuser, peer->fromuser);
4232 if (!ast_strlen_zero(peer->language))
4233 ast_string_field_set(dialog, language, peer->language);
4234 /* Set timer T1 to RTT for this peer (if known by qualify=) */
4235 /* Minimum is settable or default to 100 ms */
4236 /* If there is a maxms and lastms from a qualify use that over a manual T1
4237 value. Otherwise, use the peer's T1 value. */
4238 if (peer->maxms && peer->lastms)
4239 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
4240 else
4241 dialog->timer_t1 = peer->timer_t1;
4243 /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
4244 the known timer */
4245 if (peer->timer_b)
4246 dialog->timer_b = peer->timer_b;
4247 else
4248 dialog->timer_b = 64 * dialog->timer_t1;
4250 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4251 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4252 dialog->noncodeccapability |= AST_RTP_DTMF;
4253 else
4254 dialog->noncodeccapability &= ~AST_RTP_DTMF;
4255 if (peer->call_limit)
4256 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
4258 return 0;
4260 /*! \brief create address structure from device name
4261 * Or, if peer not found, find it in the global DNS
4262 * returns TRUE (-1) on failure, FALSE on success */
4263 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin)
4265 struct hostent *hp;
4266 struct ast_hostent ahp;
4267 struct sip_peer *peer;
4268 char *port;
4269 int portno;
4270 char host[MAXHOSTNAMELEN], *hostn;
4271 char peername[256];
4272 int srv_ret = 0;
4274 ast_copy_string(peername, opeer, sizeof(peername));
4275 port = strchr(peername, ':');
4276 if (port)
4277 *port++ = '\0';
4278 dialog->sa.sin_family = AF_INET;
4279 dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
4280 dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
4281 peer = find_peer(peername, NULL, TRUE, TRUE);
4283 if (peer) {
4284 int res = create_addr_from_peer(dialog, peer);
4285 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
4286 return res;
4287 } else {
4288 /* Setup default parameters for this dialog's socket. Currently we only support regular UDP SIP as the default */
4289 dialog->socket.type = SIP_TRANSPORT_UDP;
4290 dialog->socket.port = bindaddr.sin_port;
4293 ast_string_field_set(dialog, tohost, peername);
4295 /* Get the outbound proxy information */
4296 dialog->outboundproxy = obproxy_get(dialog, NULL);
4298 /* If we have an outbound proxy, don't bother with DNS resolution at all */
4299 if (dialog->outboundproxy)
4300 return 0;
4302 /* This address should be updated using dnsmgr */
4303 if (sin) {
4304 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
4305 if (!sin->sin_port) {
4306 portno = port ? atoi(port) : (dialog->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
4307 } else {
4308 portno = ntohs(sin->sin_port);
4310 } else {
4312 /* Let's see if we can find the host in DNS. First try DNS SRV records,
4313 then hostname lookup */
4314 /*! \todo Fix this function. When we ask SRC, we should check all transports
4315 In the future, we should first check NAPTR to find out transport preference
4317 hostn = peername;
4318 portno = port ? atoi(port) : (dialog->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
4319 if (global_srvlookup) {
4320 char service[MAXHOSTNAMELEN];
4321 int tportno;
4323 snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
4324 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
4325 if (srv_ret > 0) {
4326 hostn = host;
4327 portno = tportno;
4331 hp = ast_gethostbyname(hostn, &ahp);
4332 if (!hp) {
4333 ast_log(LOG_WARNING, "No such host: %s\n", peername);
4334 return -1;
4336 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
4339 dialog->sa.sin_port = htons(portno);
4340 dialog->recv = dialog->sa;
4341 return 0;
4344 /*! \brief Scheduled congestion on a call.
4345 * Only called by the scheduler, must return the reference when done.
4347 static int auto_congest(const void *arg)
4349 struct sip_pvt *p = (struct sip_pvt *)arg;
4351 sip_pvt_lock(p);
4352 p->initid = -1; /* event gone, will not be rescheduled */
4353 if (p->owner) {
4354 /* XXX fails on possible deadlock */
4355 if (!ast_channel_trylock(p->owner)) {
4356 append_history(p, "Cong", "Auto-congesting (timer)");
4357 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
4358 ast_channel_unlock(p->owner);
4361 sip_pvt_unlock(p);
4362 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
4363 return 0;
4367 /*! \brief Initiate SIP call from PBX
4368 * used from the dial() application */
4369 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
4371 int res;
4372 struct sip_pvt *p = ast->tech_pvt; /* chan is locked, so the reference cannot go away */
4373 struct varshead *headp;
4374 struct ast_var_t *current;
4375 const char *referer = NULL; /* SIP referrer */
4377 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
4378 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
4379 return -1;
4382 /* Check whether there is vxml_url, distinctive ring variables */
4383 headp=&ast->varshead;
4384 AST_LIST_TRAVERSE(headp, current, entries) {
4385 /* Check whether there is a VXML_URL variable */
4386 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
4387 p->options->vxml_url = ast_var_value(current);
4388 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
4389 p->options->uri_options = ast_var_value(current);
4390 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
4391 /* Check whether there is a variable with a name starting with SIPADDHEADER */
4392 p->options->addsipheaders = 1;
4393 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
4394 /* This is a transfered call */
4395 p->options->transfer = 1;
4396 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
4397 /* This is the referrer */
4398 referer = ast_var_value(current);
4399 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
4400 /* We're replacing a call. */
4401 p->options->replaces = ast_var_value(current);
4402 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
4403 p->t38.state = T38_LOCAL_DIRECT;
4404 ast_debug(1, "T38State change to %d on channel %s\n", p->t38.state, ast->name);
4409 res = 0;
4410 ast_set_flag(&p->flags[0], SIP_OUTGOING);
4412 if (p->options->transfer) {
4413 char buf[SIPBUFSIZE/2];
4415 if (referer) {
4416 if (sipdebug)
4417 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
4418 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
4419 } else
4420 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
4421 ast_string_field_set(p, cid_name, buf);
4423 ast_debug(1, "Outgoing Call for %s\n", p->username);
4425 res = update_call_counter(p, INC_CALL_RINGING);
4427 if (res == -1)
4428 return res;
4430 p->callingpres = ast->cid.cid_pres;
4431 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
4432 p->jointnoncodeccapability = p->noncodeccapability;
4434 /* If there are no audio formats left to offer, punt */
4435 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
4436 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
4437 res = -1;
4438 } else {
4439 int xmitres;
4441 p->t38.jointcapability = p->t38.capability;
4442 ast_debug(2, "Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
4444 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
4445 if (xmitres == XMIT_ERROR)
4446 return -1;
4447 p->invitestate = INV_CALLING;
4449 /* Initialize auto-congest time */
4450 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
4451 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
4452 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
4453 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
4455 return res;
4458 /*! \brief Destroy registry object
4459 Objects created with the register= statement in static configuration */
4460 static void sip_registry_destroy(struct sip_registry *reg)
4462 /* Really delete */
4463 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
4465 if (reg->call) {
4466 /* Clear registry before destroying to ensure
4467 we don't get reentered trying to grab the registry lock */
4468 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
4469 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
4470 dialog_unlink_all(reg->call, TRUE, TRUE);
4471 reg->call = dialog_unref(reg->call, "unref reg->call");
4472 /* reg->call = sip_destroy(reg->call); */
4474 AST_SCHED_DEL(sched, reg->expire);
4475 AST_SCHED_DEL(sched, reg->timeout);
4477 ast_string_field_free_memory(reg);
4478 ast_atomic_fetchadd_int(&regobjs, -1);
4479 ast_dnsmgr_release(reg->dnsmgr);
4480 ast_free(reg);
4484 /*! \brief Execute destruction of SIP dialog structure, release memory */
4485 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
4488 if (sip_debug_test_pvt(p))
4489 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
4491 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4492 update_call_counter(p, DEC_CALL_LIMIT);
4493 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
4496 /* Unlink us from the owner if we have one */
4497 if (p->owner) {
4498 if (lockowner)
4499 ast_channel_lock(p->owner);
4500 if (option_debug)
4501 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
4502 p->owner->tech_pvt = NULL;
4503 /* Make sure that the channel knows its backend is going away */
4504 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
4505 if (lockowner)
4506 ast_channel_unlock(p->owner);
4507 /* Give the channel a chance to react before deallocation */
4508 usleep(1);
4511 /* Remove link from peer to subscription of MWI */
4512 if (p->relatedpeer && p->relatedpeer->mwipvt)
4513 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
4514 if (p->relatedpeer && p->relatedpeer->call == p)
4515 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
4517 if (p->relatedpeer)
4518 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
4520 if (p->registry) {
4521 if (p->registry->call == p)
4522 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
4523 p->registry = registry_unref(p->registry, "delete p->registry");
4526 if (dumphistory)
4527 sip_dump_history(p);
4529 if (p->options)
4530 ast_free(p->options);
4532 if (p->notify_headers) {
4533 ast_variables_destroy(p->notify_headers);
4534 p->notify_headers = NULL;
4536 if (p->rtp) {
4537 ast_rtp_destroy(p->rtp);
4539 if (p->vrtp) {
4540 ast_rtp_destroy(p->vrtp);
4542 if (p->trtp) {
4543 while (ast_rtp_get_bridged(p->trtp))
4544 usleep(1);
4545 ast_rtp_destroy(p->trtp);
4547 if (p->udptl)
4548 ast_udptl_destroy(p->udptl);
4549 if (p->refer)
4550 ast_free(p->refer);
4551 if (p->route) {
4552 free_old_route(p->route);
4553 p->route = NULL;
4555 if (p->initreq.data)
4556 ast_free(p->initreq.data);
4558 /* Destroy Session-Timers if allocated */
4559 if (p->stimer) {
4560 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1)
4561 AST_SCHED_DEL(sched, p->stimer->st_schedid);
4562 ast_free(p->stimer);
4563 p->stimer = NULL;
4566 /* Clear history */
4567 if (p->history) {
4568 struct sip_history *hist;
4569 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
4570 ast_free(hist);
4571 p->history_entries--;
4573 ast_free(p->history);
4574 p->history = NULL;
4577 if (p->chanvars) {
4578 ast_variables_destroy(p->chanvars);
4579 p->chanvars = NULL;
4582 ast_string_field_free_memory(p);
4584 if (p->socket.ser) {
4585 ao2_ref(p->socket.ser, -1);
4586 p->socket.ser = NULL;
4590 /*! \brief update_call_counter: Handle call_limit for SIP devices
4591 * Setting a call-limit will cause calls above the limit not to be accepted.
4593 * Remember that for a type=friend, there's one limit for the user and
4594 * another for the peer, not a combined call limit.
4595 * This will cause unexpected behaviour in subscriptions, since a "friend"
4596 * is *two* devices in Asterisk, not one.
4598 * Thought: For realtime, we should probably update storage with inuse counter...
4600 * \return 0 if call is ok (no call limit, below threshold)
4601 * -1 on rejection of call
4604 static int update_call_counter(struct sip_pvt *fup, int event)
4606 char name[256];
4607 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
4608 int outgoing = fup->outgoing_call;
4609 struct sip_peer *p = NULL;
4611 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
4614 /* Test if we need to check call limits, in order to avoid
4615 realtime lookups if we do not need it */
4616 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
4617 return 0;
4619 ast_copy_string(name, fup->username, sizeof(name));
4621 /* Check the list of devices */
4622 if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FALSE) ) ) { /* Try to find peer */
4623 inuse = &p->inUse;
4624 call_limit = &p->call_limit;
4625 inringing = &p->inRinging;
4626 ast_copy_string(name, fup->peername, sizeof(name));
4628 if (!p) {
4629 ast_debug(2, "%s is not a local device, no call limit\n", name);
4630 return 0;
4633 switch(event) {
4634 /* incoming and outgoing affects the inUse counter */
4635 case DEC_CALL_LIMIT:
4636 /* Decrement inuse count if applicable */
4637 if (inuse && ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
4638 ast_atomic_fetchadd_int(inuse, -1);
4639 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
4640 } else
4641 *inuse = 0;
4642 /* Decrement ringing count if applicable */
4643 if (inringing && ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
4644 ast_atomic_fetchadd_int(inringing, -1);
4645 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
4647 /* Decrement onhold count if applicable */
4648 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
4649 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
4650 sip_peer_hold(fup, FALSE);
4652 if (sipdebug)
4653 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
4654 break;
4656 case INC_CALL_RINGING:
4657 case INC_CALL_LIMIT:
4658 /* If call limit is active and we have reached the limit, reject the call */
4659 if (*call_limit > 0 ) {
4660 if (*inuse >= *call_limit) {
4661 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
4662 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
4663 return -1;
4666 if (inringing && (event == INC_CALL_RINGING)) {
4667 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
4668 ast_atomic_fetchadd_int(inringing, +1);
4669 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
4672 /* Continue */
4673 ast_atomic_fetchadd_int(inuse, +1);
4674 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
4675 if (sipdebug) {
4676 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
4678 break;
4680 case DEC_CALL_RINGING:
4681 if (inringing && ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
4682 ast_atomic_fetchadd_int(inringing, -1);
4683 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
4685 break;
4687 default:
4688 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
4690 if (p) {
4691 ast_device_state_changed("SIP/%s", p->name);
4692 unref_peer(p, "update_call_counter: unref_peer from call counter");
4694 return 0;
4698 static void sip_destroy_fn(void *p)
4700 sip_destroy(p);
4703 /*! \brief Destroy SIP call structure.
4704 * Make it return NULL so the caller can do things like
4705 * foo = sip_destroy(foo);
4706 * and reduce the chance of bugs due to dangling pointers.
4708 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
4710 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
4711 __sip_destroy(p, TRUE, TRUE);
4712 return NULL;
4715 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
4716 static int hangup_sip2cause(int cause)
4718 /* Possible values taken from causes.h */
4720 switch(cause) {
4721 case 401: /* Unauthorized */
4722 return AST_CAUSE_CALL_REJECTED;
4723 case 403: /* Not found */
4724 return AST_CAUSE_CALL_REJECTED;
4725 case 404: /* Not found */
4726 return AST_CAUSE_UNALLOCATED;
4727 case 405: /* Method not allowed */
4728 return AST_CAUSE_INTERWORKING;
4729 case 407: /* Proxy authentication required */
4730 return AST_CAUSE_CALL_REJECTED;
4731 case 408: /* No reaction */
4732 return AST_CAUSE_NO_USER_RESPONSE;
4733 case 409: /* Conflict */
4734 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
4735 case 410: /* Gone */
4736 return AST_CAUSE_UNALLOCATED;
4737 case 411: /* Length required */
4738 return AST_CAUSE_INTERWORKING;
4739 case 413: /* Request entity too large */
4740 return AST_CAUSE_INTERWORKING;
4741 case 414: /* Request URI too large */
4742 return AST_CAUSE_INTERWORKING;
4743 case 415: /* Unsupported media type */
4744 return AST_CAUSE_INTERWORKING;
4745 case 420: /* Bad extension */
4746 return AST_CAUSE_NO_ROUTE_DESTINATION;
4747 case 480: /* No answer */
4748 return AST_CAUSE_NO_ANSWER;
4749 case 481: /* No answer */
4750 return AST_CAUSE_INTERWORKING;
4751 case 482: /* Loop detected */
4752 return AST_CAUSE_INTERWORKING;
4753 case 483: /* Too many hops */
4754 return AST_CAUSE_NO_ANSWER;
4755 case 484: /* Address incomplete */
4756 return AST_CAUSE_INVALID_NUMBER_FORMAT;
4757 case 485: /* Ambiguous */
4758 return AST_CAUSE_UNALLOCATED;
4759 case 486: /* Busy everywhere */
4760 return AST_CAUSE_BUSY;
4761 case 487: /* Request terminated */
4762 return AST_CAUSE_INTERWORKING;
4763 case 488: /* No codecs approved */
4764 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
4765 case 491: /* Request pending */
4766 return AST_CAUSE_INTERWORKING;
4767 case 493: /* Undecipherable */
4768 return AST_CAUSE_INTERWORKING;
4769 case 500: /* Server internal failure */
4770 return AST_CAUSE_FAILURE;
4771 case 501: /* Call rejected */
4772 return AST_CAUSE_FACILITY_REJECTED;
4773 case 502:
4774 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
4775 case 503: /* Service unavailable */
4776 return AST_CAUSE_CONGESTION;
4777 case 504: /* Gateway timeout */
4778 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
4779 case 505: /* SIP version not supported */
4780 return AST_CAUSE_INTERWORKING;
4781 case 600: /* Busy everywhere */
4782 return AST_CAUSE_USER_BUSY;
4783 case 603: /* Decline */
4784 return AST_CAUSE_CALL_REJECTED;
4785 case 604: /* Does not exist anywhere */
4786 return AST_CAUSE_UNALLOCATED;
4787 case 606: /* Not acceptable */
4788 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
4789 default:
4790 return AST_CAUSE_NORMAL;
4792 /* Never reached */
4793 return 0;
4796 /*! \brief Convert Asterisk hangup causes to SIP codes
4797 \verbatim
4798 Possible values from causes.h
4799 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
4800 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
4802 In addition to these, a lot of PRI codes is defined in causes.h
4803 ...should we take care of them too ?
4805 Quote RFC 3398
4807 ISUP Cause value SIP response
4808 ---------------- ------------
4809 1 unallocated number 404 Not Found
4810 2 no route to network 404 Not found
4811 3 no route to destination 404 Not found
4812 16 normal call clearing --- (*)
4813 17 user busy 486 Busy here
4814 18 no user responding 408 Request Timeout
4815 19 no answer from the user 480 Temporarily unavailable
4816 20 subscriber absent 480 Temporarily unavailable
4817 21 call rejected 403 Forbidden (+)
4818 22 number changed (w/o diagnostic) 410 Gone
4819 22 number changed (w/ diagnostic) 301 Moved Permanently
4820 23 redirection to new destination 410 Gone
4821 26 non-selected user clearing 404 Not Found (=)
4822 27 destination out of order 502 Bad Gateway
4823 28 address incomplete 484 Address incomplete
4824 29 facility rejected 501 Not implemented
4825 31 normal unspecified 480 Temporarily unavailable
4826 \endverbatim
4828 static const char *hangup_cause2sip(int cause)
4830 switch (cause) {
4831 case AST_CAUSE_UNALLOCATED: /* 1 */
4832 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
4833 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
4834 return "404 Not Found";
4835 case AST_CAUSE_CONGESTION: /* 34 */
4836 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
4837 return "503 Service Unavailable";
4838 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
4839 return "408 Request Timeout";
4840 case AST_CAUSE_NO_ANSWER: /* 19 */
4841 return "480 Temporarily unavailable";
4842 case AST_CAUSE_CALL_REJECTED: /* 21 */
4843 return "403 Forbidden";
4844 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
4845 return "410 Gone";
4846 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
4847 return "480 Temporarily unavailable";
4848 case AST_CAUSE_INVALID_NUMBER_FORMAT:
4849 return "484 Address incomplete";
4850 case AST_CAUSE_USER_BUSY:
4851 return "486 Busy here";
4852 case AST_CAUSE_FAILURE:
4853 return "500 Server internal failure";
4854 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
4855 return "501 Not Implemented";
4856 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
4857 return "503 Service Unavailable";
4858 /* Used in chan_iax2 */
4859 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
4860 return "502 Bad Gateway";
4861 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
4862 return "488 Not Acceptable Here";
4864 case AST_CAUSE_NOTDEFINED:
4865 default:
4866 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
4867 return NULL;
4870 /* Never reached */
4871 return 0;
4875 /*! \brief sip_hangup: Hangup SIP call
4876 * Part of PBX interface, called from ast_hangup */
4877 static int sip_hangup(struct ast_channel *ast)
4879 struct sip_pvt *p = ast->tech_pvt;
4880 int needcancel = FALSE;
4881 int needdestroy = 0;
4882 struct ast_channel *oldowner = ast;
4884 if (!p) {
4885 ast_debug(1, "Asked to hangup channel that was not connected\n");
4886 return 0;
4888 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
4889 ast_debug(1, "This call was answered elsewhere");
4890 append_history(p, "Cancel", "Call answered elsewhere");
4891 p->answered_elsewhere = TRUE;
4894 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
4895 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4896 if (sipdebug)
4897 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
4898 update_call_counter(p, DEC_CALL_LIMIT);
4900 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
4901 if (p->autokillid > -1 && sip_cancel_destroy(p))
4902 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
4903 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4904 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
4905 p->needdestroy = 0;
4906 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
4907 sip_pvt_lock(p);
4908 p->owner = NULL; /* Owner will be gone after we return, so take it away */
4909 sip_pvt_unlock(p);
4910 return 0;
4913 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
4914 if (p->refer)
4915 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
4916 else
4917 ast_debug(1, "Hanging up zombie call. Be scared.\n");
4918 } else
4919 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
4921 sip_pvt_lock(p);
4922 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4923 if (sipdebug)
4924 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
4925 update_call_counter(p, DEC_CALL_LIMIT);
4928 /* Determine how to disconnect */
4929 if (p->owner != ast) {
4930 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
4931 sip_pvt_unlock(p);
4932 return 0;
4934 /* If the call is not UP, we need to send CANCEL instead of BYE */
4935 /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
4936 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
4937 needcancel = TRUE;
4938 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
4941 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
4943 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
4945 /* Disconnect */
4946 if (p->vad)
4947 ast_dsp_free(p->vad);
4949 p->owner = NULL;
4950 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
4952 ast_module_unref(ast_module_info->self);
4953 /* Do not destroy this pvt until we have timeout or
4954 get an answer to the BYE or INVITE/CANCEL
4955 If we get no answer during retransmit period, drop the call anyway.
4956 (Sorry, mother-in-law, you can't deny a hangup by sending
4957 603 declined to BYE...)
4959 if (p->alreadygone)
4960 needdestroy = 1; /* Set destroy flag at end of this function */
4961 else if (p->invitestate != INV_CALLING)
4962 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4964 /* Start the process if it's not already started */
4965 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
4966 if (needcancel) { /* Outgoing call, not up */
4967 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
4968 /* stop retransmitting an INVITE that has not received a response */
4969 __sip_pretend_ack(p);
4970 p->invitestate = INV_CANCELLED;
4972 /* if we can't send right now, mark it pending */
4973 if (p->invitestate == INV_CALLING) {
4974 /* We can't send anything in CALLING state */
4975 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
4976 /* Do we need a timer here if we don't hear from them at all? */
4977 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4978 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
4979 } else {
4980 /* Send a new request: CANCEL */
4981 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
4982 /* Actually don't destroy us yet, wait for the 487 on our original
4983 INVITE, but do set an autodestruct just in case we never get it. */
4984 needdestroy = 0;
4985 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4987 if ( p->initid != -1 ) {
4988 /* channel still up - reverse dec of inUse counter
4989 only if the channel is not auto-congested */
4990 update_call_counter(p, INC_CALL_LIMIT);
4992 } else { /* Incoming call, not up */
4993 const char *res;
4994 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
4995 transmit_response_reliable(p, res, &p->initreq);
4996 else
4997 transmit_response_reliable(p, "603 Declined", &p->initreq);
4998 p->invitestate = INV_TERMINATED;
5000 } else { /* Call is in UP state, send BYE */
5001 if (p->stimer->st_active == TRUE) {
5002 stop_session_timer(p);
5005 if (!p->pendinginvite) {
5006 struct ast_channel *bridge = ast_bridged_channel(oldowner);
5007 char *audioqos = "";
5008 char *videoqos = "";
5009 char *textqos = "";
5011 if (p->rtp)
5012 ast_rtp_set_vars(oldowner, p->rtp);
5014 if (bridge) {
5015 struct sip_pvt *q = bridge->tech_pvt;
5017 if (IS_SIP_TECH(bridge->tech) && q->rtp)
5018 ast_rtp_set_vars(bridge, q->rtp);
5021 if (p->vrtp)
5022 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
5023 if (p->trtp)
5024 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
5025 /* Send a hangup */
5026 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
5028 /* Get RTCP quality before end of call */
5029 if (p->do_history) {
5030 if (p->rtp)
5031 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
5032 if (p->vrtp)
5033 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
5034 if (p->trtp)
5035 append_history(p, "RTCPtext", "Quality:%s", textqos);
5037 if (p->rtp && oldowner)
5038 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
5039 if (p->vrtp && oldowner)
5040 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
5041 if (p->trtp && oldowner)
5042 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
5043 } else {
5044 /* Note we will need a BYE when this all settles out
5045 but we can't send one while we have "INVITE" outstanding. */
5046 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
5047 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
5048 AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
5049 if (sip_cancel_destroy(p))
5050 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
5054 if (needdestroy)
5055 p->needdestroy = 1;
5056 sip_pvt_unlock(p);
5057 return 0;
5060 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
5061 static void try_suggested_sip_codec(struct sip_pvt *p)
5063 int fmt;
5064 const char *codec;
5066 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
5067 if (!codec)
5068 return;
5070 fmt = ast_getformatbyname(codec);
5071 if (fmt) {
5072 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
5073 if (p->jointcapability & fmt) {
5074 p->jointcapability &= fmt;
5075 p->capability &= fmt;
5076 } else
5077 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
5078 } else
5079 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
5080 return;
5083 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
5084 * Part of PBX interface */
5085 static int sip_answer(struct ast_channel *ast)
5087 int res = 0;
5088 struct sip_pvt *p = ast->tech_pvt;
5090 sip_pvt_lock(p);
5091 if (ast->_state != AST_STATE_UP) {
5092 try_suggested_sip_codec(p);
5094 ast_setstate(ast, AST_STATE_UP);
5095 ast_debug(1, "SIP answering channel: %s\n", ast->name);
5096 if (p->t38.state == T38_PEER_DIRECT) {
5097 change_t38_state(p, T38_ENABLED);
5098 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
5099 } else {
5100 ast_rtp_new_source(p->rtp);
5101 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
5104 sip_pvt_unlock(p);
5105 return res;
5108 /*! \brief Send frame to media channel (rtp) */
5109 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
5111 struct sip_pvt *p = ast->tech_pvt;
5112 int res = 0;
5114 switch (frame->frametype) {
5115 case AST_FRAME_VOICE:
5116 if (!(frame->subclass & ast->nativeformats)) {
5117 char s1[512], s2[512], s3[512];
5118 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
5119 frame->subclass,
5120 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
5121 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
5122 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
5123 ast->readformat,
5124 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
5125 ast->writeformat);
5126 return 0;
5128 if (p) {
5129 sip_pvt_lock(p);
5130 if (p->rtp) {
5131 /* If channel is not up, activate early media session */
5132 if ((ast->_state != AST_STATE_UP) &&
5133 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5134 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5135 ast_rtp_new_source(p->rtp);
5136 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5137 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5139 p->lastrtptx = time(NULL);
5140 res = ast_rtp_write(p->rtp, frame);
5142 sip_pvt_unlock(p);
5144 break;
5145 case AST_FRAME_VIDEO:
5146 if (p) {
5147 sip_pvt_lock(p);
5148 if (p->vrtp) {
5149 /* Activate video early media */
5150 if ((ast->_state != AST_STATE_UP) &&
5151 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5152 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5153 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5154 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5156 p->lastrtptx = time(NULL);
5157 res = ast_rtp_write(p->vrtp, frame);
5159 sip_pvt_unlock(p);
5161 break;
5162 case AST_FRAME_TEXT:
5163 if (p) {
5164 sip_pvt_lock(p);
5165 if (p->red) {
5166 red_buffer_t140(p->trtp, frame);
5167 } else {
5168 if (p->trtp) {
5169 /* Activate text early media */
5170 if ((ast->_state != AST_STATE_UP) &&
5171 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5172 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5173 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5174 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5176 p->lastrtptx = time(NULL);
5177 res = ast_rtp_write(p->trtp, frame);
5180 sip_pvt_unlock(p);
5182 break;
5183 case AST_FRAME_IMAGE:
5184 return 0;
5185 break;
5186 case AST_FRAME_MODEM:
5187 if (p) {
5188 sip_pvt_lock(p);
5189 /* UDPTL requires two-way communication, so early media is not needed here.
5190 we simply forget the frames if we get modem frames before the bridge is up.
5191 Fax will re-transmit.
5193 if (p->udptl && ast->_state == AST_STATE_UP)
5194 res = ast_udptl_write(p->udptl, frame);
5195 sip_pvt_unlock(p);
5197 break;
5198 default:
5199 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
5200 return 0;
5203 return res;
5206 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
5207 Basically update any ->owner links */
5208 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
5210 int ret = -1;
5211 struct sip_pvt *p;
5213 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
5214 ast_debug(1, "New channel is zombie\n");
5215 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
5216 ast_debug(1, "Old channel is zombie\n");
5218 if (!newchan || !newchan->tech_pvt) {
5219 if (!newchan)
5220 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
5221 else
5222 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
5223 return -1;
5225 p = newchan->tech_pvt;
5227 sip_pvt_lock(p);
5228 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
5229 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
5230 if (p->owner != oldchan)
5231 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
5232 else {
5233 p->owner = newchan;
5234 /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
5235 RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
5236 able to do this if the masquerade happens before the bridge breaks (e.g., AMI
5237 redirect of both channels). Note that a channel can not be masqueraded *into*
5238 a native bridge. So there is no danger that this breaks a native bridge that
5239 should stay up. */
5240 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
5241 ret = 0;
5243 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
5245 sip_pvt_unlock(p);
5246 return ret;
5249 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
5251 struct sip_pvt *p = ast->tech_pvt;
5252 int res = 0;
5254 sip_pvt_lock(p);
5255 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
5256 case SIP_DTMF_INBAND:
5257 res = -1; /* Tell Asterisk to generate inband indications */
5258 break;
5259 case SIP_DTMF_RFC2833:
5260 if (p->rtp)
5261 ast_rtp_senddigit_begin(p->rtp, digit);
5262 break;
5263 default:
5264 break;
5266 sip_pvt_unlock(p);
5268 return res;
5271 /*! \brief Send DTMF character on SIP channel
5272 within one call, we're able to transmit in many methods simultaneously */
5273 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
5275 struct sip_pvt *p = ast->tech_pvt;
5276 int res = 0;
5278 sip_pvt_lock(p);
5279 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
5280 case SIP_DTMF_INFO:
5281 case SIP_DTMF_SHORTINFO:
5282 transmit_info_with_digit(p, digit, duration);
5283 break;
5284 case SIP_DTMF_RFC2833:
5285 if (p->rtp)
5286 ast_rtp_senddigit_end(p->rtp, digit);
5287 break;
5288 case SIP_DTMF_INBAND:
5289 res = -1; /* Tell Asterisk to stop inband indications */
5290 break;
5292 sip_pvt_unlock(p);
5294 return res;
5297 /*! \brief Transfer SIP call */
5298 static int sip_transfer(struct ast_channel *ast, const char *dest)
5300 struct sip_pvt *p = ast->tech_pvt;
5301 int res;
5303 if (dest == NULL) /* functions below do not take a NULL */
5304 dest = "";
5305 sip_pvt_lock(p);
5306 if (ast->_state == AST_STATE_RING)
5307 res = sip_sipredirect(p, dest);
5308 else
5309 res = transmit_refer(p, dest);
5310 sip_pvt_unlock(p);
5311 return res;
5314 /*! \brief Play indication to user
5315 * With SIP a lot of indications is sent as messages, letting the device play
5316 the indication - busy signal, congestion etc
5317 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
5319 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
5321 struct sip_pvt *p = ast->tech_pvt;
5322 int res = 0;
5324 sip_pvt_lock(p);
5325 switch(condition) {
5326 case AST_CONTROL_RINGING:
5327 if (ast->_state == AST_STATE_RING) {
5328 p->invitestate = INV_EARLY_MEDIA;
5329 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
5330 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
5331 /* Send 180 ringing if out-of-band seems reasonable */
5332 transmit_response(p, "180 Ringing", &p->initreq);
5333 ast_set_flag(&p->flags[0], SIP_RINGING);
5334 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
5335 break;
5336 } else {
5337 /* Well, if it's not reasonable, just send in-band */
5340 res = -1;
5341 break;
5342 case AST_CONTROL_BUSY:
5343 if (ast->_state != AST_STATE_UP) {
5344 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
5345 p->invitestate = INV_COMPLETED;
5346 sip_alreadygone(p);
5347 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
5348 break;
5350 res = -1;
5351 break;
5352 case AST_CONTROL_CONGESTION:
5353 if (ast->_state != AST_STATE_UP) {
5354 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
5355 p->invitestate = INV_COMPLETED;
5356 sip_alreadygone(p);
5357 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
5358 break;
5360 res = -1;
5361 break;
5362 case AST_CONTROL_PROCEEDING:
5363 if ((ast->_state != AST_STATE_UP) &&
5364 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5365 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5366 transmit_response(p, "100 Trying", &p->initreq);
5367 p->invitestate = INV_PROCEEDING;
5368 break;
5370 res = -1;
5371 break;
5372 case AST_CONTROL_PROGRESS:
5373 if ((ast->_state != AST_STATE_UP) &&
5374 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5375 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5376 p->invitestate = INV_EARLY_MEDIA;
5377 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5378 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5379 break;
5381 res = -1;
5382 break;
5383 case AST_CONTROL_HOLD:
5384 ast_rtp_new_source(p->rtp);
5385 ast_moh_start(ast, data, p->mohinterpret);
5386 break;
5387 case AST_CONTROL_UNHOLD:
5388 ast_rtp_new_source(p->rtp);
5389 ast_moh_stop(ast);
5390 break;
5391 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
5392 if (p->vrtp && !p->novideo) {
5393 transmit_info_with_vidupdate(p);
5394 /* ast_rtcp_send_h261fur(p->vrtp); */
5395 } else
5396 res = -1;
5397 break;
5398 case AST_CONTROL_T38: /* T38 control frame */
5399 if (datalen != sizeof(enum ast_control_t38)) {
5400 ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38. Expected %d, got %d\n", (int)sizeof(enum ast_control_t38), (int)datalen);
5401 } else {
5402 switch (*((enum ast_control_t38 *) data)) {
5403 case AST_T38_REQUEST_NEGOTIATE: /* Request T38 */
5404 if (p->t38.state != T38_ENABLED) {
5405 change_t38_state(p, T38_LOCAL_REINVITE);
5406 transmit_reinvite_with_sdp(p, TRUE, FALSE);
5408 break;
5409 case AST_T38_TERMINATED:
5410 case AST_T38_REFUSED:
5411 case AST_T38_REQUEST_TERMINATE: /* Shutdown T38 */
5412 if (p->t38.state == T38_ENABLED)
5413 transmit_reinvite_with_sdp(p, FALSE, FALSE);
5414 break;
5415 default:
5416 break;
5419 break;
5420 case AST_CONTROL_SRCUPDATE:
5421 ast_rtp_new_source(p->rtp);
5422 break;
5423 case -1:
5424 res = -1;
5425 break;
5426 default:
5427 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
5428 res = -1;
5429 break;
5431 sip_pvt_unlock(p);
5432 return res;
5436 /*! \brief Initiate a call in the SIP channel
5437 called from sip_request_call (calls from the pbx ) for outbound channels
5438 and from handle_request_invite for inbound channels
5441 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
5443 struct ast_channel *tmp;
5444 struct ast_variable *v = NULL;
5445 int fmt;
5446 int what;
5447 int video;
5448 int text;
5449 int needvideo = 0;
5450 int needtext = 0;
5451 char buf[SIPBUFSIZE];
5452 char *decoded_exten;
5455 const char *my_name; /* pick a good name */
5457 if (title)
5458 my_name = title;
5459 else if ( (my_name = strchr(i->fromdomain, ':')) )
5460 my_name++; /* skip ':' */
5461 else
5462 my_name = i->fromdomain;
5464 sip_pvt_unlock(i);
5465 /* Don't hold a sip pvt lock while we allocate a channel */
5466 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, (int)(long) i);
5469 if (!tmp) {
5470 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
5471 sip_pvt_lock(i);
5472 return NULL;
5474 sip_pvt_lock(i);
5476 tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ? &sip_tech_info : &sip_tech;
5478 /* Select our native format based on codec preference until we receive
5479 something from another device to the contrary. */
5480 if (i->jointcapability) { /* The joint capabilities of us and peer */
5481 what = i->jointcapability;
5482 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
5483 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
5484 } else if (i->capability) { /* Our configured capability for this peer */
5485 what = i->capability;
5486 video = i->capability & AST_FORMAT_VIDEO_MASK;
5487 text = i->capability & AST_FORMAT_TEXT_MASK;
5488 } else {
5489 what = global_capability; /* Global codec support */
5490 video = global_capability & AST_FORMAT_VIDEO_MASK;
5491 text = global_capability & AST_FORMAT_TEXT_MASK;
5494 /* Set the native formats for audio and merge in video */
5495 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
5496 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
5497 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
5498 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
5499 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
5500 if (i->prefcodec)
5501 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
5503 /* XXX Why are we choosing a codec from the native formats?? */
5504 fmt = ast_best_codec(tmp->nativeformats);
5506 /* If we have a prefcodec setting, we have an inbound channel that set a
5507 preferred format for this call. Otherwise, we check the jointcapability
5508 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
5510 if (i->vrtp) {
5511 if (i->prefcodec)
5512 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
5513 else
5514 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
5517 if (i->trtp) {
5518 if (i->prefcodec)
5519 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
5520 else
5521 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
5524 if (needvideo)
5525 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
5526 else
5527 ast_debug(3, "This channel will not be able to handle video.\n");
5531 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
5532 i->vad = ast_dsp_new();
5533 ast_dsp_set_features(i->vad, DSP_FEATURE_DIGIT_DETECT);
5534 if (global_relaxdtmf)
5535 ast_dsp_set_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
5538 /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
5539 if (i->rtp) {
5540 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
5541 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
5543 if (needvideo && i->vrtp) {
5544 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
5545 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
5547 if (needtext && i->trtp)
5548 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
5549 if (i->udptl)
5550 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
5552 if (state == AST_STATE_RING)
5553 tmp->rings = 1;
5554 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
5555 tmp->writeformat = fmt;
5556 tmp->rawwriteformat = fmt;
5557 tmp->readformat = fmt;
5558 tmp->rawreadformat = fmt;
5559 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
5561 tmp->callgroup = i->callgroup;
5562 tmp->pickupgroup = i->pickupgroup;
5563 tmp->cid.cid_pres = i->callingpres;
5564 if (!ast_strlen_zero(i->accountcode))
5565 ast_string_field_set(tmp, accountcode, i->accountcode);
5566 if (i->amaflags)
5567 tmp->amaflags = i->amaflags;
5568 if (!ast_strlen_zero(i->language))
5569 ast_string_field_set(tmp, language, i->language);
5570 i->owner = tmp;
5571 ast_module_ref(ast_module_info->self);
5572 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5573 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
5574 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
5575 * structure so that there aren't issues when forming URI's
5577 decoded_exten = ast_strdupa(i->exten);
5578 ast_uri_decode(decoded_exten);
5579 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
5581 /* Don't use ast_set_callerid() here because it will
5582 * generate an unnecessary NewCallerID event */
5583 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5584 if (!ast_strlen_zero(i->rdnis))
5585 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
5587 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
5588 tmp->cid.cid_dnid = ast_strdup(i->exten);
5590 tmp->priority = 1;
5591 if (!ast_strlen_zero(i->uri))
5592 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
5593 if (!ast_strlen_zero(i->domain))
5594 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
5595 if (!ast_strlen_zero(i->callid))
5596 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
5597 if (i->rtp)
5598 ast_jb_configure(tmp, &global_jbconf);
5600 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
5601 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
5602 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
5604 /* Set channel variables for this call from configuration */
5605 for (v = i->chanvars ; v ; v = v->next)
5606 pbx_builtin_setvar_helper(tmp, v->name, v->value);
5608 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
5609 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
5610 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
5611 ast_hangup(tmp);
5612 tmp = NULL;
5615 if (i->do_history)
5616 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
5618 /* Inform manager user about new channel and their SIP call ID */
5619 if (global_callevents)
5620 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
5621 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
5622 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
5624 return tmp;
5627 /*! \brief Reads one line of SIP message body */
5628 static char *get_body_by_line(const char *line, const char *name, int nameLen)
5630 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
5631 return ast_skip_blanks(line + nameLen + 1);
5633 return "";
5636 /*! \brief Lookup 'name' in the SDP starting
5637 * at the 'start' line. Returns the matching line, and 'start'
5638 * is updated with the next line number.
5640 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
5642 int len = strlen(name);
5644 while (*start < req->sdp_end) {
5645 const char *r = get_body_by_line(req->line[(*start)++], name, len);
5646 if (r[0] != '\0')
5647 return r;
5650 return "";
5653 /*! \brief Get a line from an SDP message body */
5654 static const char *get_sdp(struct sip_request *req, const char *name)
5656 int dummy = 0;
5658 return get_sdp_iterate(&dummy, req, name);
5661 /*! \brief Get a specific line from the message body */
5662 static char *get_body(struct sip_request *req, char *name)
5664 int x;
5665 int len = strlen(name);
5666 char *r;
5668 for (x = 0; x < req->lines; x++) {
5669 r = get_body_by_line(req->line[x], name, len);
5670 if (r[0] != '\0')
5671 return r;
5674 return "";
5677 /*! \brief Find compressed SIP alias */
5678 static const char *find_alias(const char *name, const char *_default)
5680 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
5681 static const struct cfalias {
5682 char * const fullname;
5683 char * const shortname;
5684 } aliases[] = {
5685 { "Content-Type", "c" },
5686 { "Content-Encoding", "e" },
5687 { "From", "f" },
5688 { "Call-ID", "i" },
5689 { "Contact", "m" },
5690 { "Content-Length", "l" },
5691 { "Subject", "s" },
5692 { "To", "t" },
5693 { "Supported", "k" },
5694 { "Refer-To", "r" },
5695 { "Referred-By", "b" },
5696 { "Allow-Events", "u" },
5697 { "Event", "o" },
5698 { "Via", "v" },
5699 { "Accept-Contact", "a" },
5700 { "Reject-Contact", "j" },
5701 { "Request-Disposition", "d" },
5702 { "Session-Expires", "x" },
5703 { "Identity", "y" },
5704 { "Identity-Info", "n" },
5706 int x;
5708 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
5709 if (!strcasecmp(aliases[x].fullname, name))
5710 return aliases[x].shortname;
5712 return _default;
5715 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
5717 int pass;
5720 * Technically you can place arbitrary whitespace both before and after the ':' in
5721 * a header, although RFC3261 clearly says you shouldn't before, and place just
5722 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
5723 * a good idea to say you can do it, and if you can do it, why in the hell would.
5724 * you say you shouldn't.
5725 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
5726 * and we always allow spaces after that for compatibility.
5728 for (pass = 0; name && pass < 2;pass++) {
5729 int x, len = strlen(name);
5730 for (x=*start; x<req->headers; x++) {
5731 if (!strncasecmp(req->header[x], name, len)) {
5732 char *r = req->header[x] + len; /* skip name */
5733 if (pedanticsipchecking)
5734 r = ast_skip_blanks(r);
5736 if (*r == ':') {
5737 *start = x+1;
5738 return ast_skip_blanks(r+1);
5742 if (pass == 0) /* Try aliases */
5743 name = find_alias(name, NULL);
5746 /* Don't return NULL, so get_header is always a valid pointer */
5747 return "";
5750 /*! \brief Get header from SIP request
5751 \return Always return something, so don't check for NULL because it won't happen :-)
5753 static const char *get_header(const struct sip_request *req, const char *name)
5755 int start = 0;
5756 return __get_header(req, name, &start);
5759 /*! \brief Read RTP from network */
5760 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
5762 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
5763 struct ast_frame *f;
5765 if (!p->rtp) {
5766 /* We have no RTP allocated for this channel */
5767 return &ast_null_frame;
5770 switch(ast->fdno) {
5771 case 0:
5772 f = ast_rtp_read(p->rtp); /* RTP Audio */
5773 break;
5774 case 1:
5775 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
5776 break;
5777 case 2:
5778 f = ast_rtp_read(p->vrtp); /* RTP Video */
5779 break;
5780 case 3:
5781 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
5782 break;
5783 case 4:
5784 f = ast_rtp_read(p->trtp); /* RTP Text */
5785 if (sipdebug_text) {
5786 int i;
5787 unsigned char* arr = f->data.ptr;
5788 for (i=0; i < f->datalen; i++)
5789 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
5790 ast_verbose(" -> ");
5791 for (i=0; i < f->datalen; i++)
5792 ast_verbose("%02X ", arr[i]);
5793 ast_verbose("\n");
5795 break;
5796 case 5:
5797 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
5798 break;
5799 default:
5800 f = &ast_null_frame;
5802 /* Don't forward RFC2833 if we're not supposed to */
5803 if (f && (f->frametype == AST_FRAME_DTMF) &&
5804 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
5805 return &ast_null_frame;
5807 /* We already hold the channel lock */
5808 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
5809 return f;
5811 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
5812 if (!(f->subclass & p->jointcapability)) {
5813 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
5814 ast_getformatname(f->subclass), p->owner->name);
5815 return &ast_null_frame;
5817 ast_debug(1, "Oooh, format changed to %d %s\n",
5818 f->subclass, ast_getformatname(f->subclass));
5819 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
5820 ast_set_read_format(p->owner, p->owner->readformat);
5821 ast_set_write_format(p->owner, p->owner->writeformat);
5824 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
5825 f = ast_dsp_process(p->owner, p->vad, f);
5826 if (f && f->frametype == AST_FRAME_DTMF) {
5827 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
5828 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
5829 *faxdetect = 1;
5830 } else {
5831 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
5836 return f;
5839 /*! \brief Read SIP RTP from channel */
5840 static struct ast_frame *sip_read(struct ast_channel *ast)
5842 struct ast_frame *fr;
5843 struct sip_pvt *p = ast->tech_pvt;
5844 int faxdetected = FALSE;
5846 sip_pvt_lock(p);
5847 fr = sip_rtp_read(ast, p, &faxdetected);
5848 p->lastrtprx = time(NULL);
5850 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
5851 /* If we are bridged then it is the responsibility of the SIP device to issue T38 re-invite if it detects CNG or fax preamble */
5852 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
5853 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
5854 if (!p->pendinginvite) {
5855 ast_debug(3, "Sending reinvite on SIP (%s) for T.38 negotiation.\n", ast->name);
5856 change_t38_state(p, T38_LOCAL_REINVITE);
5857 transmit_reinvite_with_sdp(p, TRUE, FALSE);
5859 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
5860 ast_debug(3, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
5861 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
5865 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
5866 if (fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
5867 fr = &ast_null_frame;
5870 sip_pvt_unlock(p);
5872 return fr;
5876 /*! \brief Generate 32 byte random string for callid's etc */
5877 static char *generate_random_string(char *buf, size_t size)
5879 long val[4];
5880 int x;
5882 for (x=0; x<4; x++)
5883 val[x] = ast_random();
5884 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
5886 return buf;
5889 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
5890 static void build_callid_pvt(struct sip_pvt *pvt)
5892 char buf[33];
5894 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
5896 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
5900 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
5901 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
5903 char buf[33];
5905 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
5907 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
5910 /*! \brief Make our SIP dialog tag */
5911 static void make_our_tag(char *tagbuf, size_t len)
5913 snprintf(tagbuf, len, "as%08lx", ast_random());
5916 /*! \brief Allocate Session-Timers struct w/in dialog */
5917 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
5919 struct sip_st_dlg *stp;
5921 if (p->stimer) {
5922 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
5923 return p->stimer;
5926 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
5927 return NULL;
5929 p->stimer = stp;
5931 stp->st_schedid = -1; /* Session-Timers ast_sched scheduler id */
5933 return p->stimer;
5936 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
5937 * Returns a reference to the object so whoever uses it later must
5938 * remember to release the reference.
5940 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
5941 int useglobal_nat, const int intended_method)
5943 struct sip_pvt *p;
5945 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
5946 return NULL;
5948 if (ast_string_field_init(p, 512)) {
5949 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
5950 ast_free(p);
5951 return NULL;
5954 p->socket.fd = -1;
5955 p->socket.type = SIP_TRANSPORT_UDP;
5956 p->method = intended_method;
5957 p->initid = -1;
5958 p->waitid = -1;
5959 p->autokillid = -1;
5960 p->subscribed = NONE;
5961 p->stateid = -1;
5962 p->sessionversion_remote = -1;
5963 p->session_modify = TRUE;
5964 p->stimer = NULL;
5965 p->prefs = default_prefs; /* Set default codecs for this call */
5967 if (intended_method != SIP_OPTIONS) { /* Peerpoke has it's own system */
5968 p->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
5969 p->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
5972 if (!sin)
5973 p->ourip = internip;
5974 else {
5975 p->sa = *sin;
5976 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
5979 /* Copy global flags to this PVT at setup. */
5980 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
5981 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
5983 p->do_history = recordhistory;
5985 p->branch = ast_random();
5986 make_our_tag(p->tag, sizeof(p->tag));
5987 p->ocseq = INITIAL_CSEQ;
5989 if (sip_methods[intended_method].need_rtp) {
5990 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
5991 /* If the global videosupport flag is on, we always create a RTP interface for video */
5992 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
5993 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
5994 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
5995 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
5996 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
5997 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
5998 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
5999 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
6000 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
6001 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
6002 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
6003 if (p->chanvars) {
6004 ast_variables_destroy(p->chanvars);
6005 p->chanvars = NULL;
6007 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
6008 return NULL;
6010 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
6011 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
6012 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
6013 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
6014 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
6015 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
6016 if (p->vrtp) {
6017 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
6018 ast_rtp_setdtmf(p->vrtp, 0);
6019 ast_rtp_setdtmfcompensate(p->vrtp, 0);
6020 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
6021 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
6022 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
6024 if (p->trtp) {
6025 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
6026 ast_rtp_setdtmf(p->trtp, 0);
6027 ast_rtp_setdtmfcompensate(p->trtp, 0);
6029 if (p->udptl)
6030 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
6031 p->maxcallbitrate = default_maxcallbitrate;
6032 p->autoframing = global_autoframing;
6033 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6036 if (useglobal_nat && sin) {
6037 /* Setup NAT structure according to global settings if we have an address */
6038 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6039 p->recv = *sin;
6040 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6043 if (p->method != SIP_REGISTER)
6044 ast_string_field_set(p, fromdomain, default_fromdomain);
6045 build_via(p);
6046 if (!callid)
6047 build_callid_pvt(p);
6048 else
6049 ast_string_field_set(p, callid, callid);
6050 /* Assign default music on hold class */
6051 ast_string_field_set(p, mohinterpret, default_mohinterpret);
6052 ast_string_field_set(p, mohsuggest, default_mohsuggest);
6053 p->capability = global_capability;
6054 p->allowtransfer = global_allowtransfer;
6055 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
6056 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
6057 p->noncodeccapability |= AST_RTP_DTMF;
6058 if (p->udptl) {
6059 ast_copy_flags(&p->t38.t38support, &p->flags[1], SIP_PAGE2_T38SUPPORT);
6060 set_t38_capabilities(p);
6061 p->t38.jointcapability = p->t38.capability;
6063 ast_string_field_set(p, context, default_context);
6064 ast_string_field_set(p, parkinglot, default_parkinglot);
6067 /* Add to active dialog list */
6069 ao2_t_link(dialogs, p, "link pvt into dialogs table");
6071 ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
6072 return p;
6075 /*! \brief argument to the helper function to identify a call */
6076 struct find_call_cb_arg {
6077 enum sipmethod method;
6078 const char *callid;
6079 const char *fromtag;
6080 const char *totag;
6081 const char *tag;
6085 * code to determine whether this is the pvt that we are looking for.
6086 * Return FALSE if not found, true otherwise. p is unlocked.
6088 static int find_call_cb(void *__p, void *__arg, int flags)
6090 struct sip_pvt *p = __p;
6091 struct find_call_cb_arg *arg = __arg;
6092 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
6093 int found = FALSE;
6095 if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
6096 if (arg->method == SIP_REGISTER)
6097 found = (!strcmp(p->callid, arg->callid));
6098 else
6099 found = (!strcmp(p->callid, arg->callid) &&
6100 (!pedanticsipchecking || ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, arg->tag))) ;
6103 ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
6105 /* If we get a new request within an existing to-tag - check the to tag as well */
6106 if (pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
6107 if (p->tag[0] == '\0' && arg->totag[0]) {
6108 /* We have no to tag, but they have. Wrong dialog */
6109 found = FALSE;
6110 } else if (arg->totag[0]) { /* Both have tags, compare them */
6111 if (strcmp(arg->totag, p->tag)) {
6112 found = FALSE; /* This is not our packet */
6115 if (!found)
6116 ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, arg->totag, sip_methods[arg->method].text);
6119 return found;
6122 /*! \brief find or create a dialog structure for an incoming SIP message.
6123 * Connect incoming SIP message to current dialog or create new dialog structure
6124 * Returns a reference to the sip_pvt object, remember to give it back once done.
6125 * Called by handle_incoming(), sipsock_read
6127 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
6129 struct sip_pvt *p = NULL;
6130 char *tag = ""; /* note, tag is never NULL */
6131 char totag[128];
6132 char fromtag[128];
6133 struct find_call_cb_arg arg;
6134 const char *callid = get_header(req, "Call-ID");
6135 const char *from = get_header(req, "From");
6136 const char *to = get_header(req, "To");
6137 const char *cseq = get_header(req, "Cseq");
6138 struct sip_pvt *sip_pvt_ptr;
6140 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
6141 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
6142 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
6143 ast_strlen_zero(from) || ast_strlen_zero(cseq))
6144 return NULL; /* Invalid packet */
6146 arg.method = req->method;
6147 arg.callid = callid;
6148 arg.fromtag = fromtag;
6149 arg.totag = totag;
6150 arg.tag = ""; /* make sure tag is never NULL */
6152 if (pedanticsipchecking) {
6153 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
6154 we need more to identify a branch - so we have to check branch, from
6155 and to tags to identify a call leg.
6156 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
6157 in sip.conf
6159 if (gettag(req, "To", totag, sizeof(totag)))
6160 req->has_to_tag = 1; /* Used in handle_request/response */
6161 gettag(req, "From", fromtag, sizeof(fromtag));
6163 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
6165 ast_debug(5, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
6167 /* All messages must always have From: tag */
6168 if (ast_strlen_zero(fromtag)) {
6169 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
6170 return NULL;
6172 /* reject requests that must always have a To: tag */
6173 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
6174 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
6175 return NULL;
6179 restartsearch:
6180 if (!pedanticsipchecking) {
6181 struct sip_pvt tmp_dialog = {
6182 .callid = callid,
6184 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
6185 if (sip_pvt_ptr) { /* well, if we don't find it-- what IS in there? */
6186 /* Found the call */
6187 sip_pvt_lock(sip_pvt_ptr);
6188 return sip_pvt_ptr;
6190 } else { /* in pedantic mode! -- do the fancy linear search */
6191 ao2_lock(dialogs);
6192 p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
6193 if (p) {
6194 if (sip_pvt_trylock(p)) {
6195 ao2_unlock(dialogs);
6196 usleep(1);
6197 goto restartsearch;
6199 ao2_unlock(dialogs);
6200 return p;
6202 ao2_unlock(dialogs);
6205 /* See if the method is capable of creating a dialog */
6206 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
6207 if (intended_method == SIP_REFER) {
6208 /* We do support REFER, but not outside of a dialog yet */
6209 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
6210 } else if (intended_method == SIP_NOTIFY) {
6211 /* We do not support out-of-dialog NOTIFY either,
6212 like voicemail notification, so cancel that early */
6213 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
6214 } else {
6215 /* Ok, time to create a new SIP dialog object, a pvt */
6216 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
6217 /* Ok, we've created a dialog, let's go and process it */
6218 sip_pvt_lock(p);
6219 } else {
6220 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
6221 getting a dialog from sip_alloc.
6223 Without a dialog we can't retransmit and handle ACKs and all that, but at least
6224 send an error message.
6226 Sorry, we apologize for the inconvienience
6228 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
6229 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
6232 return p; /* can be NULL */
6233 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
6234 /* A method we do not support, let's take it on the volley */
6235 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
6236 ast_debug(2, "Got a request with unsupported SIP method.\n");
6237 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
6238 /* This is a request outside of a dialog that we don't know about */
6239 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
6240 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
6242 /* We do not respond to responses for dialogs that we don't know about, we just drop
6243 the session quickly */
6244 if (intended_method == SIP_RESPONSE)
6245 ast_debug(2, "That's odd... Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
6247 return NULL;
6250 /*! \brief Parse register=> line in sip.conf and add to registry */
6251 static int sip_register(const char *value, int lineno)
6253 struct sip_registry *reg;
6254 int portnum = 0;
6255 enum sip_transport transport = SIP_TRANSPORT_UDP;
6256 char buf[256] = "";
6257 char *username = NULL;
6258 char *hostname=NULL, *secret=NULL, *authuser=NULL, *expiry=NULL;
6259 char *callback=NULL;
6261 if (!value)
6262 return -1;
6264 ast_copy_string(buf, value, sizeof(buf));
6266 sip_parse_host(buf, lineno, &username, &portnum, &transport);
6268 /* First split around the last '@' then parse the two components. */
6269 hostname = strrchr(username, '@'); /* allow @ in the first part */
6270 if (hostname)
6271 *hostname++ = '\0';
6272 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
6273 ast_log(LOG_WARNING, "Format for registration is [transport://]user[:secret[:authuser]]@host[:port][/contact][~expiry] at line %d\n", lineno);
6274 return -1;
6276 /* split user[:secret[:authuser]] */
6277 secret = strchr(username, ':');
6278 if (secret) {
6279 *secret++ = '\0';
6280 authuser = strchr(secret, ':');
6281 if (authuser)
6282 *authuser++ = '\0';
6284 /* split host[:port][/contact] */
6285 expiry = strchr(hostname, '~');
6286 if (expiry)
6287 *expiry++ = '\0';
6288 callback = strchr(hostname, '/');
6289 if (callback)
6290 *callback++ = '\0';
6291 if (ast_strlen_zero(callback))
6292 callback = "s";
6293 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
6294 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
6295 return -1;
6298 if (ast_string_field_init(reg, 256)) {
6299 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
6300 ast_free(reg);
6301 return -1;
6304 ast_atomic_fetchadd_int(&regobjs, 1);
6305 ASTOBJ_INIT(reg);
6306 ast_string_field_set(reg, callback, callback);
6307 if (!ast_strlen_zero(username))
6308 ast_string_field_set(reg, username, username);
6309 if (hostname)
6310 ast_string_field_set(reg, hostname, hostname);
6311 if (authuser)
6312 ast_string_field_set(reg, authuser, authuser);
6313 if (secret)
6314 ast_string_field_set(reg, secret, secret);
6315 reg->transport = transport;
6316 reg->expire = -1;
6317 reg->expiry = (expiry ? atoi(expiry) : default_expiry);
6318 reg->timeout = -1;
6319 reg->refresh = reg->expiry;
6320 reg->portno = portnum;
6321 reg->callid_valid = FALSE;
6322 reg->ocseq = INITIAL_CSEQ;
6323 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
6324 registry_unref(reg, "unref the reg pointer"); /* release the reference given by ASTOBJ_INIT. The container has another reference */
6325 return 0;
6328 /*! \brief Parse multiline SIP headers into one header
6329 This is enabled if pedanticsipchecking is enabled */
6330 static int lws2sws(char *msgbuf, int len)
6332 int h = 0, t = 0;
6333 int lws = 0;
6335 for (; h < len;) {
6336 /* Eliminate all CRs */
6337 if (msgbuf[h] == '\r') {
6338 h++;
6339 continue;
6341 /* Check for end-of-line */
6342 if (msgbuf[h] == '\n') {
6343 /* Check for end-of-message */
6344 if (h + 1 == len)
6345 break;
6346 /* Check for a continuation line */
6347 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
6348 /* Merge continuation line */
6349 h++;
6350 continue;
6352 /* Propagate LF and start new line */
6353 msgbuf[t++] = msgbuf[h++];
6354 lws = 0;
6355 continue;
6357 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
6358 if (lws) {
6359 h++;
6360 continue;
6362 msgbuf[t++] = msgbuf[h++];
6363 lws = 1;
6364 continue;
6366 msgbuf[t++] = msgbuf[h++];
6367 if (lws)
6368 lws = 0;
6370 msgbuf[t] = '\0';
6371 return t;
6374 /*! \brief Parse a SIP message
6375 \note this function is used both on incoming and outgoing packets
6377 static int parse_request(struct sip_request *req)
6379 char *c = req->data->str, **dst = req->header;
6380 int i = 0, lim = SIP_MAX_HEADERS - 1;
6382 req->header[0] = c;
6383 req->headers = -1; /* mark that we are working on the header */
6384 for (; *c; c++) {
6385 if (*c == '\r') /* remove \r */
6386 *c = '\0';
6387 else if (*c == '\n') { /* end of this line */
6388 *c = '\0';
6389 if (sipdebug)
6390 ast_debug(4, "%7s %2d [%3d]: %s\n",
6391 req->headers < 0 ? "Header" : "Body",
6392 i, (int)strlen(dst[i]), dst[i]);
6393 if (ast_strlen_zero(dst[i]) && req->headers < 0) {
6394 req->headers = i; /* record number of header lines */
6395 dst = req->line; /* start working on the body */
6396 i = 0;
6397 lim = SIP_MAX_LINES - 1;
6398 } else { /* move to next line, check for overflows */
6399 if (i++ >= lim)
6400 break;
6402 dst[i] = c + 1; /* record start of next line */
6405 /* Check for last header without CRLF. The RFC for SDP requires CRLF,
6406 but since some devices send without, we'll be generous in what we accept.
6408 if (!ast_strlen_zero(dst[i])) {
6409 if (sipdebug)
6410 ast_debug(4, "%7s %2d [%3d]: %s\n",
6411 req->headers < 0 ? "Header" : "Body",
6412 i, (int)strlen(dst[i]), dst[i]);
6413 i++;
6415 /* update count of header or body lines */
6416 if (req->headers >= 0) /* we are in the body */
6417 req->lines = i;
6418 else { /* no body */
6419 req->headers = i;
6420 req->lines = 0;
6421 req->line[0] = "";
6424 if (*c)
6425 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
6426 /* Split up the first line parts */
6427 return determine_firstline_parts(req);
6431 \brief Determine whether a SIP message contains an SDP in its body
6432 \param req the SIP request to process
6433 \return 1 if SDP found, 0 if not found
6435 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
6436 lives in the message body.
6438 static int find_sdp(struct sip_request *req)
6440 const char *content_type;
6441 const char *content_length;
6442 const char *search;
6443 char *boundary;
6444 unsigned int x;
6445 int boundaryisquoted = FALSE;
6446 int found_application_sdp = FALSE;
6447 int found_end_of_headers = FALSE;
6449 content_length = get_header(req, "Content-Length");
6451 if (!ast_strlen_zero(content_length)) {
6452 if (sscanf(content_length, "%ud", &x) != 1) {
6453 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
6454 return 0;
6457 /* Content-Length of zero means there can't possibly be an
6458 SDP here, even if the Content-Type says there is */
6459 if (x == 0)
6460 return 0;
6463 content_type = get_header(req, "Content-Type");
6465 /* if the body contains only SDP, this is easy */
6466 if (!strncasecmp(content_type, "application/sdp", 15)) {
6467 req->sdp_start = 0;
6468 req->sdp_end = req->lines;
6469 return req->lines ? 1 : 0;
6472 /* if it's not multipart/mixed, there cannot be an SDP */
6473 if (strncasecmp(content_type, "multipart/mixed", 15))
6474 return 0;
6476 /* if there is no boundary marker, it's invalid */
6477 if ((search = strcasestr(content_type, ";boundary=")))
6478 search += 10;
6479 else if ((search = strcasestr(content_type, "; boundary=")))
6480 search += 11;
6481 else
6482 return 0;
6484 if (ast_strlen_zero(search))
6485 return 0;
6487 /* If the boundary is quoted with ", remove quote */
6488 if (*search == '\"') {
6489 search++;
6490 boundaryisquoted = TRUE;
6493 /* make a duplicate of the string, with two extra characters
6494 at the beginning */
6495 boundary = ast_strdupa(search - 2);
6496 boundary[0] = boundary[1] = '-';
6497 /* Remove final quote */
6498 if (boundaryisquoted)
6499 boundary[strlen(boundary) - 1] = '\0';
6501 /* search for the boundary marker, the empty line delimiting headers from
6502 sdp part and the end boundry if it exists */
6504 for (x = 0; x < (req->lines ); x++) {
6505 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
6506 if(found_application_sdp && found_end_of_headers){
6507 req->sdp_end = x-1;
6508 return 1;
6510 found_application_sdp = FALSE;
6512 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
6513 found_application_sdp = TRUE;
6515 if(strlen(req->line[x]) == 0 ){
6516 if(found_application_sdp && !found_end_of_headers){
6517 req->sdp_start = x;
6518 found_end_of_headers = TRUE;
6522 if(found_application_sdp && found_end_of_headers) {
6523 req->sdp_end = x;
6524 return TRUE;
6526 return FALSE;
6529 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
6530 If offer is rejected, we will not change any properties of the call
6531 Return 0 on success, a negative value on errors.
6532 Must be called after find_sdp().
6534 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
6536 const char *m; /* SDP media offer */
6537 const char *c;
6538 const char *a;
6539 const char *o; /* Pointer to o= line */
6540 char *o_copy; /* Copy of o= line */
6541 char *token;
6542 char host[258];
6543 int len = -1;
6544 int portno = -1; /*!< RTP Audio port number */
6545 int vportno = -1; /*!< RTP Video port number */
6546 int tportno = -1; /*!< RTP Text port number */
6547 int udptlportno = -1;
6548 int peert38capability = 0;
6549 char s[256];
6550 int old = 0;
6552 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
6553 int peercapability = 0, peernoncodeccapability = 0;
6554 int vpeercapability = 0, vpeernoncodeccapability = 0;
6555 int tpeercapability = 0, tpeernoncodeccapability = 0;
6556 struct sockaddr_in sin; /*!< media socket address */
6557 struct sockaddr_in vsin; /*!< Video socket address */
6558 struct sockaddr_in tsin; /*!< Text socket address */
6560 const char *codecs;
6561 struct hostent *hp; /*!< RTP Audio host IP */
6562 struct hostent *vhp = NULL; /*!< RTP video host IP */
6563 struct hostent *thp = NULL; /*!< RTP text host IP */
6564 struct ast_hostent audiohp;
6565 struct ast_hostent videohp;
6566 struct ast_hostent texthp;
6567 int codec;
6568 int destiterator = 0;
6569 int iterator;
6570 int sendonly = -1;
6571 int numberofports;
6572 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp; /* Buffers for codec handling */
6573 int newjointcapability; /* Negotiated capability */
6574 int newpeercapability;
6575 int newnoncodeccapability;
6576 int numberofmediastreams = 0;
6577 int debug = sip_debug_test_pvt(p);
6579 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
6580 int last_rtpmap_codec=0;
6582 char buf[SIPBUFSIZE];
6583 int rua_version;
6585 int red_data_pt[10];
6586 int red_num_gen = 0;
6587 int red_pt = 0;
6589 char *red_cp; /* For T.140 red */
6590 char red_fmtp[100] = "empty"; /* For T.140 red */
6592 if (!p->rtp) {
6593 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
6594 return -1;
6597 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
6598 #ifdef LOW_MEMORY
6599 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
6600 #else
6601 newaudiortp = alloca(ast_rtp_alloc_size());
6602 #endif
6603 memset(newaudiortp, 0, ast_rtp_alloc_size());
6604 ast_rtp_new_init(newaudiortp);
6605 ast_rtp_pt_clear(newaudiortp);
6607 #ifdef LOW_MEMORY
6608 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
6609 #else
6610 newvideortp = alloca(ast_rtp_alloc_size());
6611 #endif
6612 memset(newvideortp, 0, ast_rtp_alloc_size());
6613 ast_rtp_new_init(newvideortp);
6614 ast_rtp_pt_clear(newvideortp);
6616 #ifdef LOW_MEMORY
6617 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
6618 #else
6619 newtextrtp = alloca(ast_rtp_alloc_size());
6620 #endif
6621 memset(newtextrtp, 0, ast_rtp_alloc_size());
6622 ast_rtp_new_init(newtextrtp);
6623 ast_rtp_pt_clear(newtextrtp);
6625 /* Update our last rtprx when we receive an SDP, too */
6626 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6628 /* Store the SDP version number of remote UA. This will allow us to
6629 distinguish between session modifications and session refreshes. If
6630 the remote UA does not send an incremented SDP version number in a
6631 subsequent RE-INVITE then that means its not changing media session.
6632 The RE-INVITE may have been sent to update connected party, remote
6633 target or to refresh the session (Session-Timers). Asterisk must not
6634 change media session and increment its own version number in answer
6635 SDP in this case. */
6637 o = get_sdp(req, "o");
6638 if (ast_strlen_zero(o)) {
6639 ast_log(LOG_WARNING, "SDP sytax error. SDP without an o= line\n");
6640 return -1;
6643 o_copy = ast_strdupa(o);
6644 token = strsep(&o_copy, " "); /* Skip username */
6645 if (!o_copy) {
6646 ast_log(LOG_WARNING, "SDP sytax error in o= line username\n");
6647 return -1;
6649 token = strsep(&o_copy, " "); /* Skip session-id */
6650 if (!o_copy) {
6651 ast_log(LOG_WARNING, "SDP sytax error in o= line session-id\n");
6652 return -1;
6654 token = strsep(&o_copy, " "); /* Version */
6655 if (!o_copy) {
6656 ast_log(LOG_WARNING, "SDP sytax error in o= line\n");
6657 return -1;
6659 if (!sscanf(token, "%d", &rua_version)) {
6660 ast_log(LOG_WARNING, "SDP sytax error in o= line version\n");
6661 return -1;
6664 if (p->sessionversion_remote < 0 || p->sessionversion_remote != rua_version) {
6665 p->sessionversion_remote = rua_version;
6666 p->session_modify = TRUE;
6667 } else if (p->sessionversion_remote == rua_version) {
6668 p->session_modify = FALSE;
6669 ast_debug(2, "SDP version number same as previous SDP\n");
6670 return 0;
6673 /* Try to find first media stream */
6674 m = get_sdp(req, "m");
6675 destiterator = req->sdp_start;
6676 c = get_sdp_iterate(&destiterator, req, "c");
6677 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
6678 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
6679 return -1;
6682 /* Check for IPv4 address (not IPv6 yet) */
6683 if (sscanf(c, "IN IP4 %256s", host) != 1) {
6684 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
6685 return -1;
6688 /* XXX This could block for a long time, and block the main thread! XXX */
6689 hp = ast_gethostbyname(host, &audiohp);
6690 if (!hp) {
6691 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
6692 return -1;
6694 vhp = hp; /* Copy to video address as default too */
6695 thp = hp; /* Copy to text address as default too */
6697 iterator = req->sdp_start;
6698 /* default: novideo and notext set */
6699 p->novideo = TRUE;
6700 p->notext = TRUE;
6702 if (p->vrtp)
6703 ast_rtp_pt_clear(newvideortp); /* Must be cleared in case no m=video line exists */
6705 if (p->trtp)
6706 ast_rtp_pt_clear(newtextrtp); /* Must be cleared in case no m=text line exists */
6708 /* Find media streams in this SDP offer */
6709 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
6710 int x;
6711 int audio = FALSE;
6712 int video = FALSE;
6713 int text = FALSE;
6715 numberofports = 1;
6716 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
6717 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
6718 audio = TRUE;
6719 numberofmediastreams++;
6720 /* Found audio stream in this media definition */
6721 portno = x;
6722 /* Scan through the RTP payload types specified in a "m=" line: */
6723 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
6724 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
6725 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
6726 return -1;
6728 if (debug)
6729 ast_verbose("Found RTP audio format %d\n", codec);
6730 ast_rtp_set_m_type(newaudiortp, codec);
6732 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
6733 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
6734 video = TRUE;
6735 p->novideo = FALSE;
6736 numberofmediastreams++;
6737 vportno = x;
6738 /* Scan through the RTP payload types specified in a "m=" line: */
6739 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
6740 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
6741 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
6742 return -1;
6744 if (debug)
6745 ast_verbose("Found RTP video format %d\n", codec);
6746 ast_rtp_set_m_type(newvideortp, codec);
6748 } else if ((sscanf(m, "text %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
6749 (sscanf(m, "text %d RTP/AVP %n", &x, &len) == 1)) {
6750 text = TRUE;
6751 p->notext = FALSE;
6752 numberofmediastreams++;
6753 tportno = x;
6754 /* Scan through the RTP payload types specified in a "m=" line: */
6755 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
6756 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
6757 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
6758 return -1;
6760 if (debug)
6761 ast_verbose("Found RTP text format %d\n", codec);
6762 ast_rtp_set_m_type(newtextrtp, codec);
6764 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
6765 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
6766 if (debug)
6767 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
6768 udptlportno = x;
6769 numberofmediastreams++;
6770 } else
6771 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
6772 if (numberofports > 1)
6773 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
6776 /* Check for Media-description-level-address for audio */
6777 c = get_sdp_iterate(&destiterator, req, "c");
6778 if (!ast_strlen_zero(c)) {
6779 if (sscanf(c, "IN IP4 %256s", host) != 1) {
6780 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
6781 } else {
6782 /* XXX This could block for a long time, and block the main thread! XXX */
6783 if (audio) {
6784 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
6785 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
6786 return -2;
6788 } else if (video) {
6789 if (!(vhp = ast_gethostbyname(host, &videohp))) {
6790 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
6791 return -2;
6793 } else if (text) {
6794 if (!(thp = ast_gethostbyname(host, &texthp))) {
6795 ast_log(LOG_WARNING, "Unable to lookup RTP text host in secondary c= line, '%s'\n", c);
6796 return -2;
6803 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
6804 /* No acceptable offer found in SDP - we have no ports */
6805 /* Do not change RTP or VRTP if this is a re-invite */
6806 return -2;
6808 if (numberofmediastreams > 3)
6809 /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
6810 return -3;
6812 /* RTP addresses and ports for audio and video */
6813 sin.sin_family = AF_INET;
6814 vsin.sin_family = AF_INET;
6815 tsin.sin_family = AF_INET;
6816 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
6817 if (vhp)
6818 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
6819 if (thp)
6820 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
6822 /* Setup UDPTL port number */
6823 if (p->udptl) {
6824 if (udptlportno > 0) {
6825 sin.sin_port = htons(udptlportno);
6826 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
6827 struct sockaddr_in peer;
6828 ast_rtp_get_peer(p->rtp, &peer);
6829 if (peer.sin_addr.s_addr) {
6830 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
6831 if (debug) {
6832 ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(sin.sin_addr));
6836 ast_udptl_set_peer(p->udptl, &sin);
6837 if (debug)
6838 ast_debug(1, "Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6839 } else {
6840 ast_udptl_stop(p->udptl);
6841 if (debug)
6842 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
6847 if (p->rtp) {
6848 if (portno > 0) {
6849 sin.sin_port = htons(portno);
6850 ast_rtp_set_peer(p->rtp, &sin);
6851 if (debug)
6852 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6853 } else {
6854 if (udptlportno > 0) {
6855 if (debug)
6856 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
6857 } else {
6858 ast_rtp_stop(p->rtp);
6859 if (debug)
6860 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
6864 /* Setup video port number, assumes we have audio */
6865 if (vportno != -1)
6866 vsin.sin_port = htons(vportno);
6868 /* Setup text port number, assumes we have audio */
6869 if (tportno != -1)
6870 tsin.sin_port = htons(tportno);
6872 /* Next, scan through each "a=xxxx:" line, noting each
6873 * specified RTP payload type (with corresponding MIME subtype):
6875 /* XXX This needs to be done per media stream, since it's media stream specific */
6876 iterator = req->sdp_start;
6877 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
6878 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
6879 if (option_debug > 1) {
6880 int breakout = FALSE;
6882 /* If we're debugging, check for unsupported sdp options */
6883 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
6884 if (debug)
6885 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
6886 breakout = TRUE;
6887 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
6888 /* Format parameters: Not supported */
6889 /* Note: This is used for codec parameters, like bitrate for
6890 G722 and video formats for H263 and H264
6891 See RFC2327 for an example */
6892 if (debug)
6893 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
6894 breakout = TRUE;
6895 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
6896 /* Video stuff: Not supported */
6897 if (debug)
6898 ast_verbose("Got unsupported a:framerate in SDP offer \n");
6899 breakout = TRUE;
6900 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
6901 /* Video stuff: Not supported */
6902 if (debug)
6903 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
6904 breakout = TRUE;
6905 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
6906 /* SRTP stuff, not yet supported */
6907 if (debug)
6908 ast_verbose("Got unsupported a:crypto in SDP offer \n");
6909 breakout = TRUE;
6911 if (breakout) /* We have a match, skip to next header */
6912 continue;
6914 if (!strcasecmp(a, "sendonly")) {
6915 if (sendonly == -1)
6916 sendonly = 1;
6917 continue;
6918 } else if (!strcasecmp(a, "inactive")) {
6919 if (sendonly == -1)
6920 sendonly = 2;
6921 continue;
6922 } else if (!strcasecmp(a, "sendrecv")) {
6923 if (sendonly == -1)
6924 sendonly = 0;
6925 continue;
6926 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
6927 char *tmp = strrchr(a, ':');
6928 long int framing = 0;
6929 if (tmp) {
6930 tmp++;
6931 framing = strtol(tmp, NULL, 10);
6932 if (framing == LONG_MIN || framing == LONG_MAX) {
6933 framing = 0;
6934 ast_debug(1, "Can't read framing from SDP: %s\n", a);
6937 if (framing && p->autoframing) {
6938 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
6939 int codec_n;
6940 int format = 0;
6941 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
6942 format = ast_rtp_codec_getformat(codec_n);
6943 if (!format) /* non-codec or not found */
6944 continue;
6945 if (option_debug)
6946 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
6947 ast_codec_pref_setsize(pref, format, framing);
6949 ast_rtp_codec_setpref(p->rtp, pref);
6951 continue;
6953 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
6954 /* count numbers of generations in fmtp */
6955 red_cp = &red_fmtp[strlen(red_fmtp)];
6956 strncpy(red_fmtp, a, 100);
6958 sscanf(red_cp, "%u", &red_data_pt[red_num_gen]);
6959 red_cp = strtok(red_cp, "/");
6960 while (red_cp && red_num_gen++ < RED_MAX_GENERATION) {
6961 sscanf(red_cp, "%u", &red_data_pt[red_num_gen]);
6962 red_cp = strtok(NULL, "/");
6964 red_cp = red_fmtp;
6966 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
6967 /* We have a rtpmap to handle */
6969 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
6970 /* Note: should really look at the 'freq' and '#chans' params too */
6971 /* Note: This should all be done in the context of the m= above */
6972 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) { /* Video */
6973 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
6974 if (debug)
6975 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
6976 found_rtpmap_codecs[last_rtpmap_codec] = codec;
6977 last_rtpmap_codec++;
6978 } else {
6979 ast_rtp_unset_m_type(newvideortp, codec);
6980 if (debug)
6981 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
6983 } else if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
6984 if (p->trtp) {
6985 /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
6986 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
6988 } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
6989 if (p->trtp) {
6990 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
6991 red_pt = codec;
6992 sprintf(red_fmtp, "fmtp:%d ", red_pt);
6994 if (debug)
6995 ast_verbose("Red submimetype has payload type: %d\n", red_pt);
6997 } else { /* Must be audio?? */
6998 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
6999 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
7000 if (debug)
7001 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
7002 found_rtpmap_codecs[last_rtpmap_codec] = codec;
7003 last_rtpmap_codec++;
7004 } else {
7005 ast_rtp_unset_m_type(newaudiortp, codec);
7006 if (debug)
7007 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
7010 } else {
7011 if (debug)
7012 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
7018 if (udptlportno != -1) {
7019 int found = 0, x;
7021 old = 0;
7023 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
7024 iterator = req->sdp_start;
7025 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
7026 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
7027 found = 1;
7028 ast_debug(3, "MaxBufferSize:%d\n", x);
7029 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
7030 found = 1;
7031 ast_debug(3, "T38MaxBitRate: %d\n", x);
7032 switch (x) {
7033 case 14400:
7034 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7035 break;
7036 case 12000:
7037 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7038 break;
7039 case 9600:
7040 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7041 break;
7042 case 7200:
7043 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7044 break;
7045 case 4800:
7046 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
7047 break;
7048 case 2400:
7049 peert38capability |= T38FAX_RATE_2400;
7050 break;
7052 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
7053 found = 1;
7054 ast_debug(3, "FaxVersion: %d\n", x);
7055 if (x == 0)
7056 peert38capability |= T38FAX_VERSION_0;
7057 else if (x == 1)
7058 peert38capability |= T38FAX_VERSION_1;
7059 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
7060 found = 1;
7061 ast_debug(3, "FaxMaxDatagram: %d\n", x);
7062 ast_udptl_set_far_max_datagram(p->udptl, x);
7063 ast_udptl_set_local_max_datagram(p->udptl, x);
7064 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
7065 found = 1;
7066 ast_debug(3, "FillBitRemoval: %d\n", x);
7067 if (x == 1)
7068 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
7069 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
7070 found = 1;
7071 ast_debug(3, "Transcoding MMR: %d\n", x);
7072 if (x == 1)
7073 peert38capability |= T38FAX_TRANSCODING_MMR;
7075 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
7076 found = 1;
7077 ast_debug(3, "Transcoding JBIG: %d\n", x);
7078 if (x == 1)
7079 peert38capability |= T38FAX_TRANSCODING_JBIG;
7080 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
7081 found = 1;
7082 ast_debug(3, "RateManagement: %s\n", s);
7083 if (!strcasecmp(s, "localTCF"))
7084 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
7085 else if (!strcasecmp(s, "transferredTCF"))
7086 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
7087 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
7088 found = 1;
7089 ast_debug(3, "UDP EC: %s\n", s);
7090 if (!strcasecmp(s, "t38UDPRedundancy")) {
7091 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
7092 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
7093 } else if (!strcasecmp(s, "t38UDPFEC")) {
7094 peert38capability |= T38FAX_UDP_EC_FEC;
7095 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
7096 } else {
7097 peert38capability |= T38FAX_UDP_EC_NONE;
7098 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
7102 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
7103 p->t38.peercapability = peert38capability;
7104 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
7105 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
7106 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
7108 if (debug)
7109 ast_debug(1, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
7110 p->t38.capability,
7111 p->t38.peercapability,
7112 p->t38.jointcapability);
7114 /* Remote party offers T38, we need to update state */
7115 if (t38action == SDP_T38_ACCEPT) {
7116 if (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)
7117 change_t38_state(p, T38_ENABLED);
7118 } else if (t38action == SDP_T38_INITIATE) {
7119 if (p->owner && p->lastinvite) {
7120 change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
7121 } else {
7122 change_t38_state(p, T38_PEER_DIRECT); /* T38 Offered directly from peer in first invite */
7125 } else {
7126 change_t38_state(p, T38_DISABLED);
7129 /* Now gather all of the codecs that we are asked for: */
7130 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
7131 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
7132 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
7134 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
7135 newpeercapability = (peercapability | vpeercapability | tpeercapability);
7136 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
7139 if (debug) {
7140 /* shame on whoever coded this.... */
7141 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
7143 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
7144 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
7145 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
7146 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
7147 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
7148 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
7150 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
7151 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
7152 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
7153 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
7155 if (!newjointcapability) {
7156 /* If T.38 was not negotiated either, totally bail out... */
7157 if (!p->t38.jointcapability || !udptlportno) {
7158 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
7159 /* Do NOT Change current setting */
7160 return -1;
7161 } else {
7162 ast_debug(3, "Have T.38 but no audio codecs, accepting offer anyway\n");
7163 return 0;
7167 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
7168 they are acceptable */
7169 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
7170 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
7171 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
7173 if (p->jointcapability & AST_FORMAT_T140RED) {
7174 p->red = 1;
7175 rtp_red_init(p->trtp, 300, red_data_pt, 2);
7176 } else {
7177 p->red = 0;
7180 ast_rtp_pt_copy(p->rtp, newaudiortp);
7181 if (p->vrtp)
7182 ast_rtp_pt_copy(p->vrtp, newvideortp);
7183 if (p->trtp)
7184 ast_rtp_pt_copy(p->trtp, newtextrtp);
7186 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
7187 ast_clear_flag(&p->flags[0], SIP_DTMF);
7188 if (newnoncodeccapability & AST_RTP_DTMF) {
7189 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
7190 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
7191 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
7192 ast_rtp_setdtmf(p->rtp, 1);
7193 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
7194 } else {
7195 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
7199 /* Setup audio port number */
7200 if (p->rtp && sin.sin_port) {
7201 ast_rtp_set_peer(p->rtp, &sin);
7202 if (debug)
7203 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
7206 /* Setup video port number */
7207 if (p->vrtp && vsin.sin_port) {
7208 ast_rtp_set_peer(p->vrtp, &vsin);
7209 if (debug)
7210 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
7213 /* Setup text port number */
7214 if (p->trtp && tsin.sin_port) {
7215 ast_rtp_set_peer(p->trtp, &tsin);
7216 if (debug)
7217 ast_verbose("Peer text RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
7220 /* Ok, we're going with this offer */
7221 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
7223 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
7224 return 0;
7226 ast_debug(4, "We have an owner, now see if we need to change this call\n");
7228 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
7229 if (debug) {
7230 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
7231 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
7232 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
7233 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
7235 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
7236 ast_set_read_format(p->owner, p->owner->readformat);
7237 ast_set_write_format(p->owner, p->owner->writeformat);
7240 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
7241 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
7242 /* Activate a re-invite */
7243 ast_queue_frame(p->owner, &ast_null_frame);
7244 /* Queue Manager Unhold event */
7245 append_history(p, "Unhold", "%s", req->data->str);
7246 if (global_callevents)
7247 manager_event(EVENT_FLAG_CALL, "Hold",
7248 "Status: Off\r\n"
7249 "Channel: %s\r\n"
7250 "Uniqueid: %s\r\n",
7251 p->owner->name,
7252 p->owner->uniqueid);
7253 if (global_notifyhold)
7254 sip_peer_hold(p, FALSE);
7255 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
7256 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
7257 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
7258 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
7259 S_OR(p->mohsuggest, NULL),
7260 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
7261 if (sendonly)
7262 ast_rtp_stop(p->rtp);
7263 /* RTCP needs to go ahead, even if we're on hold!!! */
7264 /* Activate a re-invite */
7265 ast_queue_frame(p->owner, &ast_null_frame);
7266 /* Queue Manager Hold event */
7267 append_history(p, "Hold", "%s", req->data->str);
7268 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
7269 manager_event(EVENT_FLAG_CALL, "Hold",
7270 "Status: On\r\n"
7271 "Channel: %s\r\n"
7272 "Uniqueid: %s\r\n",
7273 p->owner->name,
7274 p->owner->uniqueid);
7276 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
7277 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
7278 else if (sendonly == 2) /* Inactive stream */
7279 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
7280 else
7281 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
7282 if (global_notifyhold && !already_on_hold)
7283 sip_peer_hold(p, TRUE);
7286 return 0;
7289 #ifdef LOW_MEMORY
7290 static void ts_ast_rtp_destroy(void *data)
7292 struct ast_rtp *tmp = data;
7293 ast_rtp_destroy(tmp);
7295 #endif
7297 /*! \brief Add header to SIP message */
7298 static int add_header(struct sip_request *req, const char *var, const char *value)
7300 if (req->headers == SIP_MAX_HEADERS) {
7301 ast_log(LOG_WARNING, "Out of SIP header space\n");
7302 return -1;
7305 if (req->lines) {
7306 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
7307 return -1;
7310 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
7311 req->header[req->headers] = req->data->str + req->len;
7313 if (compactheaders)
7314 var = find_alias(var, var);
7315 req->len += strlen(req->header[req->headers]);
7316 req->headers++;
7318 return 0;
7321 /*! \brief Add 'Content-Length' header to SIP message */
7322 static int add_header_contentLength(struct sip_request *req, int len)
7324 char clen[10];
7326 snprintf(clen, sizeof(clen), "%d", len);
7327 return add_header(req, "Content-Length", clen);
7330 /*! \brief Add content (not header) to SIP message */
7331 static int add_line(struct sip_request *req, const char *line)
7333 if (req->lines == SIP_MAX_LINES) {
7334 ast_log(LOG_WARNING, "Out of SIP line space\n");
7335 return -1;
7337 if (!req->lines)
7338 /* Add extra empty return */
7339 req->len += ast_str_append(&req->data, 0, "\r\n");
7340 if (req->len >= sizeof(req->data->str) - 4) {
7341 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
7342 return -1;
7344 req->line[req->lines] = req->data->str + req->len;
7345 ast_str_append(&req->data, 0, "%s", line);
7346 req->len += strlen(req->line[req->lines]);
7347 req->lines++;
7348 return 0;
7351 /*! \brief Copy one header field from one request to another */
7352 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
7354 const char *tmp = get_header(orig, field);
7356 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
7357 return add_header(req, field, tmp);
7358 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
7359 return -1;
7362 /*! \brief Copy all headers from one request to another */
7363 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
7365 int start = 0;
7366 int copied = 0;
7367 for (;;) {
7368 const char *tmp = __get_header(orig, field, &start);
7370 if (ast_strlen_zero(tmp))
7371 break;
7372 /* Add what we're responding to */
7373 add_header(req, field, tmp);
7374 copied++;
7376 return copied ? 0 : -1;
7379 /*! \brief Copy SIP VIA Headers from the request to the response
7380 \note If the client indicates that it wishes to know the port we received from,
7381 it adds ;rport without an argument to the topmost via header. We need to
7382 add the port number (from our point of view) to that parameter.
7383 \verbatim
7384 We always add ;received=<ip address> to the topmost via header.
7385 \endverbatim
7386 Received: RFC 3261, rport RFC 3581 */
7387 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
7389 int copied = 0;
7390 int start = 0;
7392 for (;;) {
7393 char new[512];
7394 const char *oh = __get_header(orig, field, &start);
7396 if (ast_strlen_zero(oh))
7397 break;
7399 if (!copied) { /* Only check for empty rport in topmost via header */
7400 char leftmost[512], *others, *rport;
7402 /* Only work on leftmost value */
7403 ast_copy_string(leftmost, oh, sizeof(leftmost));
7404 others = strchr(leftmost, ',');
7405 if (others)
7406 *others++ = '\0';
7408 /* Find ;rport; (empty request) */
7409 rport = strstr(leftmost, ";rport");
7410 if (rport && *(rport+6) == '=')
7411 rport = NULL; /* We already have a parameter to rport */
7413 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
7414 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
7415 /* We need to add received port - rport */
7416 char *end;
7418 rport = strstr(leftmost, ";rport");
7420 if (rport) {
7421 end = strchr(rport + 1, ';');
7422 if (end)
7423 memmove(rport, end, strlen(end) + 1);
7424 else
7425 *rport = '\0';
7428 /* Add rport to first VIA header if requested */
7429 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
7430 leftmost, ast_inet_ntoa(p->recv.sin_addr),
7431 ntohs(p->recv.sin_port),
7432 others ? "," : "", others ? others : "");
7433 } else {
7434 /* We should *always* add a received to the topmost via */
7435 snprintf(new, sizeof(new), "%s;received=%s%s%s",
7436 leftmost, ast_inet_ntoa(p->recv.sin_addr),
7437 others ? "," : "", others ? others : "");
7439 oh = new; /* the header to copy */
7440 } /* else add the following via headers untouched */
7441 add_header(req, field, oh);
7442 copied++;
7444 if (!copied) {
7445 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
7446 return -1;
7448 return 0;
7451 /*! \brief Add route header into request per learned route */
7452 static void add_route(struct sip_request *req, struct sip_route *route)
7454 char r[SIPBUFSIZE*2], *p;
7455 int n, rem = sizeof(r);
7457 if (!route)
7458 return;
7460 p = r;
7461 for (;route ; route = route->next) {
7462 n = strlen(route->hop);
7463 if (rem < n+3) /* we need room for ",<route>" */
7464 break;
7465 if (p != r) { /* add a separator after fist route */
7466 *p++ = ',';
7467 --rem;
7469 *p++ = '<';
7470 ast_copy_string(p, route->hop, rem); /* cannot fail */
7471 p += n;
7472 *p++ = '>';
7473 rem -= (n+2);
7475 *p = '\0';
7476 add_header(req, "Route", r);
7479 /*! \brief Set destination from SIP URI */
7480 static void set_destination(struct sip_pvt *p, char *uri)
7482 char *h, *maddr, hostname[256];
7483 int port, hn;
7484 struct hostent *hp;
7485 struct ast_hostent ahp;
7486 int debug=sip_debug_test_pvt(p);
7488 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
7489 /* general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] */
7491 if (debug)
7492 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
7494 /* Find and parse hostname */
7495 h = strchr(uri, '@');
7496 if (h)
7497 ++h;
7498 else {
7499 h = uri;
7500 if (strncasecmp(h, "sip:", 4) == 0)
7501 h += 4;
7502 else if (strncasecmp(h, "sips:", 5) == 0)
7503 h += 5;
7505 hn = strcspn(h, ":;>") + 1;
7506 if (hn > sizeof(hostname))
7507 hn = sizeof(hostname);
7508 ast_copy_string(hostname, h, hn);
7509 /* XXX bug here if string has been trimmed to sizeof(hostname) */
7510 h += hn - 1;
7512 /* Is "port" present? if not default to STANDARD_SIP_PORT */
7513 if (*h == ':') {
7514 /* Parse port */
7515 ++h;
7516 port = strtol(h, &h, 10);
7518 else
7519 port = STANDARD_SIP_PORT;
7521 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
7522 maddr = strstr(h, "maddr=");
7523 if (maddr) {
7524 maddr += 6;
7525 hn = strspn(maddr, "0123456789.") + 1;
7526 if (hn > sizeof(hostname))
7527 hn = sizeof(hostname);
7528 ast_copy_string(hostname, maddr, hn);
7531 hp = ast_gethostbyname(hostname, &ahp);
7532 if (hp == NULL) {
7533 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
7534 return;
7536 p->sa.sin_family = AF_INET;
7537 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
7538 p->sa.sin_port = htons(port);
7539 if (debug)
7540 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
7543 /*! \brief Initialize SIP response, based on SIP request */
7544 static int init_resp(struct sip_request *resp, const char *msg)
7546 /* Initialize a response */
7547 memset(resp, 0, sizeof(*resp));
7548 resp->method = SIP_RESPONSE;
7549 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
7550 return -1;
7551 resp->header[0] = resp->data->str;
7552 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
7553 resp->len = strlen(resp->header[0]);
7554 resp->headers++;
7555 return 0;
7558 /*! \brief Initialize SIP request */
7559 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
7561 /* Initialize a request */
7562 memset(req, 0, sizeof(*req));
7563 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
7564 return -1;
7565 req->method = sipmethod;
7566 req->header[0] = req->data->str;
7567 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
7568 req->len = strlen(req->header[0]);
7569 req->headers++;
7570 return 0;
7574 /*! \brief Prepare SIP response packet */
7575 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
7577 char newto[256];
7578 const char *ot;
7580 init_resp(resp, msg);
7581 copy_via_headers(p, resp, req, "Via");
7582 if (msg[0] == '1' || msg[0] == '2')
7583 copy_all_header(resp, req, "Record-Route");
7584 copy_header(resp, req, "From");
7585 ot = get_header(req, "To");
7586 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
7587 /* Add the proper tag if we don't have it already. If they have specified
7588 their tag, use it. Otherwise, use our own tag */
7589 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
7590 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
7591 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
7592 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
7593 else
7594 ast_copy_string(newto, ot, sizeof(newto));
7595 ot = newto;
7597 add_header(resp, "To", ot);
7598 copy_header(resp, req, "Call-ID");
7599 copy_header(resp, req, "CSeq");
7600 if (!ast_strlen_zero(global_useragent))
7601 add_header(resp, "Server", global_useragent);
7602 add_header(resp, "Allow", ALLOWED_METHODS);
7603 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
7605 /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
7606 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
7607 char se_hdr[256];
7608 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
7609 strefresher2str(p->stimer->st_ref));
7610 add_header(resp, "Require", "timer");
7611 add_header(resp, "Session-Expires", se_hdr);
7614 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
7615 /* For registration responses, we also need expiry and
7616 contact info */
7617 char tmp[256];
7619 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
7620 add_header(resp, "Expires", tmp);
7621 if (p->expiry) { /* Only add contact if we have an expiry time */
7622 char contact[SIPBUFSIZE];
7623 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
7624 add_header(resp, "Contact", contact); /* Not when we unregister */
7626 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
7627 add_header(resp, "Contact", p->our_contact);
7630 if (!ast_strlen_zero(p->url)) {
7631 add_header(resp, "Access-URL", p->url);
7632 ast_string_field_set(p, url, NULL);
7635 return 0;
7638 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
7639 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
7641 struct sip_request *orig = &p->initreq;
7642 char stripped[80];
7643 char tmp[80];
7644 char newto[256];
7645 const char *c;
7646 const char *ot, *of;
7647 int is_strict = FALSE; /*!< Strict routing flag */
7648 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING); /* Session direction */
7650 memset(req, 0, sizeof(struct sip_request));
7652 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
7654 if (!seqno) {
7655 p->ocseq++;
7656 seqno = p->ocseq;
7659 if (newbranch) {
7660 p->branch ^= ast_random();
7661 build_via(p);
7664 /* Check for strict or loose router */
7665 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
7666 is_strict = TRUE;
7667 if (sipdebug)
7668 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
7671 if (sipmethod == SIP_CANCEL)
7672 c = p->initreq.rlPart2; /* Use original URI */
7673 else if (sipmethod == SIP_ACK) {
7674 /* Use URI from Contact: in 200 OK (if INVITE)
7675 (we only have the contacturi on INVITEs) */
7676 if (!ast_strlen_zero(p->okcontacturi))
7677 c = is_strict ? p->route->hop : p->okcontacturi;
7678 else
7679 c = p->initreq.rlPart2;
7680 } else if (!ast_strlen_zero(p->okcontacturi))
7681 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
7682 else if (!ast_strlen_zero(p->uri))
7683 c = p->uri;
7684 else {
7685 char *n;
7686 /* We have no URI, use To: or From: header as URI (depending on direction) */
7687 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
7688 sizeof(stripped));
7689 n = get_in_brackets(stripped);
7690 c = remove_uri_parameters(n);
7692 init_req(req, sipmethod, c);
7694 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
7696 add_header(req, "Via", p->via);
7697 if (p->route) {
7698 set_destination(p, p->route->hop);
7699 add_route(req, is_strict ? p->route->next : p->route);
7701 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7703 ot = get_header(orig, "To");
7704 of = get_header(orig, "From");
7706 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
7707 as our original request, including tag (or presumably lack thereof) */
7708 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
7709 /* Add the proper tag if we don't have it already. If they have specified
7710 their tag, use it. Otherwise, use our own tag */
7711 if (is_outbound && !ast_strlen_zero(p->theirtag))
7712 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
7713 else if (!is_outbound)
7714 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
7715 else
7716 snprintf(newto, sizeof(newto), "%s", ot);
7717 ot = newto;
7720 if (is_outbound) {
7721 add_header(req, "From", of);
7722 add_header(req, "To", ot);
7723 } else {
7724 add_header(req, "From", ot);
7725 add_header(req, "To", of);
7727 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
7728 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
7729 add_header(req, "Contact", p->our_contact);
7731 copy_header(req, orig, "Call-ID");
7732 add_header(req, "CSeq", tmp);
7734 if (!ast_strlen_zero(global_useragent))
7735 add_header(req, "User-Agent", global_useragent);
7737 if (!ast_strlen_zero(p->rpid))
7738 add_header(req, "Remote-Party-ID", p->rpid);
7740 if (!ast_strlen_zero(p->url)) {
7741 add_header(req, "Access-URL", p->url);
7742 ast_string_field_set(p, url, NULL);
7745 /* Add Session-Timers related headers if the feature is active for this session.
7746 An exception to this behavior is the ACK request. Since Asterisk never requires
7747 session-timers support from a remote end-point (UAS) in an INVITE, it must
7748 not send 'Require: timer' header in the ACK request.
7749 This should only be added in the INVITE transactions, not MESSAGE or REFER or other
7750 in-dialog messages.
7752 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
7753 && sipmethod == SIP_INVITE) {
7754 char se_hdr[256];
7755 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
7756 strefresher2str(p->stimer->st_ref));
7757 add_header(req, "Require", "timer");
7758 add_header(req, "Session-Expires", se_hdr);
7759 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
7760 add_header(req, "Min-SE", se_hdr);
7763 return 0;
7766 /*! \brief Base transmit response function */
7767 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
7769 struct sip_request resp;
7770 int seqno = 0;
7772 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
7773 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
7774 return -1;
7776 respprep(&resp, p, msg, req);
7777 add_header_contentLength(&resp, 0);
7778 /* If we are cancelling an incoming invite for some reason, add information
7779 about the reason why we are doing this in clear text */
7780 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
7781 char buf[10];
7783 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7784 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7785 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7787 return send_response(p, &resp, reliable, seqno);
7790 static int temp_pvt_init(void *data)
7792 struct sip_pvt *p = data;
7794 p->do_history = 0; /* XXX do we need it ? isn't already all 0 ? */
7795 return ast_string_field_init(p, 512);
7798 static void temp_pvt_cleanup(void *data)
7800 struct sip_pvt *p = data;
7802 ast_string_field_free_memory(p);
7804 ast_free(data);
7807 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
7808 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
7810 struct sip_pvt *p = NULL;
7812 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
7813 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
7814 return -1;
7817 /* XXX the structure may be dirty from previous usage.
7818 * Here we should state clearly how we should reinitialize it
7819 * before using it.
7820 * E.g. certainly the threadstorage should be left alone,
7821 * but other thihngs such as flags etc. maybe need cleanup ?
7824 /* Initialize the bare minimum */
7825 p->method = intended_method;
7827 if (!sin)
7828 p->ourip = internip;
7829 else {
7830 p->sa = *sin;
7831 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
7834 p->branch = ast_random();
7835 make_our_tag(p->tag, sizeof(p->tag));
7836 p->ocseq = INITIAL_CSEQ;
7838 if (useglobal_nat && sin) {
7839 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
7840 p->recv = *sin;
7841 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
7844 ast_string_field_set(p, fromdomain, default_fromdomain);
7845 build_via(p);
7846 ast_string_field_set(p, callid, callid);
7848 copy_socket_data(&p->socket, &req->socket);
7850 /* Use this temporary pvt structure to send the message */
7851 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
7853 /* Free the string fields, but not the pool space */
7854 ast_string_field_init(p, 0);
7856 return 0;
7859 /*! \brief Transmit response, no retransmits */
7860 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
7862 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
7865 /*! \brief Transmit response, no retransmits */
7866 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
7868 struct sip_request resp;
7869 respprep(&resp, p, msg, req);
7870 append_date(&resp);
7871 add_header(&resp, "Unsupported", unsupported);
7872 add_header_contentLength(&resp, 0);
7873 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
7876 /*! \brief Transmit 422 response with Min-SE header (Session-Timers) */
7877 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
7879 struct sip_request resp;
7880 char minse_str[20];
7882 respprep(&resp, p, msg, req);
7883 append_date(&resp);
7885 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
7886 add_header(&resp, "Min-SE", minse_str);
7888 add_header_contentLength(&resp, 0);
7889 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
7893 /*! \brief Transmit response, Make sure you get an ACK
7894 This is only used for responses to INVITEs, where we need to make sure we get an ACK
7896 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
7898 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
7901 /*! \brief Append date to SIP message */
7902 static void append_date(struct sip_request *req)
7904 char tmpdat[256];
7905 struct tm tm;
7906 time_t t = time(NULL);
7908 gmtime_r(&t, &tm);
7909 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
7910 add_header(req, "Date", tmpdat);
7913 /*! \brief Append date and content length before transmitting response */
7914 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
7916 struct sip_request resp;
7917 respprep(&resp, p, msg, req);
7918 append_date(&resp);
7919 add_header_contentLength(&resp, 0);
7920 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
7923 /*! \brief Append Accept header, content length before transmitting response */
7924 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
7926 struct sip_request resp;
7927 respprep(&resp, p, msg, req);
7928 add_header(&resp, "Accept", "application/sdp");
7929 add_header_contentLength(&resp, 0);
7930 return send_response(p, &resp, reliable, 0);
7933 /*! \brief Respond with authorization request */
7934 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
7936 struct sip_request resp;
7937 char tmp[512];
7938 int seqno = 0;
7940 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
7941 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
7942 return -1;
7944 /* Stale means that they sent us correct authentication, but
7945 based it on an old challenge (nonce) */
7946 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
7947 respprep(&resp, p, msg, req);
7948 add_header(&resp, header, tmp);
7949 add_header_contentLength(&resp, 0);
7950 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
7951 return send_response(p, &resp, reliable, seqno);
7954 /*! \brief Add text body to SIP message */
7955 static int add_text(struct sip_request *req, const char *text)
7957 /* XXX Convert \n's to \r\n's XXX */
7958 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
7959 add_header_contentLength(req, strlen(text));
7960 add_line(req, text);
7961 return 0;
7964 /*! \brief Add DTMF INFO tone to sip message
7965 Mode = 0 for application/dtmf-relay (Cisco)
7966 1 for application/dtmf
7968 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
7970 char tmp[256];
7971 int event;
7972 if (mode) {
7973 /* Application/dtmf short version used by some implementations */
7974 if (digit == '*')
7975 event = 10;
7976 else if (digit == '#')
7977 event = 11;
7978 else if ((digit >= 'A') && (digit <= 'D'))
7979 event = 12 + digit - 'A';
7980 else
7981 event = atoi(&digit);
7982 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
7983 add_header(req, "Content-Type", "application/dtmf");
7984 add_header_contentLength(req, strlen(tmp));
7985 add_line(req, tmp);
7986 } else {
7987 /* Application/dtmf-relay as documented by Cisco */
7988 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
7989 add_header(req, "Content-Type", "application/dtmf-relay");
7990 add_header_contentLength(req, strlen(tmp));
7991 add_line(req, tmp);
7993 return 0;
7996 /*! \brief add XML encoded media control with update
7997 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
7998 static int add_vidupdate(struct sip_request *req)
8000 const char *xml_is_a_huge_waste_of_space =
8001 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
8002 " <media_control>\r\n"
8003 " <vc_primitive>\r\n"
8004 " <to_encoder>\r\n"
8005 " <picture_fast_update>\r\n"
8006 " </picture_fast_update>\r\n"
8007 " </to_encoder>\r\n"
8008 " </vc_primitive>\r\n"
8009 " </media_control>\r\n";
8010 add_header(req, "Content-Type", "application/media_control+xml");
8011 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
8012 add_line(req, xml_is_a_huge_waste_of_space);
8013 return 0;
8016 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
8017 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
8018 struct ast_str **m_buf, struct ast_str **a_buf,
8019 int debug, int *min_packet_size)
8021 int rtp_code;
8022 struct ast_format_list fmt;
8025 if (debug)
8026 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
8027 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
8028 return;
8030 if (p->rtp) {
8031 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
8032 fmt = ast_codec_pref_getsize(pref, codec);
8033 } else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
8034 return;
8035 ast_str_append(m_buf, 0, " %d", rtp_code);
8036 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8037 ast_rtp_lookup_mime_subtype(1, codec,
8038 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
8039 sample_rate);
8040 if (codec == AST_FORMAT_G729A) {
8041 /* Indicate that we don't support VAD (G.729 annex B) */
8042 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
8043 } else if (codec == AST_FORMAT_G723_1) {
8044 /* Indicate that we don't support VAD (G.723.1 annex A) */
8045 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
8046 } else if (codec == AST_FORMAT_ILBC) {
8047 /* Add information about us using only 20/30 ms packetization */
8048 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
8051 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
8052 *min_packet_size = fmt.cur_ms;
8054 /* Our first codec packetization processed cannot be zero */
8055 if ((*min_packet_size)==0 && fmt.cur_ms)
8056 *min_packet_size = fmt.cur_ms;
8059 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
8060 /* This is different to the audio one now so we can add more caps later */
8061 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
8062 struct ast_str **m_buf, struct ast_str **a_buf,
8063 int debug, int *min_packet_size)
8065 int rtp_code;
8067 if (!p->vrtp)
8068 return;
8070 if (debug)
8071 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
8073 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
8074 return;
8076 ast_str_append(m_buf, 0, " %d", rtp_code);
8077 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8078 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
8079 /* Add fmtp code here */
8082 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
8083 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
8084 struct ast_str **m_buf, struct ast_str **a_buf,
8085 int debug, int *min_packet_size)
8087 int rtp_code;
8089 if (!p->trtp)
8090 return;
8092 if (debug)
8093 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
8095 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
8096 return;
8098 ast_str_append(m_buf, 0, " %d", rtp_code);
8099 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8100 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
8101 /* Add fmtp code here */
8103 if (codec == AST_FORMAT_T140RED) {
8104 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
8105 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
8106 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
8107 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
8113 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
8114 static int t38_get_rate(int t38cap)
8116 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
8118 if (maxrate & T38FAX_RATE_14400) {
8119 ast_debug(2, "T38MaxFaxRate 14400 found\n");
8120 return 14400;
8121 } else if (maxrate & T38FAX_RATE_12000) {
8122 ast_debug(2, "T38MaxFaxRate 12000 found\n");
8123 return 12000;
8124 } else if (maxrate & T38FAX_RATE_9600) {
8125 ast_debug(2, "T38MaxFaxRate 9600 found\n");
8126 return 9600;
8127 } else if (maxrate & T38FAX_RATE_7200) {
8128 ast_debug(2, "T38MaxFaxRate 7200 found\n");
8129 return 7200;
8130 } else if (maxrate & T38FAX_RATE_4800) {
8131 ast_debug(2, "T38MaxFaxRate 4800 found\n");
8132 return 4800;
8133 } else if (maxrate & T38FAX_RATE_2400) {
8134 ast_debug(2, "T38MaxFaxRate 2400 found\n");
8135 return 2400;
8136 } else {
8137 ast_debug(2, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
8138 return 0;
8142 /*! \brief Add T.38 Session Description Protocol message */
8143 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
8145 int len = 0;
8146 int x = 0;
8147 struct sockaddr_in udptlsin;
8148 struct ast_str *m_modem = ast_str_alloca(1024);
8149 struct ast_str *a_modem = ast_str_alloca(1024);
8150 struct sockaddr_in udptldest = { 0, };
8151 int debug;
8153 debug = sip_debug_test_pvt(p);
8154 len = 0;
8155 if (!p->udptl) {
8156 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
8157 return -1;
8160 if (!p->sessionid) {
8161 p->sessionid = (int)ast_random();
8162 p->sessionversion = p->sessionid;
8163 } else
8164 p->sessionversion++;
8166 /* Our T.38 end is */
8167 ast_udptl_get_us(p->udptl, &udptlsin);
8169 /* Determine T.38 UDPTL destination */
8170 if (p->udptlredirip.sin_addr.s_addr) {
8171 udptldest.sin_port = p->udptlredirip.sin_port;
8172 udptldest.sin_addr = p->udptlredirip.sin_addr;
8173 } else {
8174 udptldest.sin_addr = p->ourip.sin_addr;
8175 udptldest.sin_port = udptlsin.sin_port;
8178 if (debug)
8179 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
8181 /* We break with the "recommendation" and send our IP, in order that our
8182 peer doesn't have to ast_gethostbyname() us */
8184 if (debug) {
8185 ast_debug(1, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
8186 p->t38.capability,
8187 p->t38.peercapability,
8188 p->t38.jointcapability);
8190 ast_str_append(&m_modem, 0, "v=0\r\n");
8191 ast_str_append(&m_modem, 0, "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner , p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
8192 ast_str_append(&m_modem, 0, "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
8193 ast_str_append(&m_modem, 0, "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
8194 ast_str_append(&m_modem, 0, "t=0 0\r\n");
8195 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
8197 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
8198 ast_str_append(&a_modem, 0, "a=T38FaxVersion:0\r\n");
8199 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
8200 ast_str_append(&a_modem, 0, "a=T38FaxVersion:1\r\n");
8201 if ((x = t38_get_rate(p->t38.jointcapability)))
8202 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", x);
8203 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
8204 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
8205 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
8206 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
8207 x = ast_udptl_get_local_max_datagram(p->udptl);
8208 ast_str_append(&a_modem, 0, "a=T38FaxMaxBuffer:%d\r\n", x);
8209 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%d\r\n", x);
8210 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
8211 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
8212 len = m_modem->used + a_modem->used;
8213 add_header(resp, "Content-Type", "application/sdp");
8214 add_header_contentLength(resp, len);
8215 add_line(resp, m_modem->str);
8216 add_line(resp, a_modem->str);
8218 /* Update lastrtprx when we send our SDP */
8219 p->lastrtprx = p->lastrtptx = time(NULL);
8221 return 0;
8225 /*! \brief Add RFC 2833 DTMF offer to SDP */
8226 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
8227 struct ast_str **m_buf, struct ast_str **a_buf,
8228 int debug)
8230 int rtp_code;
8232 if (debug)
8233 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
8234 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
8235 return;
8237 ast_str_append(m_buf, 0, " %d", rtp_code);
8238 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8239 ast_rtp_lookup_mime_subtype(0, format, 0),
8240 sample_rate);
8241 if (format == AST_RTP_DTMF) /* Indicate we support DTMF and FLASH... */
8242 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
8245 /*! \brief Set all IP media addresses for this call
8246 \note called from add_sdp()
8248 static void get_our_media_address(struct sip_pvt *p, int needvideo,
8249 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
8250 struct sockaddr_in *dest, struct sockaddr_in *vdest)
8252 /* First, get our address */
8253 ast_rtp_get_us(p->rtp, sin);
8254 if (p->vrtp)
8255 ast_rtp_get_us(p->vrtp, vsin);
8256 if (p->trtp)
8257 ast_rtp_get_us(p->trtp, tsin);
8259 /* Now, try to figure out where we want them to send data */
8260 /* Is this a re-invite to move the media out, then use the original offer from caller */
8261 if (p->redirip.sin_addr.s_addr) { /* If we have a redirection IP, use it */
8262 dest->sin_port = p->redirip.sin_port;
8263 dest->sin_addr = p->redirip.sin_addr;
8264 } else {
8265 dest->sin_addr = p->ourip.sin_addr;
8266 dest->sin_port = sin->sin_port;
8268 if (needvideo) {
8269 /* Determine video destination */
8270 if (p->vredirip.sin_addr.s_addr) {
8271 vdest->sin_addr = p->vredirip.sin_addr;
8272 vdest->sin_port = p->vredirip.sin_port;
8273 } else {
8274 vdest->sin_addr = p->ourip.sin_addr;
8275 vdest->sin_port = vsin->sin_port;
8282 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
8283 * really 16 kHz. Update this macro for other formats as they are added in
8284 * the future.
8286 #define SDP_SAMPLE_RATE(x) 8000
8288 /*! \brief Add Session Description Protocol message
8290 If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
8291 is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
8292 without modifying the media session in any way.
8294 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp)
8296 int len = 0;
8297 int alreadysent = 0;
8299 struct sockaddr_in sin;
8300 struct sockaddr_in vsin;
8301 struct sockaddr_in tsin;
8302 struct sockaddr_in dest;
8303 struct sockaddr_in vdest = { 0, };
8304 struct sockaddr_in tdest = { 0, };
8306 /* SDP fields */
8307 char *version = "v=0\r\n"; /* Protocol version */
8308 char subject[256]; /* Subject of the session */
8309 char owner[256]; /* Session owner/creator */
8310 char connection[256]; /* Connection data */
8311 char *stime = "t=0 0\r\n"; /* Time the session is active */
8312 char bandwidth[256] = ""; /* Max bitrate */
8313 char *hold;
8314 struct ast_str *m_audio = ast_str_alloca(256); /* Media declaration line for audio */
8315 struct ast_str *m_video = ast_str_alloca(256); /* Media declaration line for video */
8316 struct ast_str *m_text = ast_str_alloca(256); /* Media declaration line for text */
8317 struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
8318 struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
8319 struct ast_str *a_text = ast_str_alloca(1024); /* Attributes for text */
8321 int x;
8322 int capability;
8323 int needaudio = FALSE;
8324 int needvideo = FALSE;
8325 int needtext = FALSE;
8326 int debug = sip_debug_test_pvt(p);
8327 int min_audio_packet_size = 0;
8328 int min_video_packet_size = 0;
8329 int min_text_packet_size = 0;
8331 char codecbuf[SIPBUFSIZE];
8332 char buf[SIPBUFSIZE];
8334 /* Set the SDP session name */
8335 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
8337 if (!p->rtp) {
8338 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
8339 return AST_FAILURE;
8341 /* XXX We should not change properties in the SIP dialog until
8342 we have acceptance of the offer if this is a re-invite */
8344 /* Set RTP Session ID and version */
8345 if (!p->sessionid) {
8346 p->sessionid = (int)ast_random();
8347 p->sessionversion = p->sessionid;
8348 } else {
8349 if (oldsdp == FALSE)
8350 p->sessionversion++;
8353 capability = p->jointcapability;
8355 /* XXX note, Video and Text are negated - 'true' means 'no' */
8356 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
8357 p->novideo ? "True" : "False", p->notext ? "True" : "False");
8358 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
8360 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
8361 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
8362 ast_str_append(&m_audio, 0, " %d", 191);
8363 ast_str_append(&a_audio, 0, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
8365 #endif
8367 /* Check if we need audio */
8368 if (capability & AST_FORMAT_AUDIO_MASK)
8369 needaudio = TRUE;
8371 /* Check if we need video in this call */
8372 if ((capability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
8373 if (p->vrtp) {
8374 needvideo = TRUE;
8375 ast_debug(2, "This call needs video offers!\n");
8376 } else
8377 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
8380 /* Get our media addresses */
8381 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
8383 if (debug)
8384 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
8386 /* Ok, we need video. Let's add what we need for video and set codecs.
8387 Video is handled differently than audio since we can not transcode. */
8388 if (needvideo) {
8389 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
8391 /* Build max bitrate string */
8392 if (p->maxcallbitrate)
8393 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
8394 if (debug)
8395 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vsin.sin_port));
8398 /* Check if we need text in this call */
8399 if((capability & AST_FORMAT_TEXT_MASK) && !p->notext) {
8400 if (sipdebug_text)
8401 ast_verbose("We think we can do text\n");
8402 if (p->trtp) {
8403 if (sipdebug_text)
8404 ast_verbose("And we have a text rtp object\n");
8405 needtext = TRUE;
8406 ast_debug(2, "This call needs text offers! \n");
8407 } else
8408 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
8411 /* Ok, we need text. Let's add what we need for text and set codecs.
8412 Text is handled differently than audio since we can not transcode. */
8413 if (needtext) {
8414 if (sipdebug_text)
8415 ast_verbose("Lets set up the text sdp\n");
8416 /* Determine text destination */
8417 if (p->tredirip.sin_addr.s_addr) {
8418 tdest.sin_addr = p->tredirip.sin_addr;
8419 tdest.sin_port = p->tredirip.sin_port;
8420 } else {
8421 tdest.sin_addr = p->ourip.sin_addr;
8422 tdest.sin_port = tsin.sin_port;
8424 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
8426 if (debug) /* XXX should I use tdest below ? */
8427 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
8431 /* Start building generic SDP headers */
8433 /* We break with the "recommendation" and send our IP, in order that our
8434 peer doesn't have to ast_gethostbyname() us */
8436 snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
8437 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
8438 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
8440 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
8441 hold = "a=recvonly\r\n";
8442 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
8443 hold = "a=inactive\r\n";
8444 else
8445 hold = "a=sendrecv\r\n";
8447 /* Now, start adding audio codecs. These are added in this order:
8448 - First what was requested by the calling channel
8449 - Then preferences in order from sip.conf device config for this peer/user
8450 - Then other codecs in capabilities, including video
8453 /* Prefer the audio codec we were requested to use, first, no matter what
8454 Note that p->prefcodec can include video codecs, so mask them out
8456 if (capability & p->prefcodec) {
8457 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
8459 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
8460 &m_audio, &a_audio,
8461 debug, &min_audio_packet_size);
8462 alreadysent |= codec;
8465 /* Start by sending our preferred audio/video codecs */
8466 for (x = 0; x < 32; x++) {
8467 int codec;
8469 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
8470 break;
8472 if (!(capability & codec))
8473 continue;
8475 if (alreadysent & codec)
8476 continue;
8478 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
8479 &m_audio, &a_audio,
8480 debug, &min_audio_packet_size);
8481 alreadysent |= codec;
8484 /* Now send any other common audio and video codecs, and non-codec formats: */
8485 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
8486 if (!(capability & x)) /* Codec not requested */
8487 continue;
8489 if (alreadysent & x) /* Already added to SDP */
8490 continue;
8492 if (x & AST_FORMAT_AUDIO_MASK)
8493 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
8494 &m_audio, &a_audio, debug, &min_audio_packet_size);
8495 else if (x & AST_FORMAT_VIDEO_MASK)
8496 add_vcodec_to_sdp(p, x, 90000,
8497 &m_video, &a_video, debug, &min_video_packet_size);
8498 else if (x & AST_FORMAT_TEXT_MASK)
8499 add_tcodec_to_sdp(p, x, 1000,
8500 &m_text, &a_text, debug, &min_text_packet_size);
8503 /* Now add DTMF RFC2833 telephony-event as a codec */
8504 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
8505 if (!(p->jointnoncodeccapability & x))
8506 continue;
8508 add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
8511 ast_debug(3, "-- Done with adding codecs to SDP\n");
8513 if (!p->owner || !ast_internal_timing_enabled(p->owner))
8514 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
8516 if (min_audio_packet_size)
8517 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
8519 /* XXX don't think you can have ptime for video */
8520 if (min_video_packet_size)
8521 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
8523 /* XXX don't think you can have ptime for text */
8524 if (min_text_packet_size)
8525 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
8527 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
8528 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
8529 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
8530 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
8532 if (needaudio)
8533 ast_str_append(&m_audio, 0, "\r\n");
8534 if (needvideo)
8535 ast_str_append(&m_video, 0, "\r\n");
8536 if (needtext)
8537 ast_str_append(&m_text, 0, "\r\n");
8539 len = strlen(version) + strlen(subject) + strlen(owner) +
8540 strlen(connection) + strlen(stime);
8541 if (needaudio)
8542 len += m_audio->used + a_audio->used + strlen(hold);
8543 if (needvideo) /* only if video response is appropriate */
8544 len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
8545 if (needtext) /* only if text response is appropriate */
8546 len += m_text->used + a_text->used + strlen(hold);
8548 add_header(resp, "Content-Type", "application/sdp");
8549 add_header_contentLength(resp, len);
8550 add_line(resp, version);
8551 add_line(resp, owner);
8552 add_line(resp, subject);
8553 add_line(resp, connection);
8554 if (needvideo) /* only if video response is appropriate */
8555 add_line(resp, bandwidth);
8556 add_line(resp, stime);
8557 if (needaudio) {
8558 add_line(resp, m_audio->str);
8559 add_line(resp, a_audio->str);
8560 add_line(resp, hold);
8562 if (needvideo) { /* only if video response is appropriate */
8563 add_line(resp, m_video->str);
8564 add_line(resp, a_video->str);
8565 add_line(resp, hold); /* Repeat hold for the video stream */
8567 if (needtext) { /* only if text response is appropriate */
8568 add_line(resp, m_text->str);
8569 add_line(resp, a_text->str);
8570 add_line(resp, hold); /* Repeat hold for the text stream */
8573 /* Update lastrtprx when we send our SDP */
8574 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
8576 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
8578 return AST_SUCCESS;
8581 /*! \brief Used for 200 OK and 183 early media */
8582 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
8584 struct sip_request resp;
8585 int seqno;
8587 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
8588 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
8589 return -1;
8591 respprep(&resp, p, msg, req);
8592 if (p->udptl) {
8593 ast_udptl_offered_from_local(p->udptl, 0);
8594 add_t38_sdp(&resp, p);
8595 } else
8596 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
8597 if (retrans && !p->pendinginvite)
8598 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
8599 return send_response(p, &resp, retrans, seqno);
8602 /*! \brief copy SIP request (mostly used to save request for responses) */
8603 static void copy_request(struct sip_request *dst, const struct sip_request *src)
8605 long offset;
8606 int x;
8607 struct ast_str *dup = dst->data;
8609 /* First copy stuff */
8610 memcpy(dst, src, sizeof(*dst));
8611 dst->data = dup;
8613 /* All these + 1's are to account for the need to include the NULL terminator
8614 * Using typical string functions like ast_copy_string or ast_str_set will not
8615 * work in this case because the src's data string is riddled with \0's all over
8616 * the place and so a memcpy is the only way to accurately copy the string
8619 if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
8620 return;
8621 else if (dst->data->len < src->data->used + 1)
8622 ast_str_make_space(&dst->data, src->data->used + 1);
8624 memcpy(dst->data->str, src->data->str, src->data->used + 1);
8625 dst->data->used = src->data->used;
8626 offset = ((void *)dst->data->str) - ((void *)src->data->str);
8627 /* Now fix pointer arithmetic */
8628 for (x = 0; x < src->headers; x++)
8629 dst->header[x] += offset;
8630 for (x = 0; x < src->lines; x++)
8631 dst->line[x] += offset;
8632 /* On some occasions this function is called without parse_request being called first so lets not create an invalid pointer */
8633 if (src->rlPart1)
8634 dst->rlPart1 += offset;
8635 if (src->rlPart2)
8636 dst->rlPart2 += offset;
8639 /*! \brief Used for 200 OK and 183 early media
8640 \return Will return XMIT_ERROR for network errors.
8642 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
8644 struct sip_request resp;
8645 int seqno;
8646 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
8647 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
8648 return -1;
8650 respprep(&resp, p, msg, req);
8651 if (p->rtp) {
8652 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
8653 ast_debug(1, "Setting framing from config on incoming call\n");
8654 ast_rtp_codec_setpref(p->rtp, &p->prefs);
8656 try_suggested_sip_codec(p);
8657 add_sdp(&resp, p, oldsdp);
8658 } else
8659 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
8660 if (reliable && !p->pendinginvite)
8661 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
8662 return send_response(p, &resp, reliable, seqno);
8665 /*! \brief Parse first line of incoming SIP request */
8666 static int determine_firstline_parts(struct sip_request *req)
8668 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
8670 if (!*e)
8671 return -1;
8672 req->rlPart1 = e; /* method or protocol */
8673 e = ast_skip_nonblanks(e);
8674 if (*e)
8675 *e++ = '\0';
8676 /* Get URI or status code */
8677 e = ast_skip_blanks(e);
8678 if ( !*e )
8679 return -1;
8680 ast_trim_blanks(e);
8682 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
8683 if (strlen(e) < 3) /* status code is 3 digits */
8684 return -1;
8685 req->rlPart2 = e;
8686 } else { /* We have a request */
8687 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
8688 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
8689 e++;
8690 if (!*e)
8691 return -1;
8693 req->rlPart2 = e; /* URI */
8694 e = ast_skip_nonblanks(e);
8695 if (*e)
8696 *e++ = '\0';
8697 e = ast_skip_blanks(e);
8698 if (strcasecmp(e, "SIP/2.0") ) {
8699 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
8700 return -1;
8703 return 1;
8706 /*! \brief Transmit reinvite with SDP
8707 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
8708 INVITE that opened the SIP dialogue
8709 We reinvite so that the audio stream (RTP) go directly between
8710 the SIP UAs. SIP Signalling stays with * in the path.
8712 If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
8713 T38 UDPTL transmission on the channel
8715 If oldsdp is TRUE then the SDP version number is not incremented. This
8716 is needed for Session-Timers so we can send a re-invite to refresh the
8717 SIP session without modifying the media session.
8719 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
8721 struct sip_request req;
8723 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
8725 add_header(&req, "Allow", ALLOWED_METHODS);
8726 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
8727 if (sipdebug) {
8728 if (oldsdp == TRUE)
8729 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
8730 else
8731 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
8734 if (p->do_history)
8735 append_history(p, "ReInv", "Re-invite sent");
8736 if (t38version)
8737 add_t38_sdp(&req, p);
8738 else
8739 add_sdp(&req, p, oldsdp);
8741 /* Use this as the basis */
8742 initialize_initreq(p, &req);
8743 p->lastinvite = p->ocseq;
8744 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
8746 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
8749 /* \brief Remove URI parameters at end of URI, not in username part though */
8750 static char *remove_uri_parameters(char *uri)
8752 char *atsign;
8753 atsign = strchr(uri, '@'); /* First, locate the at sign */
8754 if (!atsign)
8755 atsign = uri; /* Ok hostname only, let's stick with the rest */
8756 atsign = strchr(atsign, ';'); /* Locate semi colon */
8757 if (atsign)
8758 *atsign = '\0'; /* Kill at the semi colon */
8759 return uri;
8762 /*! \brief Check Contact: URI of SIP message */
8763 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
8765 char stripped[SIPBUFSIZE];
8766 char *c;
8768 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
8769 c = get_in_brackets(stripped);
8770 /* Cut the URI at the at sign after the @, not in the username part */
8771 c = remove_uri_parameters(c);
8772 if (!ast_strlen_zero(c))
8773 ast_string_field_set(p, uri, c);
8777 /*! \brief Build contact header - the contact header we send out */
8778 static void build_contact(struct sip_pvt *p)
8780 /* Construct Contact: header */
8781 if (p->socket.type & SIP_TRANSPORT_UDP) {
8782 if (!sip_standard_port(p->socket))
8783 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ntohs(p->socket.port));
8784 else
8785 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
8786 } else
8787 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ntohs(p->socket.port), get_transport_pvt(p));
8790 /*! \brief Build the Remote Party-ID & From using callingpres options */
8791 static void build_rpid(struct sip_pvt *p)
8793 int send_pres_tags = TRUE;
8794 const char *privacy=NULL;
8795 const char *screen=NULL;
8796 char buf[256];
8797 const char *clid = default_callerid;
8798 const char *clin = NULL;
8799 const char *fromdomain;
8801 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
8802 return;
8804 if (p->owner && p->owner->cid.cid_num)
8805 clid = p->owner->cid.cid_num;
8806 if (p->owner && p->owner->cid.cid_name)
8807 clin = p->owner->cid.cid_name;
8808 if (ast_strlen_zero(clin))
8809 clin = clid;
8811 switch (p->callingpres) {
8812 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
8813 privacy = "off";
8814 screen = "no";
8815 break;
8816 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
8817 privacy = "off";
8818 screen = "yes";
8819 break;
8820 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
8821 privacy = "off";
8822 screen = "no";
8823 break;
8824 case AST_PRES_ALLOWED_NETWORK_NUMBER:
8825 privacy = "off";
8826 screen = "yes";
8827 break;
8828 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
8829 privacy = "full";
8830 screen = "no";
8831 break;
8832 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
8833 privacy = "full";
8834 screen = "yes";
8835 break;
8836 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
8837 privacy = "full";
8838 screen = "no";
8839 break;
8840 case AST_PRES_PROHIB_NETWORK_NUMBER:
8841 privacy = "full";
8842 screen = "yes";
8843 break;
8844 case AST_PRES_NUMBER_NOT_AVAILABLE:
8845 send_pres_tags = FALSE;
8846 break;
8847 default:
8848 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
8849 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
8850 privacy = "full";
8851 else
8852 privacy = "off";
8853 screen = "no";
8854 break;
8857 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
8859 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
8860 if (send_pres_tags)
8861 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
8862 ast_string_field_set(p, rpid, buf);
8864 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
8865 S_OR(p->fromuser, clid),
8866 fromdomain, p->tag);
8869 /*! \brief Initiate new SIP request to peer/user */
8870 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
8872 struct ast_str *invite = ast_str_alloca(256);
8873 char from[256];
8874 char to[256];
8875 char tmp_n[SIPBUFSIZE/2]; /* build a local copy of 'n' if needed */
8876 char tmp_l[SIPBUFSIZE/2]; /* build a local copy of 'l' if needed */
8877 const char *l = NULL; /* XXX what is this, exactly ? */
8878 const char *n = NULL; /* XXX what is this, exactly ? */
8879 const char *urioptions = "";
8881 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
8882 const char *s = p->username; /* being a string field, cannot be NULL */
8884 /* Test p->username against allowed characters in AST_DIGIT_ANY
8885 If it matches the allowed characters list, then sipuser = ";user=phone"
8886 If not, then sipuser = ""
8888 /* + is allowed in first position in a tel: uri */
8889 if (*s == '+')
8890 s++;
8891 for (; *s; s++) {
8892 if (!strchr(AST_DIGIT_ANYNUM, *s) )
8893 break;
8895 /* If we have only digits, add ;user=phone to the uri */
8896 if (*s)
8897 urioptions = ";user=phone";
8901 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
8903 if (p->owner) {
8904 l = p->owner->cid.cid_num;
8905 n = p->owner->cid.cid_name;
8907 /* if we are not sending RPID and user wants his callerid restricted */
8908 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
8909 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
8910 l = CALLERID_UNKNOWN;
8911 n = l;
8913 if (ast_strlen_zero(l))
8914 l = default_callerid;
8915 if (ast_strlen_zero(n))
8916 n = l;
8917 /* Allow user to be overridden */
8918 if (!ast_strlen_zero(p->fromuser))
8919 l = p->fromuser;
8920 else /* Save for any further attempts */
8921 ast_string_field_set(p, fromuser, l);
8923 /* Allow user to be overridden */
8924 if (!ast_strlen_zero(p->fromname))
8925 n = p->fromname;
8926 else /* Save for any further attempts */
8927 ast_string_field_set(p, fromname, n);
8929 if (pedanticsipchecking) {
8930 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
8931 n = tmp_n;
8932 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
8933 l = tmp_l;
8936 if (!sip_standard_port(p->socket) && ast_strlen_zero(p->fromdomain))
8937 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr)), ntohs(p->socket.port), p->tag);
8938 else
8939 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr)), p->tag);
8941 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
8942 if (!ast_strlen_zero(p->fullcontact)) {
8943 /* If we have full contact, trust it */
8944 ast_str_append(&invite, 0, "%s", p->fullcontact);
8945 } else {
8946 /* Otherwise, use the username while waiting for registration */
8947 ast_str_append(&invite, 0, "sip:");
8948 if (!ast_strlen_zero(p->username)) {
8949 n = p->username;
8950 if (pedanticsipchecking) {
8951 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
8952 n = tmp_n;
8954 ast_str_append(&invite, 0, "%s@", n);
8956 ast_str_append(&invite, 0, "%s", p->tohost);
8957 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
8958 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
8959 ast_str_append(&invite, 0, "%s", urioptions);
8962 /* If custom URI options have been provided, append them */
8963 if (p->options && !ast_strlen_zero(p->options->uri_options))
8964 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
8966 /* This is the request URI, which is the next hop of the call
8967 which may or may not be the destination of the call
8969 ast_string_field_set(p, uri, invite->str);
8971 if (!ast_strlen_zero(p->todnid)) {
8972 /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
8973 if (!strchr(p->todnid, '@')) {
8974 /* We have no domain in the dnid */
8975 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
8976 } else {
8977 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
8979 } else {
8980 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
8981 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
8982 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
8983 } else if (p->options && p->options->vxml_url) {
8984 /* If there is a VXML URL append it to the SIP URL */
8985 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
8986 } else
8987 snprintf(to, sizeof(to), "<%s>", p->uri);
8990 init_req(req, sipmethod, p->uri);
8991 /* now tmp_n is available so reuse it to build the CSeq */
8992 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
8994 add_header(req, "Via", p->via);
8995 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
8996 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
8997 * OTOH, then we won't have anything in p->route anyway */
8999 /* Build Remote Party-ID and From */
9000 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
9001 build_rpid(p);
9002 add_header(req, "From", p->rpid_from);
9003 } else
9004 add_header(req, "From", from);
9005 add_header(req, "To", to);
9006 ast_string_field_set(p, exten, l);
9007 build_contact(p);
9008 add_header(req, "Contact", p->our_contact);
9009 add_header(req, "Call-ID", p->callid);
9010 add_header(req, "CSeq", tmp_n);
9011 if (!ast_strlen_zero(global_useragent))
9012 add_header(req, "User-Agent", global_useragent);
9013 if (!ast_strlen_zero(p->rpid))
9014 add_header(req, "Remote-Party-ID", p->rpid);
9017 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it
9018 \param init 0 = Prepare request within dialog, 1= prepare request, new branch, 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
9019 \param p sip_pvt structure
9020 \param sdp unknown
9021 \param sipmethod unknown
9024 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
9026 struct sip_request req;
9027 struct ast_variable *var;
9029 req.method = sipmethod;
9030 if (init) {/* Bump branch even on initial requests */
9031 p->branch ^= ast_random();
9032 build_via(p);
9034 if (init > 1)
9035 initreqprep(&req, p, sipmethod);
9036 else
9037 reqprep(&req, p, sipmethod, 0, 1);
9039 if (p->options && p->options->auth)
9040 add_header(&req, p->options->authheader, p->options->auth);
9041 append_date(&req);
9042 if (sipmethod == SIP_REFER) { /* Call transfer */
9043 if (p->refer) {
9044 char buf[SIPBUFSIZE];
9045 if (!ast_strlen_zero(p->refer->refer_to))
9046 add_header(&req, "Refer-To", p->refer->refer_to);
9047 if (!ast_strlen_zero(p->refer->referred_by)) {
9048 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
9049 add_header(&req, "Referred-By", buf);
9053 /* This new INVITE is part of an attended transfer. Make sure that the
9054 other end knows and replace the current call with this new call */
9055 if (p->options && !ast_strlen_zero(p->options->replaces)) {
9056 add_header(&req, "Replaces", p->options->replaces);
9057 add_header(&req, "Require", "replaces");
9060 /* Add Session-Timers related headers */
9061 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
9062 char i2astr[10];
9064 if (!p->stimer->st_interval)
9065 p->stimer->st_interval = st_get_se(p, TRUE);
9067 p->stimer->st_active = TRUE;
9069 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
9070 add_header(&req, "Session-Expires", i2astr);
9071 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
9072 add_header(&req, "Min-SE", i2astr);
9075 add_header(&req, "Allow", ALLOWED_METHODS);
9076 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
9078 if(p->notify_headers) {
9079 char buf[512];
9080 for (var = p->notify_headers; var; var = var->next) {
9081 ast_copy_string(buf, var->value, sizeof(buf));
9082 add_header(&req, var->name, ast_unescape_semicolon(buf));
9085 if (p->options && p->options->addsipheaders && p->owner) {
9086 struct ast_channel *chan = p->owner; /* The owner channel */
9087 struct varshead *headp;
9089 ast_channel_lock(chan);
9091 headp = &chan->varshead;
9093 if (!headp)
9094 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
9095 else {
9096 const struct ast_var_t *current;
9097 AST_LIST_TRAVERSE(headp, current, entries) {
9098 /* SIPADDHEADER: Add SIP header to outgoing call */
9099 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
9100 char *content, *end;
9101 const char *header = ast_var_value(current);
9102 char *headdup = ast_strdupa(header);
9104 /* Strip of the starting " (if it's there) */
9105 if (*headdup == '"')
9106 headdup++;
9107 if ((content = strchr(headdup, ':'))) {
9108 *content++ = '\0';
9109 content = ast_skip_blanks(content); /* Skip white space */
9110 /* Strip the ending " (if it's there) */
9111 end = content + strlen(content) -1;
9112 if (*end == '"')
9113 *end = '\0';
9115 add_header(&req, headdup, content);
9116 if (sipdebug)
9117 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
9123 ast_channel_unlock(chan);
9125 if (sdp) {
9126 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
9127 ast_udptl_offered_from_local(p->udptl, 1);
9128 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
9129 add_t38_sdp(&req, p);
9130 } else if (p->rtp)
9131 add_sdp(&req, p, FALSE);
9132 } else {
9133 if (!p->notify_headers) {
9134 add_header_contentLength(&req, 0);
9138 if (!p->initreq.headers)
9139 initialize_initreq(p, &req);
9140 p->lastinvite = p->ocseq;
9141 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
9144 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
9145 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
9147 struct ast_str *tmp = ast_str_alloca(4000);
9148 char from[256], to[256];
9149 char *c, *mfrom, *mto;
9150 struct sip_request req;
9151 char hint[AST_MAX_EXTENSION];
9152 char *statestring = "terminated";
9153 const struct cfsubscription_types *subscriptiontype;
9154 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
9155 char *pidfstate = "--";
9156 char *pidfnote= "Ready";
9158 memset(from, 0, sizeof(from));
9159 memset(to, 0, sizeof(to));
9161 switch (state) {
9162 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
9163 statestring = (global_notifyringing) ? "early" : "confirmed";
9164 local_state = NOTIFY_INUSE;
9165 pidfstate = "busy";
9166 pidfnote = "Ringing";
9167 break;
9168 case AST_EXTENSION_RINGING:
9169 statestring = "early";
9170 local_state = NOTIFY_INUSE;
9171 pidfstate = "busy";
9172 pidfnote = "Ringing";
9173 break;
9174 case AST_EXTENSION_INUSE:
9175 statestring = "confirmed";
9176 local_state = NOTIFY_INUSE;
9177 pidfstate = "busy";
9178 pidfnote = "On the phone";
9179 break;
9180 case AST_EXTENSION_BUSY:
9181 statestring = "confirmed";
9182 local_state = NOTIFY_CLOSED;
9183 pidfstate = "busy";
9184 pidfnote = "On the phone";
9185 break;
9186 case AST_EXTENSION_UNAVAILABLE:
9187 statestring = "terminated";
9188 local_state = NOTIFY_CLOSED;
9189 pidfstate = "away";
9190 pidfnote = "Unavailable";
9191 break;
9192 case AST_EXTENSION_ONHOLD:
9193 statestring = "confirmed";
9194 local_state = NOTIFY_CLOSED;
9195 pidfstate = "busy";
9196 pidfnote = "On hold";
9197 break;
9198 case AST_EXTENSION_NOT_INUSE:
9199 default:
9200 /* Default setting */
9201 break;
9204 subscriptiontype = find_subscription_type(p->subscribed);
9206 /* Check which device/devices we are watching and if they are registered */
9207 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
9208 char *hint2 = hint, *individual_hint = NULL;
9209 int hint_count = 0, unavailable_count = 0;
9211 while ((individual_hint = strsep(&hint2, "&"))) {
9212 hint_count++;
9214 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
9215 unavailable_count++;
9218 /* If none of the hinted devices are registered, we will
9219 * override notification and show no availability.
9221 if (hint_count > 0 && hint_count == unavailable_count) {
9222 local_state = NOTIFY_CLOSED;
9223 pidfstate = "away";
9224 pidfnote = "Not online";
9228 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
9229 c = get_in_brackets(from);
9230 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
9231 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
9232 return -1;
9235 mfrom = remove_uri_parameters(c);
9237 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
9238 c = get_in_brackets(to);
9239 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
9240 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
9241 return -1;
9243 mto = remove_uri_parameters(c);
9245 reqprep(&req, p, SIP_NOTIFY, 0, 1);
9248 add_header(&req, "Event", subscriptiontype->event);
9249 add_header(&req, "Content-Type", subscriptiontype->mediatype);
9250 switch(state) {
9251 case AST_EXTENSION_DEACTIVATED:
9252 if (timeout)
9253 add_header(&req, "Subscription-State", "terminated;reason=timeout");
9254 else {
9255 add_header(&req, "Subscription-State", "terminated;reason=probation");
9256 add_header(&req, "Retry-After", "60");
9258 break;
9259 case AST_EXTENSION_REMOVED:
9260 add_header(&req, "Subscription-State", "terminated;reason=noresource");
9261 break;
9262 default:
9263 if (p->expiry)
9264 add_header(&req, "Subscription-State", "active");
9265 else /* Expired */
9266 add_header(&req, "Subscription-State", "terminated;reason=timeout");
9268 switch (p->subscribed) {
9269 case XPIDF_XML:
9270 case CPIM_PIDF_XML:
9271 ast_str_append(&tmp, 0,
9272 "<?xml version=\"1.0\"?>\n"
9273 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
9274 "<presence>\n");
9275 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
9276 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
9277 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
9278 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
9279 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
9280 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
9281 break;
9282 case PIDF_XML: /* Eyebeam supports this format */
9283 ast_str_append(&tmp, 0,
9284 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
9285 "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
9286 ast_str_append(&tmp, 0, "<pp:person><status>\n");
9287 if (pidfstate[0] != '-')
9288 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
9289 ast_str_append(&tmp, 0, "</status></pp:person>\n");
9290 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
9291 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
9292 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
9293 if (pidfstate[0] == 'b') /* Busy? Still open ... */
9294 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
9295 else
9296 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
9297 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
9298 break;
9299 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
9300 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
9301 ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
9302 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
9303 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
9304 else
9305 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
9306 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
9307 if (state == AST_EXTENSION_ONHOLD) {
9308 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
9309 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
9310 "</target>\n</local>\n", mto);
9312 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
9313 break;
9314 case NONE:
9315 default:
9316 break;
9319 add_header_contentLength(&req, tmp->used);
9320 add_line(&req, tmp->str);
9322 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
9324 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9327 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
9328 \note - Notification only works for registered peers with mailbox= definitions
9329 in sip.conf
9330 - We use the SIP Event package message-summary
9331 MIME type defaults to "application/simple-message-summary";
9333 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
9335 struct sip_request req;
9336 struct ast_str *out = ast_str_alloca(500);
9338 initreqprep(&req, p, SIP_NOTIFY);
9339 add_header(&req, "Event", "message-summary");
9340 add_header(&req, "Content-Type", default_notifymime);
9342 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
9343 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n",
9344 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr)));
9345 /* Cisco has a bug in the SIP stack where it can't accept the
9346 (0/0) notification. This can temporarily be disabled in
9347 sip.conf with the "buggymwi" option */
9348 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
9349 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
9351 if (p->subscribed) {
9352 if (p->expiry)
9353 add_header(&req, "Subscription-State", "active");
9354 else /* Expired */
9355 add_header(&req, "Subscription-State", "terminated;reason=timeout");
9358 add_header_contentLength(&req, out->used);
9359 add_line(&req, out->str);
9361 if (!p->initreq.headers)
9362 initialize_initreq(p, &req);
9363 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9366 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
9367 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
9369 struct sip_request req;
9370 char tmp[SIPBUFSIZE/2];
9372 reqprep(&req, p, SIP_NOTIFY, 0, 1);
9373 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
9374 add_header(&req, "Event", tmp);
9375 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
9376 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
9377 add_header(&req, "Allow", ALLOWED_METHODS);
9378 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
9380 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
9381 add_header_contentLength(&req, strlen(tmp));
9382 add_line(&req, tmp);
9384 if (!p->initreq.headers)
9385 initialize_initreq(p, &req);
9387 p->lastnoninvite = p->ocseq;
9389 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9392 /*! \brief Notify device with custom headers from sip_notify.conf */
9393 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
9394 struct sip_request req;
9395 struct ast_variable *var, *newvar;
9397 initreqprep(&req, p, SIP_NOTIFY);
9399 /* Copy notify vars and add headers */
9400 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
9401 add_header(&req, newvar->name, newvar->value);
9402 for (var = vars; var; var = var->next) {
9403 char buf[512];
9404 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
9405 ast_copy_string(buf, var->value, sizeof(buf));
9406 add_header(&req, var->name, ast_unescape_semicolon(buf));
9407 newvar->next = ast_variable_new(var->name, var->value, "");
9408 newvar = newvar->next;
9411 if (!p->initreq.headers) { /* Initialize first request before sending */
9412 initialize_initreq(p, &req);
9415 return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
9418 static int manager_sipnotify(struct mansession *s, const struct message *m)
9420 const char *channame = astman_get_header(m, "Channel");
9421 struct ast_variable *vars = astman_get_variables(m);
9422 struct sip_pvt *p;
9424 if (!channame) {
9425 astman_send_error(s, m, "SIPNotify requires a channel name");
9426 return -1;
9429 if (strncasecmp(channame, "sip/", 4) == 0) {
9430 channame += 4;
9433 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
9434 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
9435 return -1;
9438 if (create_addr(p, channame, NULL)) {
9439 /* Maybe they're not registered, etc. */
9440 dialog_unlink_all(p, TRUE, TRUE);
9441 dialog_unref(p, "unref dialog inside for loop" );
9442 /* sip_destroy(p); */
9443 astman_send_error(s, m, "Could not create address");
9444 return -1;
9447 /* Notify is outgoing call */
9448 ast_set_flag(&p->flags[0], SIP_OUTGOING);
9450 /* Recalculate our side, and recalculate Call ID */
9451 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
9452 build_via(p);
9453 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
9454 build_callid_pvt(p);
9455 ao2_t_link(dialogs, p, "Linking in new name");
9456 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
9457 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
9459 if (!transmit_notify_custom(p, vars)) {
9460 astman_send_ack(s, m, "Notify Sent");
9461 } else {
9462 astman_send_error(s, m, "Unable to send notify");
9464 ast_variables_destroy(vars);
9465 return 0;
9468 static char mandescr_sipnotify[] =
9469 "Description: Sends a SIP Notify event\n"
9470 "All parameters for this event must be specified in the body of this request\n"
9471 "via multiple Variable: name=value sequences.\n"
9472 "Variables: \n"
9473 " *Channel: <peername> Peer to receive the notify. Required.\n"
9474 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
9475 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9477 static const struct _map_x_s regstatestrings[] = {
9478 { REG_STATE_FAILED, "Failed" },
9479 { REG_STATE_UNREGISTERED, "Unregistered"},
9480 { REG_STATE_REGSENT, "Request Sent"},
9481 { REG_STATE_AUTHSENT, "Auth. Sent"},
9482 { REG_STATE_REGISTERED, "Registered"},
9483 { REG_STATE_REJECTED, "Rejected"},
9484 { REG_STATE_TIMEOUT, "Timeout"},
9485 { REG_STATE_NOAUTH, "No Authentication"},
9486 { -1, NULL } /* terminator */
9489 /*! \brief Convert registration state status to string */
9490 static const char *regstate2str(enum sipregistrystate regstate)
9492 return map_x_s(regstatestrings, regstate, "Unknown");
9495 /*! \brief Update registration with SIP Proxy.
9496 * Called from the scheduler when the previous registration expires,
9497 * so we don't have to cancel the pending event.
9498 * We assume the reference so the sip_registry is valid, since it
9499 * is stored in the scheduled event anyways.
9501 static int sip_reregister(const void *data)
9503 /* if we are here, we know that we need to reregister. */
9504 struct sip_registry *r= (struct sip_registry *) data;
9506 /* if we couldn't get a reference to the registry object, punt */
9507 if (!r)
9508 return 0;
9510 if (r->call && r->call->do_history)
9511 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
9512 /* Since registry's are only added/removed by the the monitor thread, this
9513 may be overkill to reference/dereference at all here */
9514 if (sipdebug)
9515 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
9517 r->expire = -1;
9518 __sip_do_register(r);
9519 registry_unref(r, "unreg the re-registered");
9520 return 0;
9523 /*! \brief Register with SIP proxy */
9524 static int __sip_do_register(struct sip_registry *r)
9526 int res;
9528 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
9529 return res;
9532 /*! \brief Registration timeout, register again
9533 * Registered as a timeout handler during transmit_register(),
9534 * to retransmit the packet if a reply does not come back.
9535 * This is called by the scheduler so the event is not pending anymore when
9536 * we are called.
9538 static int sip_reg_timeout(const void *data)
9541 /* if we are here, our registration timed out, so we'll just do it over */
9542 struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
9543 struct sip_pvt *p;
9544 int res;
9546 /* if we couldn't get a reference to the registry object, punt */
9547 if (!r)
9548 return 0;
9550 if (r->dnsmgr) {
9551 /* If the registration has timed out, maybe the IP changed. Force a refresh. */
9552 ast_dnsmgr_refresh(r->dnsmgr);
9555 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
9556 /* If the initial tranmission failed, we may not have an existing dialog,
9557 * so it is possible that r->call == NULL.
9558 * Otherwise destroy it, as we have a timeout so we don't want it.
9560 if (r->call) {
9561 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
9562 in the single SIP manager thread. */
9563 p = r->call;
9564 sip_pvt_lock(p);
9565 p->needdestroy = 1;
9566 /* Pretend to ACK anything just in case */
9567 __sip_pretend_ack(p);
9568 sip_pvt_unlock(p);
9570 /* decouple the two objects */
9571 /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
9572 if (p->registry)
9573 p->registry = registry_unref(p->registry, "p->registry unreffed");
9574 r->call = dialog_unref(r->call, "unrefing r->call");
9576 /* If we have a limit, stop registration and give up */
9577 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
9578 /* Ok, enough is enough. Don't try any more */
9579 /* We could add an external notification here...
9580 steal it from app_voicemail :-) */
9581 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
9582 r->regstate = REG_STATE_FAILED;
9583 } else {
9584 r->regstate = REG_STATE_UNREGISTERED;
9585 r->timeout = -1;
9586 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
9588 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
9589 registry_unref(r, "unreffing registry_unref r");
9590 return 0;
9593 /*! \brief Transmit register to SIP proxy or UA
9594 * auth = NULL on the initial registration (from sip_reregister())
9596 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
9598 struct sip_request req;
9599 char from[256];
9600 char to[256];
9601 char tmp[80];
9602 char addr[80];
9603 struct sip_pvt *p;
9604 int res;
9605 char *fromdomain;
9607 /* exit if we are already in process with this registrar ?*/
9608 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
9609 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
9610 return 0;
9613 if (r->dnsmgr == NULL) {
9614 char transport[MAXHOSTNAMELEN];
9615 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
9616 ast_dnsmgr_lookup(r->hostname, &r->us, &r->dnsmgr, global_srvlookup ? transport : NULL);
9619 if (r->call) { /* We have a registration */
9620 if (!auth) {
9621 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
9622 return 0;
9623 } else {
9624 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
9625 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
9626 ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
9628 } else {
9629 /* Build callid for registration if we haven't registered before */
9630 if (!r->callid_valid) {
9631 build_callid_registry(r, internip.sin_addr, default_fromdomain);
9632 r->callid_valid = TRUE;
9634 /* Allocate SIP dialog for registration */
9635 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
9636 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
9637 return 0;
9640 if (p->do_history)
9641 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
9643 p->outboundproxy = obproxy_get(p, NULL);
9645 /* Use port number specified if no SRV record was found */
9646 if (!r->us.sin_port && r->portno)
9647 r->us.sin_port = htons(r->portno);
9649 /* Find address to hostname */
9650 if (create_addr(p, r->hostname, &r->us)) {
9651 /* we have what we hope is a temporary network error,
9652 * probably DNS. We need to reschedule a registration try */
9653 dialog_unlink_all(p, TRUE, TRUE);
9654 p = dialog_unref(p, "unref dialog after unlink_all");
9655 if (r->timeout > -1) {
9656 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
9657 registry_unref(_data, "del for REPLACE of registry ptr"),
9658 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
9659 registry_addref(r,"add for REPLACE registry ptr"));
9660 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
9661 } else {
9662 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
9663 ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
9665 r->regattempts++;
9666 return 0;
9669 /* Copy back Call-ID in case create_addr changed it */
9670 ast_string_field_set(r, callid, p->callid);
9671 if (!r->dnsmgr && r->portno) {
9672 p->sa.sin_port = htons(r->portno);
9673 p->recv.sin_port = htons(r->portno);
9674 } else { /* Set registry port to the port set from the peer definition/srv or default */
9675 r->portno = ntohs(p->sa.sin_port);
9677 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
9678 r->call = dialog_ref(p, "copying dialog into registry r->call"); /* Save pointer to SIP dialog */
9679 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
9680 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
9681 ast_string_field_set(p, peersecret, r->secret);
9682 if (!ast_strlen_zero(r->md5secret))
9683 ast_string_field_set(p, peermd5secret, r->md5secret);
9684 /* User name in this realm
9685 - if authuser is set, use that, otherwise use username */
9686 if (!ast_strlen_zero(r->authuser)) {
9687 ast_string_field_set(p, peername, r->authuser);
9688 ast_string_field_set(p, authname, r->authuser);
9689 } else if (!ast_strlen_zero(r->username)) {
9690 ast_string_field_set(p, peername, r->username);
9691 ast_string_field_set(p, authname, r->username);
9692 ast_string_field_set(p, fromuser, r->username);
9694 if (!ast_strlen_zero(r->username))
9695 ast_string_field_set(p, username, r->username);
9696 /* Save extension in packet */
9697 if (!ast_strlen_zero(r->callback))
9698 ast_string_field_set(p, exten, r->callback);
9700 /* Set transport and port so the correct contact is built */
9701 p->socket.type = r->transport;
9702 p->socket.port = htons(r->portno);
9705 check which address we should use in our contact header
9706 based on whether the remote host is on the external or
9707 internal network so we can register through nat
9709 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
9710 build_contact(p);
9713 /* set up a timeout */
9714 if (auth == NULL) {
9715 if (r->timeout > -1)
9716 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
9717 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
9718 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
9719 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
9720 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
9721 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
9724 if ((fromdomain = strchr(r->username, '@'))) {
9725 /* We have a domain in the username for registration */
9726 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
9727 if (!ast_strlen_zero(p->theirtag))
9728 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
9729 else
9730 snprintf(to, sizeof(to), "<sip:%s>", r->username);
9732 /* If the registration username contains '@', then the domain should be used as
9733 the equivalent of "fromdomain" for the registration */
9734 if (ast_strlen_zero(p->fromdomain)) {
9735 ast_string_field_set(p, fromdomain, ++fromdomain);
9737 } else {
9738 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
9739 if (!ast_strlen_zero(p->theirtag))
9740 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
9741 else
9742 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
9745 /* Fromdomain is what we are registering to, regardless of actual
9746 host name from SRV */
9747 if (!ast_strlen_zero(p->fromdomain)) {
9748 if (r->portno && r->portno != STANDARD_SIP_PORT)
9749 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
9750 else
9751 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
9752 } else {
9753 if (r->portno && r->portno != STANDARD_SIP_PORT)
9754 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
9755 else
9756 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
9758 ast_string_field_set(p, uri, addr);
9760 p->branch ^= ast_random();
9762 init_req(&req, sipmethod, addr);
9764 /* Add to CSEQ */
9765 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
9766 p->ocseq = r->ocseq;
9768 build_via(p);
9769 add_header(&req, "Via", p->via);
9770 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
9771 add_header(&req, "From", from);
9772 add_header(&req, "To", to);
9773 add_header(&req, "Call-ID", p->callid);
9774 add_header(&req, "CSeq", tmp);
9775 if (!ast_strlen_zero(global_useragent))
9776 add_header(&req, "User-Agent", global_useragent);
9779 if (auth) /* Add auth header */
9780 add_header(&req, authheader, auth);
9781 else if (!ast_strlen_zero(r->nonce)) {
9782 char digest[1024];
9784 /* We have auth data to reuse, build a digest header.
9785 * Note, this is not always useful because some parties do not
9786 * like nonces to be reused (for good reasons!) so they will
9787 * challenge us anyways.
9789 if (sipdebug)
9790 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
9791 ast_string_field_set(p, realm, r->realm);
9792 ast_string_field_set(p, nonce, r->nonce);
9793 ast_string_field_set(p, domain, r->domain);
9794 ast_string_field_set(p, opaque, r->opaque);
9795 ast_string_field_set(p, qop, r->qop);
9796 p->noncecount = ++r->noncecount;
9798 memset(digest, 0, sizeof(digest));
9799 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
9800 add_header(&req, "Authorization", digest);
9801 else
9802 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
9806 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
9807 add_header(&req, "Expires", tmp);
9808 add_header(&req, "Contact", p->our_contact);
9809 add_header_contentLength(&req, 0);
9811 initialize_initreq(p, &req);
9812 if (sip_debug_test_pvt(p)) {
9813 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
9815 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
9816 r->regattempts++; /* Another attempt */
9817 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
9818 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
9819 dialog_unref(p, "p is finished here at the end of transmit_register");
9820 return res;
9823 /*! \brief Transmit text with SIP MESSAGE method */
9824 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
9826 struct sip_request req;
9828 reqprep(&req, p, SIP_MESSAGE, 0, 1);
9829 add_text(&req, text);
9830 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9833 /*! \brief Allocate SIP refer structure */
9834 static int sip_refer_allocate(struct sip_pvt *p)
9836 p->refer = ast_calloc(1, sizeof(struct sip_refer));
9837 return p->refer ? 1 : 0;
9840 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
9841 \note this is currently broken as we have no way of telling the dialplan
9842 engine whether a transfer succeeds or fails.
9843 \todo Fix the transfer() dialplan function so that a transfer may fail
9845 static int transmit_refer(struct sip_pvt *p, const char *dest)
9847 struct sip_request req = {
9848 .headers = 0,
9850 char from[256];
9851 const char *of;
9852 char *c;
9853 char referto[256];
9854 char *ttag, *ftag;
9855 char *theirtag = ast_strdupa(p->theirtag);
9857 if (sipdebug)
9858 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
9860 /* Are we transfering an inbound or outbound call ? */
9861 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
9862 of = get_header(&p->initreq, "To");
9863 ttag = theirtag;
9864 ftag = p->tag;
9865 } else {
9866 of = get_header(&p->initreq, "From");
9867 ftag = theirtag;
9868 ttag = p->tag;
9871 ast_copy_string(from, of, sizeof(from));
9872 of = get_in_brackets(from);
9873 ast_string_field_set(p, from, of);
9874 if (!strncasecmp(of, "sip:", 4))
9875 of += 4;
9876 else if (!strncasecmp(of, "sips:", 5))
9877 of += 5;
9878 else
9879 ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
9880 /* Get just the username part */
9881 if ((c = strchr(dest, '@')))
9882 c = NULL;
9883 else if ((c = strchr(of, '@')))
9884 *c++ = '\0';
9885 if (c)
9886 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
9887 else
9888 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
9890 /* save in case we get 407 challenge */
9891 sip_refer_allocate(p);
9892 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
9893 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
9894 p->refer->status = REFER_SENT; /* Set refer status */
9896 reqprep(&req, p, SIP_REFER, 0, 1);
9898 add_header(&req, "Refer-To", referto);
9899 add_header(&req, "Allow", ALLOWED_METHODS);
9900 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
9901 if (!ast_strlen_zero(p->our_contact))
9902 add_header(&req, "Referred-By", p->our_contact);
9904 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9906 /* We should propably wait for a NOTIFY here until we ack the transfer */
9907 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
9909 /*! \todo In theory, we should hang around and wait for a reply, before
9910 returning to the dial plan here. Don't know really how that would
9911 affect the transfer() app or the pbx, but, well, to make this
9912 useful we should have a STATUS code on transfer().
9917 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
9918 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
9920 struct sip_request req;
9922 reqprep(&req, p, SIP_INFO, 0, 1);
9923 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
9924 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9927 /*! \brief Send SIP INFO with video update request */
9928 static int transmit_info_with_vidupdate(struct sip_pvt *p)
9930 struct sip_request req;
9932 reqprep(&req, p, SIP_INFO, 0, 1);
9933 add_vidupdate(&req);
9934 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9937 /*! \brief Transmit generic SIP request
9938 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
9940 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
9942 struct sip_request resp;
9944 if (sipmethod == SIP_ACK)
9945 p->invitestate = INV_CONFIRMED;
9947 reqprep(&resp, p, sipmethod, seqno, newbranch);
9948 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
9949 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
9951 add_header_contentLength(&resp, 0);
9952 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
9955 /*! \brief return the request and response heade for a 401 or 407 code */
9956 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
9958 if (code == WWW_AUTH) { /* 401 */
9959 *header = "WWW-Authenticate";
9960 *respheader = "Authorization";
9961 } else if (code == PROXY_AUTH) { /* 407 */
9962 *header = "Proxy-Authenticate";
9963 *respheader = "Proxy-Authorization";
9964 } else {
9965 ast_verbose("-- wrong response code %d\n", code);
9966 *header = *respheader = "Invalid";
9970 /*! \brief Transmit SIP request, auth added */
9971 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
9973 struct sip_request resp;
9975 reqprep(&resp, p, sipmethod, seqno, newbranch);
9976 if (!ast_strlen_zero(p->realm)) {
9977 char digest[1024];
9979 memset(digest, 0, sizeof(digest));
9980 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
9981 char *dummy, *response;
9982 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
9983 auth_headers(code, &dummy, &response);
9984 add_header(&resp, response, digest);
9985 } else
9986 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
9988 /* If we are hanging up and know a cause for that, send it in clear text to make
9989 debugging easier. */
9990 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
9991 char buf[10];
9993 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
9994 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
9995 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
9998 add_header_contentLength(&resp, 0);
9999 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
10002 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
10003 static void destroy_association(struct sip_peer *peer)
10005 int realtimeregs = ast_check_realtime("sipregs");
10006 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
10008 if (!sip_cfg.ignore_regexpire) {
10009 if (peer->rt_fromcontact)
10010 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", SENTINEL);
10011 else
10012 ast_db_del("SIP/Registry", peer->name);
10016 /*! \brief Expire registration of SIP peer */
10017 static int expire_register(const void *data)
10019 struct sip_peer *peer = (struct sip_peer *)data;
10021 if (!peer) /* Hmmm. We have no peer. Weird. */
10022 return 0;
10024 peer->expire = -1;
10025 memset(&peer->addr, 0, sizeof(peer->addr));
10027 destroy_association(peer); /* remove registration data from storage */
10029 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
10030 register_peer_exten(peer, FALSE); /* Remove regexten */
10031 ast_device_state_changed("SIP/%s", peer->name);
10033 /* Do we need to release this peer from memory?
10034 Only for realtime peers and autocreated peers
10036 if (peer->is_realtime)
10037 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
10039 if (peer->selfdestruct ||
10040 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
10041 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
10042 if (peer->addr.sin_addr.s_addr) {
10043 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
10048 return 0;
10051 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
10052 static int sip_poke_peer_s(const void *data)
10054 struct sip_peer *peer = (struct sip_peer *)data;
10056 peer->pokeexpire = -1;
10057 sip_poke_peer(peer, 0);
10058 return 0;
10061 /*! \brief Get registration details from Asterisk DB */
10062 static void reg_source_db(struct sip_peer *peer)
10064 char data[256];
10065 struct in_addr in;
10066 int expiry;
10067 int port;
10068 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
10070 if (peer->rt_fromcontact)
10071 return;
10072 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
10073 return;
10075 scan = data;
10076 addr = strsep(&scan, ":");
10077 port_str = strsep(&scan, ":");
10078 expiry_str = strsep(&scan, ":");
10079 username = strsep(&scan, ":");
10080 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
10082 if (!inet_aton(addr, &in))
10083 return;
10085 if (port_str)
10086 port = atoi(port_str);
10087 else
10088 return;
10090 if (expiry_str)
10091 expiry = atoi(expiry_str);
10092 else
10093 return;
10095 if (username)
10096 ast_copy_string(peer->username, username, sizeof(peer->username));
10097 if (contact)
10098 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
10100 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
10101 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
10103 memset(&peer->addr, 0, sizeof(peer->addr));
10104 peer->addr.sin_family = AF_INET;
10105 peer->addr.sin_addr = in;
10106 peer->addr.sin_port = htons(port);
10107 if (sipsock < 0) {
10108 /* SIP isn't up yet, so schedule a poke only, pretty soon */
10109 AST_SCHED_REPLACE(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
10110 } else {
10111 sip_poke_peer(peer, 0);
10113 AST_SCHED_REPLACE(peer->expire, sched, (expiry + 10) * 1000, expire_register, peer);
10114 register_peer_exten(peer, TRUE);
10117 /*! \brief Save contact header for 200 OK on INVITE */
10118 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
10120 char contact[SIPBUFSIZE];
10121 char *c;
10123 /* Look for brackets */
10124 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10125 c = get_in_brackets(contact);
10127 /* Save full contact to call pvt for later bye or re-invite */
10128 ast_string_field_set(pvt, fullcontact, c);
10130 /* Save URI for later ACKs, BYE or RE-invites */
10131 ast_string_field_set(pvt, okcontacturi, c);
10133 /* We should return false for URI:s we can't handle,
10134 like tel:, mailto:,ldap: etc */
10135 return TRUE;
10138 /*! \brief Change the other partys IP address based on given contact */
10139 static int set_address_from_contact(struct sip_pvt *pvt)
10141 struct hostent *hp;
10142 struct ast_hostent ahp;
10143 int port;
10144 char *host, *pt;
10145 char contact_buf[256];
10146 char contact2_buf[256];
10147 char *contact, *contact2;
10149 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
10150 /* NAT: Don't trust the contact field. Just use what they came to us
10151 with. */
10152 pvt->sa = pvt->recv;
10153 return 0;
10156 /* Work on a copy */
10157 ast_copy_string(contact_buf, pvt->fullcontact, sizeof(contact_buf));
10158 ast_copy_string(contact2_buf, pvt->fullcontact, sizeof(contact2_buf));
10159 contact = contact_buf;
10160 contact2 = contact2_buf;
10162 /* We have only the part in <brackets> here so we just need to parse a SIP URI.*/
10164 if (pvt->socket.type == SIP_TRANSPORT_TLS) {
10165 if (parse_uri(contact, "sips:", &contact, NULL, &host, &pt, NULL)) {
10166 if (parse_uri(contact2, "sip:", &contact, NULL, &host, &pt, NULL))
10167 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10169 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10170 } else {
10171 if (parse_uri(contact, "sip:", &contact, NULL, &host, &pt, NULL))
10172 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10173 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10176 if (sip_debug_test_pvt(pvt)) {
10177 ast_verbose("--- set_address_from_contact host '%s'\n", host);
10180 /* XXX This could block for a long time XXX */
10181 /* We should only do this if it's a name, not an IP */
10182 hp = ast_gethostbyname(host, &ahp);
10183 if (!hp) {
10184 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
10185 return -1;
10187 pvt->sa.sin_family = AF_INET;
10188 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
10189 pvt->sa.sin_port = htons(port);
10191 return 0;
10195 /*! \brief Parse contact header and save registration (peer registration) */
10196 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
10198 char contact[SIPBUFSIZE];
10199 char data[SIPBUFSIZE];
10200 const char *expires = get_header(req, "Expires");
10201 int expiry = atoi(expires);
10202 char *curi, *host, *pt, *curi2;
10203 int port;
10204 const char *useragent;
10205 struct hostent *hp;
10206 struct ast_hostent ahp;
10207 struct sockaddr_in oldsin;
10209 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10211 if (ast_strlen_zero(expires)) { /* No expires header, try look in Contact: */
10212 char *s = strcasestr(contact, ";expires=");
10213 if (s) {
10214 expires = strsep(&s, ";"); /* trim ; and beyond */
10215 if (sscanf(expires + 9, "%d", &expiry) != 1)
10216 expiry = default_expiry;
10217 } else {
10218 /* Nothing has been specified */
10219 expiry = default_expiry;
10223 if (peer->socket.type == req->socket.type)
10224 copy_socket_data(&peer->socket, &req->socket);
10225 copy_socket_data(&pvt->socket, &req->socket);
10227 /* Look for brackets */
10228 curi = contact;
10229 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
10230 strsep(&curi, ";"); /* This is Header options, not URI options */
10231 curi = get_in_brackets(contact);
10232 curi2 = ast_strdupa(curi);
10234 /* if they did not specify Contact: or Expires:, they are querying
10235 what we currently have stored as their contact address, so return
10238 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
10239 /* If we have an active registration, tell them when the registration is going to expire */
10240 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
10241 pvt->expiry = ast_sched_when(sched, peer->expire);
10242 return PARSE_REGISTER_QUERY;
10243 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
10244 /* This means remove all registrations and return OK */
10245 memset(&peer->addr, 0, sizeof(peer->addr));
10246 AST_SCHED_DEL(sched, peer->expire);
10248 destroy_association(peer);
10250 register_peer_exten(peer, FALSE); /* Remove extension from regexten= setting in sip.conf */
10251 peer->fullcontact[0] = '\0';
10252 peer->useragent[0] = '\0';
10253 peer->sipoptions = 0;
10254 peer->lastms = 0;
10256 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
10257 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
10258 return PARSE_REGISTER_UPDATE;
10261 /* Store whatever we got as a contact from the client */
10262 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
10264 /* For the 200 OK, we should use the received contact */
10265 ast_string_field_build(pvt, our_contact, "<%s>", curi);
10267 /* Make sure it's a SIP URL */
10268 if (pvt->socket.type == SIP_TRANSPORT_TLS) {
10269 if (parse_uri(curi, "sips:", &curi, NULL, &host, &pt, NULL)) {
10270 if (parse_uri(curi2, "sip:", &curi, NULL, &host, &pt, NULL))
10271 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10273 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10274 } else {
10275 if (parse_uri(curi, "sip:", &curi, NULL, &host, &pt, NULL))
10276 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10277 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10280 oldsin = peer->addr;
10281 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
10282 /* XXX This could block for a long time XXX */
10283 hp = ast_gethostbyname(host, &ahp);
10284 if (!hp) {
10285 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
10286 return PARSE_REGISTER_FAILED;
10288 peer->addr.sin_family = AF_INET;
10289 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
10290 peer->addr.sin_port = htons(port);
10291 } else {
10292 /* Don't trust the contact field. Just use what they came to us
10293 with */
10294 peer->addr = pvt->recv;
10297 /* Save SIP options profile */
10298 peer->sipoptions = pvt->sipoptions;
10300 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
10301 ast_copy_string(peer->username, curi, sizeof(peer->username));
10303 AST_SCHED_DEL(sched, peer->expire);
10304 if (expiry > max_expiry)
10305 expiry = max_expiry;
10306 if (expiry < min_expiry)
10307 expiry = min_expiry;
10308 peer->expire = peer->is_realtime ? -1 :
10309 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
10310 pvt->expiry = expiry;
10311 snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry, peer->username, peer->fullcontact);
10312 /* Saving TCP connections is useless, we won't be able to reconnect
10313 XXX WHY???? XXX
10314 \todo check this
10316 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
10317 ast_db_put("SIP/Registry", peer->name, data);
10318 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
10320 /* Is this a new IP address for us? */
10321 if (inaddrcmp(&peer->addr, &oldsin)) {
10322 sip_poke_peer(peer, 0);
10323 ast_verb(3, "Registered SIP '%s' at %s port %d expires %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry);
10324 register_peer_exten(peer, TRUE);
10327 /* Save User agent */
10328 useragent = get_header(req, "User-Agent");
10329 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
10330 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
10331 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
10333 return PARSE_REGISTER_UPDATE;
10336 /*! \brief Remove route from route list */
10337 static void free_old_route(struct sip_route *route)
10339 struct sip_route *next;
10341 while (route) {
10342 next = route->next;
10343 ast_free(route);
10344 route = next;
10348 /*! \brief List all routes - mostly for debugging */
10349 static void list_route(struct sip_route *route)
10351 if (!route)
10352 ast_verbose("list_route: no route\n");
10353 else {
10354 for (;route; route = route->next)
10355 ast_verbose("list_route: hop: <%s>\n", route->hop);
10359 /*! \brief Build route list from Record-Route header */
10360 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
10362 struct sip_route *thishop, *head, *tail;
10363 int start = 0;
10364 int len;
10365 const char *rr, *contact, *c;
10367 /* Once a persistant route is set, don't fool with it */
10368 if (p->route && p->route_persistant) {
10369 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
10370 return;
10373 if (p->route) {
10374 free_old_route(p->route);
10375 p->route = NULL;
10378 /* We only want to create the route set the first time this is called */
10379 p->route_persistant = 1;
10381 /* Build a tailq, then assign it to p->route when done.
10382 * If backwards, we add entries from the head so they end up
10383 * in reverse order. However, we do need to maintain a correct
10384 * tail pointer because the contact is always at the end.
10386 head = NULL;
10387 tail = head;
10388 /* 1st we pass through all the hops in any Record-Route headers */
10389 for (;;) {
10390 /* Each Record-Route header */
10391 rr = __get_header(req, "Record-Route", &start);
10392 if (*rr == '\0')
10393 break;
10394 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
10395 ++rr;
10396 len = strcspn(rr, ">") + 1;
10397 /* Make a struct route */
10398 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
10399 /* ast_calloc is not needed because all fields are initialized in this block */
10400 ast_copy_string(thishop->hop, rr, len);
10401 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
10402 /* Link in */
10403 if (backwards) {
10404 /* Link in at head so they end up in reverse order */
10405 thishop->next = head;
10406 head = thishop;
10407 /* If this was the first then it'll be the tail */
10408 if (!tail)
10409 tail = thishop;
10410 } else {
10411 thishop->next = NULL;
10412 /* Link in at the end */
10413 if (tail)
10414 tail->next = thishop;
10415 else
10416 head = thishop;
10417 tail = thishop;
10423 /* Only append the contact if we are dealing with a strict router */
10424 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
10425 /* 2nd append the Contact: if there is one */
10426 /* Can be multiple Contact headers, comma separated values - we just take the first */
10427 contact = get_header(req, "Contact");
10428 if (!ast_strlen_zero(contact)) {
10429 ast_debug(2, "build_route: Contact hop: %s\n", contact);
10430 /* Look for <: delimited address */
10431 c = strchr(contact, '<');
10432 if (c) {
10433 /* Take to > */
10434 ++c;
10435 len = strcspn(c, ">") + 1;
10436 } else {
10437 /* No <> - just take the lot */
10438 c = contact;
10439 len = strlen(contact) + 1;
10441 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
10442 /* ast_calloc is not needed because all fields are initialized in this block */
10443 ast_copy_string(thishop->hop, c, len);
10444 thishop->next = NULL;
10445 /* Goes at the end */
10446 if (tail)
10447 tail->next = thishop;
10448 else
10449 head = thishop;
10454 /* Store as new route */
10455 p->route = head;
10457 /* For debugging dump what we ended up with */
10458 if (sip_debug_test_pvt(p))
10459 list_route(p->route);
10462 AST_THREADSTORAGE(check_auth_buf);
10463 #define CHECK_AUTH_BUF_INITLEN 256
10465 /*! \brief Check user authorization from peer definition
10466 Some actions, like REGISTER and INVITEs from peers require
10467 authentication (if peer have secret set)
10468 \return 0 on success, non-zero on error
10470 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
10471 const char *secret, const char *md5secret, int sipmethod,
10472 char *uri, enum xmittype reliable, int ignore)
10474 const char *response;
10475 char *reqheader, *respheader;
10476 const char *authtoken;
10477 char a1_hash[256];
10478 char resp_hash[256]="";
10479 char *c;
10480 int wrongnonce = FALSE;
10481 int good_response;
10482 const char *usednonce = p->randdata;
10483 struct ast_str *buf;
10484 int res;
10486 /* table of recognised keywords, and their value in the digest */
10487 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
10488 struct x {
10489 const char *key;
10490 const char *s;
10491 } *i, keys[] = {
10492 [K_RESP] = { "response=", "" },
10493 [K_URI] = { "uri=", "" },
10494 [K_USER] = { "username=", "" },
10495 [K_NONCE] = { "nonce=", "" },
10496 [K_LAST] = { NULL, NULL}
10499 /* Always OK if no secret */
10500 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
10501 return AUTH_SUCCESSFUL;
10503 /* Always auth with WWW-auth since we're NOT a proxy */
10504 /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
10505 response = "401 Unauthorized";
10508 * Note the apparent swap of arguments below, compared to other
10509 * usages of auth_headers().
10511 auth_headers(WWW_AUTH, &respheader, &reqheader);
10513 authtoken = get_header(req, reqheader);
10514 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
10515 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
10516 information */
10517 if (!reliable) {
10518 /* Resend message if this was NOT a reliable delivery. Otherwise the
10519 retransmission should get it */
10520 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
10521 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
10522 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10524 return AUTH_CHALLENGE_SENT;
10525 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
10526 /* We have no auth, so issue challenge and request authentication */
10527 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
10528 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
10529 /* Schedule auto destroy in 32 seconds */
10530 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10531 return AUTH_CHALLENGE_SENT;
10534 /* --- We have auth, so check it */
10536 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
10537 an example in the spec of just what it is you're doing a hash on. */
10539 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
10540 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
10542 /* Make a copy of the response and parse it */
10543 res = ast_str_set(&buf, 0, "%s", authtoken);
10545 if (res == AST_DYNSTR_BUILD_FAILED)
10546 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
10548 c = buf->str;
10550 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
10551 for (i = keys; i->key != NULL; i++) {
10552 const char *separator = ","; /* default */
10554 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
10555 continue;
10556 /* Found. Skip keyword, take text in quotes or up to the separator. */
10557 c += strlen(i->key);
10558 if (*c == '"') { /* in quotes. Skip first and look for last */
10559 c++;
10560 separator = "\"";
10562 i->s = c;
10563 strsep(&c, separator);
10564 break;
10566 if (i->key == NULL) /* not found, jump after space or comma */
10567 strsep(&c, " ,");
10570 /* Verify that digest username matches the username we auth as */
10571 if (strcmp(username, keys[K_USER].s)) {
10572 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
10573 username, keys[K_USER].s);
10574 /* Oops, we're trying something here */
10575 return AUTH_USERNAME_MISMATCH;
10578 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
10579 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
10580 wrongnonce = TRUE;
10581 usednonce = keys[K_NONCE].s;
10584 if (!ast_strlen_zero(md5secret))
10585 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
10586 else {
10587 char a1[256];
10588 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
10589 ast_md5_hash(a1_hash, a1);
10592 /* compute the expected response to compare with what we received */
10594 char a2[256];
10595 char a2_hash[256];
10596 char resp[256];
10598 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
10599 S_OR(keys[K_URI].s, uri));
10600 ast_md5_hash(a2_hash, a2);
10601 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
10602 ast_md5_hash(resp_hash, resp);
10605 good_response = keys[K_RESP].s &&
10606 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
10607 if (wrongnonce) {
10608 if (good_response) {
10609 if (sipdebug)
10610 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
10611 /* We got working auth token, based on stale nonce . */
10612 ast_string_field_build(p, randdata, "%08lx", ast_random());
10613 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
10614 } else {
10615 /* Everything was wrong, so give the device one more try with a new challenge */
10616 if (!req->ignore) {
10617 if (sipdebug)
10618 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
10619 ast_string_field_build(p, randdata, "%08lx", ast_random());
10620 } else {
10621 if (sipdebug)
10622 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
10624 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
10627 /* Schedule auto destroy in 32 seconds */
10628 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10629 return AUTH_CHALLENGE_SENT;
10631 if (good_response) {
10632 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
10633 return AUTH_SUCCESSFUL;
10636 /* Ok, we have a bad username/secret pair */
10637 /* Tell the UAS not to re-send this authentication data, because
10638 it will continue to fail
10641 return AUTH_SECRET_FAILED;
10644 /*! \brief Change onhold state of a peer using a pvt structure */
10645 static void sip_peer_hold(struct sip_pvt *p, int hold)
10647 struct sip_peer *peer = find_peer(p->peername, NULL, 1, TRUE);
10649 if (!peer)
10650 return;
10652 /* If they put someone on hold, increment the value... otherwise decrement it */
10653 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
10655 /* Request device state update */
10656 ast_device_state_changed("SIP/%s", peer->name);
10657 unref_peer(peer, "sip_peer_hold: from find_peer operation");
10659 return;
10662 /*! \brief Receive MWI events that we have subscribed to */
10663 static void mwi_event_cb(const struct ast_event *event, void *userdata)
10665 struct sip_peer *peer = userdata;
10667 ao2_lock(peer);
10668 sip_send_mwi_to_peer(peer, event, 0);
10669 ao2_unlock(peer);
10672 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
10673 \note If you add an "hint" priority to the extension in the dial plan,
10674 you will get notifications on device state changes */
10675 static int cb_extensionstate(char *context, char* exten, int state, void *data)
10677 struct sip_pvt *p = data;
10679 sip_pvt_lock(p);
10681 switch(state) {
10682 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
10683 case AST_EXTENSION_REMOVED: /* Extension is gone */
10684 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
10685 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
10686 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
10687 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
10688 p->stateid = -1;
10689 p->subscribed = NONE;
10690 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
10691 break;
10692 default: /* Tell user */
10693 p->laststate = state;
10694 break;
10696 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
10697 if (!p->pendinginvite) {
10698 transmit_state_notify(p, state, 1, FALSE);
10699 } else {
10700 /* We already have a NOTIFY sent that is not answered. Queue the state up.
10701 if many state changes happen meanwhile, we will only send a notification of the last one */
10702 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
10705 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
10706 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
10708 sip_pvt_unlock(p);
10710 return 0;
10713 /*! \brief Send a fake 401 Unauthorized response when the administrator
10714 wants to hide the names of local devices from fishers
10716 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
10718 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
10719 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
10723 * Terminate the uri at the first ';' or space.
10724 * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
10725 * but don't do it for the time being. Remember the uri format is:
10726 *\verbatim
10728 * sip:user:password@host:port;uri-parameters?headers
10729 * sips:user:password@host:port;uri-parameters?headers
10731 *\endverbatim
10733 static char *terminate_uri(char *uri)
10735 char *t = uri;
10736 while (*t && *t > ' ' && *t != ';')
10737 t++;
10738 *t = '\0';
10739 return uri;
10742 /*! \brief Verify registration of user
10743 - Registration is done in several steps, first a REGISTER without auth
10744 to get a challenge (nonce) then a second one with auth
10745 - Registration requests are only matched with peers that are marked as "dynamic"
10747 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
10748 struct sip_request *req, char *uri)
10750 enum check_auth_result res = AUTH_NOT_FOUND;
10751 struct sip_peer *peer;
10752 char tmp[256];
10753 char *name, *c;
10754 char *domain;
10756 terminate_uri(uri); /* warning, overwrite the string */
10758 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
10759 if (pedanticsipchecking)
10760 ast_uri_decode(tmp);
10762 c = get_in_brackets(tmp);
10763 c = remove_uri_parameters(c);
10765 if (!strncasecmp(c, "sip:", 4)) {
10766 name = c + 4;
10767 } else if (!strncasecmp(c, "sips:", 5)) {
10768 name = c + 5;
10769 } else {
10770 name = c;
10771 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
10774 /* XXX here too we interpret a missing @domain as a name-only
10775 * URI, whereas the RFC says this is a domain-only uri.
10777 /* Strip off the domain name */
10778 if ((c = strchr(name, '@'))) {
10779 *c++ = '\0';
10780 domain = c;
10781 if ((c = strchr(domain, ':'))) /* Remove :port */
10782 *c = '\0';
10783 if (!AST_LIST_EMPTY(&domain_list)) {
10784 if (!check_sip_domain(domain, NULL, 0)) {
10785 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
10786 return AUTH_UNKNOWN_DOMAIN;
10790 c = strchr(name, ';'); /* Remove any Username parameters */
10791 if (c)
10792 *c = '\0';
10794 ast_string_field_set(p, exten, name);
10795 build_contact(p);
10796 peer = find_peer(name, NULL, TRUE, TRUE);
10797 if (!(peer && ast_apply_ha(peer->ha, sin))) {
10798 /* Peer fails ACL check */
10799 if (peer) {
10800 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
10801 peer = NULL;
10802 res = AUTH_ACL_FAILED;
10803 } else
10804 res = AUTH_NOT_FOUND;
10807 if (peer) {
10808 /* Set Frame packetization */
10809 if (p->rtp) {
10810 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
10811 p->autoframing = peer->autoframing;
10813 if (!peer->host_dynamic) {
10814 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
10815 res = AUTH_PEER_NOT_DYNAMIC;
10816 } else {
10817 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
10818 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
10819 transmit_response(p, "100 Trying", req);
10820 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
10821 if (sip_cancel_destroy(p))
10822 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
10824 /* We have a successful registration attempt with proper authentication,
10825 now, update the peer */
10826 switch (parse_register_contact(p, peer, req)) {
10827 case PARSE_REGISTER_FAILED:
10828 ast_log(LOG_WARNING, "Failed to parse contact info\n");
10829 transmit_response_with_date(p, "400 Bad Request", req);
10830 peer->lastmsgssent = -1;
10831 res = 0;
10832 break;
10833 case PARSE_REGISTER_QUERY:
10834 transmit_response_with_date(p, "200 OK", req);
10835 peer->lastmsgssent = -1;
10836 res = 0;
10837 break;
10838 case PARSE_REGISTER_UPDATE:
10839 update_peer(peer, p->expiry);
10840 /* Say OK and ask subsystem to retransmit msg counter */
10841 transmit_response_with_date(p, "200 OK", req);
10842 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
10843 peer->lastmsgssent = -1;
10844 res = 0;
10845 break;
10848 if (peer->socket.type != req->socket.type ) {
10849 if (!(peer->transports & req->socket.type)) {
10850 ast_log(LOG_ERROR,
10851 "peer '%s' has contacted us over %s, but we only accept '%s' for this peer! ending call.\n",
10852 peer->name, get_transport(req->socket.type), get_transport_list(peer)
10855 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
10856 transmit_response_with_date(p, "403 Forbidden", req);
10857 res = AUTH_BAD_TRANSPORT;
10858 } else if (peer->socket.type & SIP_TRANSPORT_TLS) {
10859 ast_log(LOG_WARNING,
10860 "peer '%s' HAS STOPPED USING TLS in favor of '%s' (but this was allowed in sip.conf)!\n",
10861 peer->name, get_transport(req->socket.type)
10863 } else {
10864 ast_log(LOG_DEBUG,
10865 "peer '%s' has contacted us over %s even though we prefer %s.\n",
10866 peer->name, get_transport(req->socket.type), get_transport(peer->socket.type)
10873 if (!peer && autocreatepeer) {
10874 /* Create peer if we have autocreate mode enabled */
10875 peer = temp_peer(name);
10876 if (peer) {
10877 ao2_t_link(peers, peer, "link peer into peer table");
10878 if (peer->addr.sin_addr.s_addr) {
10879 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
10882 if (sip_cancel_destroy(p))
10883 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
10884 switch (parse_register_contact(p, peer, req)) {
10885 case PARSE_REGISTER_FAILED:
10886 ast_log(LOG_WARNING, "Failed to parse contact info\n");
10887 transmit_response_with_date(p, "400 Bad Request", req);
10888 peer->lastmsgssent = -1;
10889 res = 0;
10890 break;
10891 case PARSE_REGISTER_QUERY:
10892 transmit_response_with_date(p, "200 OK", req);
10893 peer->lastmsgssent = -1;
10894 res = 0;
10895 break;
10896 case PARSE_REGISTER_UPDATE:
10897 /* Say OK and ask subsystem to retransmit msg counter */
10898 transmit_response_with_date(p, "200 OK", req);
10899 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10900 peer->lastmsgssent = -1;
10901 res = 0;
10902 break;
10906 if (!res) {
10907 ast_device_state_changed("SIP/%s", peer->name);
10909 if (res < 0) {
10910 switch (res) {
10911 case AUTH_SECRET_FAILED:
10912 /* Wrong password in authentication. Go away, don't try again until you fixed it */
10913 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
10914 if (global_authfailureevents)
10915 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_SECRET_FAILED\r\nAddress: %s\r\nPort: %d\r\n",
10916 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10917 break;
10918 case AUTH_USERNAME_MISMATCH:
10919 /* Username and digest username does not match.
10920 Asterisk uses the From: username for authentication. We need the
10921 devices to use the same authentication user name until we support
10922 proper authentication by digest auth name */
10923 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
10924 if (global_authfailureevents)
10925 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_USERNAME_MISMATCH\r\nAddress: %s\r\nPort: %d\r\n",
10926 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10927 break;
10928 case AUTH_NOT_FOUND:
10929 case AUTH_PEER_NOT_DYNAMIC:
10930 case AUTH_ACL_FAILED:
10931 if (global_alwaysauthreject) {
10932 transmit_fake_auth_response(p, &p->initreq, 1);
10933 } else {
10934 /* URI not found */
10935 if (res == AUTH_PEER_NOT_DYNAMIC) {
10936 transmit_response(p, "403 Forbidden", &p->initreq);
10937 if (global_authfailureevents)
10938 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_PEER_NOT_DYNAMIC\r\nAddress: %s\r\nPort: %d\r\n",
10939 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10941 else
10942 transmit_response(p, "404 Not found", &p->initreq);
10943 if (global_authfailureevents)
10944 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: URI_NOT_FOUND\r\nAddress: %s\r\nPort: %d\r\n",
10945 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10947 break;
10948 case AUTH_BAD_TRANSPORT:
10949 default:
10950 break;
10953 if (peer)
10954 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
10956 return res;
10959 /*! \brief Translate referring cause */
10960 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
10962 if (strcmp(reason, "unknown")==0) {
10963 ast_string_field_set(p, redircause, "UNKNOWN");
10964 } else if (strcmp(reason, "user-busy")==0) {
10965 ast_string_field_set(p, redircause, "BUSY");
10966 } else if (strcmp(reason, "no-answer")==0) {
10967 ast_string_field_set(p, redircause, "NOANSWER");
10968 } else if (strcmp(reason, "unavailable")==0) {
10969 ast_string_field_set(p, redircause, "UNREACHABLE");
10970 } else if (strcmp(reason, "unconditional")==0) {
10971 ast_string_field_set(p, redircause, "UNCONDITIONAL");
10972 } else if (strcmp(reason, "time-of-day")==0) {
10973 ast_string_field_set(p, redircause, "UNKNOWN");
10974 } else if (strcmp(reason, "do-not-disturb")==0) {
10975 ast_string_field_set(p, redircause, "UNKNOWN");
10976 } else if (strcmp(reason, "deflection")==0) {
10977 ast_string_field_set(p, redircause, "UNKNOWN");
10978 } else if (strcmp(reason, "follow-me")==0) {
10979 ast_string_field_set(p, redircause, "UNKNOWN");
10980 } else if (strcmp(reason, "out-of-service")==0) {
10981 ast_string_field_set(p, redircause, "UNREACHABLE");
10982 } else if (strcmp(reason, "away")==0) {
10983 ast_string_field_set(p, redircause, "UNREACHABLE");
10984 } else {
10985 ast_string_field_set(p, redircause, "UNKNOWN");
10989 /*! \brief Get referring dnis */
10990 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
10992 char tmp[256], *exten, *rexten, *rdomain;
10993 char *params, *reason = NULL;
10994 struct sip_request *req;
10996 req = oreq ? oreq : &p->initreq;
10998 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
10999 if (ast_strlen_zero(tmp))
11000 return 0;
11002 exten = get_in_brackets(tmp);
11003 if (!strncasecmp(exten, "sip:", 4)) {
11004 exten += 4;
11005 } else if (!strncasecmp(exten, "sips:", 5)) {
11006 exten += 5;
11007 } else {
11008 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
11009 return -1;
11012 /* Get diversion-reason param if present */
11013 if ((params = strchr(tmp, ';'))) {
11014 *params = '\0'; /* Cut off parameters */
11015 params++;
11016 while (*params == ';' || *params == ' ')
11017 params++;
11018 /* Check if we have a reason parameter */
11019 if ((reason = strcasestr(params, "reason="))) {
11020 reason+=7;
11021 /* Remove enclosing double-quotes */
11022 if (*reason == '"')
11023 ast_strip_quoted(reason, "\"", "\"");
11024 if (!ast_strlen_zero(reason)) {
11025 sip_set_redirstr(p, reason);
11026 if (p->owner) {
11027 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
11028 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
11034 rdomain = exten;
11035 rexten = strsep(&rdomain, "@"); /* trim anything after @ */
11036 if (p->owner)
11037 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
11039 if (sip_debug_test_pvt(p))
11040 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
11042 ast_string_field_set(p, rdnis, rexten);
11044 return 0;
11047 /*! \brief Find out who the call is for.
11048 We use the request uri as a destination.
11049 This code assumes authentication has been done, so that the
11050 device (peer/user) context is already set.
11051 \return 0 on success (found a matching extension),
11052 1 for pickup extension or overlap dialling support (if we support it),
11053 -1 on error.
11055 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
11057 char tmp[256] = "", *uri, *a;
11058 char tmpf[256] = "", *from = NULL;
11059 struct sip_request *req;
11060 char *colon;
11061 char *decoded_uri;
11063 req = oreq;
11064 if (!req)
11065 req = &p->initreq;
11067 /* Find the request URI */
11068 if (req->rlPart2)
11069 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
11071 if (pedanticsipchecking)
11072 ast_uri_decode(tmp);
11074 uri = get_in_brackets(tmp);
11076 if (!strncasecmp(uri, "sip:", 4)) {
11077 uri += 4;
11078 } else if (!strncasecmp(uri, "sips:", 5)) {
11079 uri += 5;
11080 } else {
11081 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
11082 return -1;
11085 /* Now find the From: caller ID and name */
11086 /* XXX Why is this done in get_destination? Isn't it already done?
11087 Needs to be checked
11089 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
11090 if (!ast_strlen_zero(tmpf)) {
11091 if (pedanticsipchecking)
11092 ast_uri_decode(tmpf);
11093 from = get_in_brackets(tmpf);
11096 if (!ast_strlen_zero(from)) {
11097 if (!strncasecmp(from, "sip:", 4)) {
11098 from += 4;
11099 } else if (!strncasecmp(from, "sips:", 5)) {
11100 from += 5;
11101 } else {
11102 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
11103 return -1;
11105 if ((a = strchr(from, '@')))
11106 *a++ = '\0';
11107 else
11108 a = from; /* just a domain */
11109 from = strsep(&from, ";"); /* Remove userinfo options */
11110 a = strsep(&a, ";"); /* Remove URI options */
11111 ast_string_field_set(p, fromdomain, a);
11114 /* Skip any options and find the domain */
11116 /* Get the target domain */
11117 if ((a = strchr(uri, '@'))) {
11118 *a++ = '\0';
11119 } else { /* No username part */
11120 a = uri;
11121 uri = "s"; /* Set extension to "s" */
11123 colon = strchr(a, ':'); /* Remove :port */
11124 if (colon)
11125 *colon = '\0';
11127 uri = strsep(&uri, ";"); /* Remove userinfo options */
11128 a = strsep(&a, ";"); /* Remove URI options */
11130 ast_string_field_set(p, domain, a);
11132 if (!AST_LIST_EMPTY(&domain_list)) {
11133 char domain_context[AST_MAX_EXTENSION];
11135 domain_context[0] = '\0';
11136 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
11137 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
11138 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
11139 return -2;
11142 /* If we have a context defined, overwrite the original context */
11143 if (!ast_strlen_zero(domain_context))
11144 ast_string_field_set(p, context, domain_context);
11147 /* If the request coming in is a subscription and subscribecontext has been specified use it */
11148 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
11149 ast_string_field_set(p, context, p->subscribecontext);
11151 if (sip_debug_test_pvt(p))
11152 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
11154 /* If this is a subscription we actually just need to see if a hint exists for the extension */
11155 if (req->method == SIP_SUBSCRIBE) {
11156 char hint[AST_MAX_EXTENSION];
11157 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
11158 } else {
11159 decoded_uri = ast_strdupa(uri);
11160 ast_uri_decode(decoded_uri);
11161 /* Check the dialplan for the username part of the request URI,
11162 the domain will be stored in the SIPDOMAIN variable
11163 Since extensions.conf can have unescaped characters, try matching a decoded
11164 uri in addition to the non-decoded uri
11165 Return 0 if we have a matching extension */
11166 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
11167 !strcmp(decoded_uri, ast_pickup_ext())) {
11168 if (!oreq)
11169 ast_string_field_set(p, exten, decoded_uri);
11170 return 0;
11174 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
11175 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
11176 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
11177 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
11178 return 1;
11181 return -1;
11184 /*! \brief Lock dialog lock and find matching pvt lock
11185 - Their tag is fromtag, our tag is to-tag
11186 - This means that in some transactions, totag needs to be their tag :-)
11187 depending upon the direction
11188 \return a reference, remember to release it when done
11190 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
11192 struct sip_pvt *sip_pvt_ptr;
11193 struct sip_pvt tmp_dialog = {
11194 .callid = callid,
11197 if (totag)
11198 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
11200 /* Search dialogs and find the match */
11202 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
11203 if (sip_pvt_ptr) {
11204 char *ourtag = sip_pvt_ptr->tag;
11205 /* Go ahead and lock it (and its owner) before returning */
11206 sip_pvt_lock(sip_pvt_ptr);
11208 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag)))) {
11209 sip_pvt_unlock(sip_pvt_ptr);
11210 ast_debug(4, "Matched %s call for callid=%s - But the pedantic check rejected the match; their tag is %s Our tag is %s\n",
11211 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
11212 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
11213 return 0;
11216 if (totag)
11217 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
11218 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
11219 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
11221 /* deadlock avoidance... */
11222 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
11223 sip_pvt_unlock(sip_pvt_ptr);
11224 usleep(1);
11225 sip_pvt_lock(sip_pvt_ptr);
11229 return sip_pvt_ptr;
11232 /*! \brief Call transfer support (the REFER method)
11233 * Extracts Refer headers into pvt dialog structure */
11234 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
11237 const char *p_referred_by = NULL;
11238 char *h_refer_to = NULL;
11239 char *h_referred_by = NULL;
11240 char *refer_to;
11241 const char *p_refer_to;
11242 char *referred_by_uri = NULL;
11243 char *ptr;
11244 struct sip_request *req = NULL;
11245 const char *transfer_context = NULL;
11246 struct sip_refer *referdata;
11249 req = outgoing_req;
11250 referdata = transferer->refer;
11252 if (!req)
11253 req = &transferer->initreq;
11255 p_refer_to = get_header(req, "Refer-To");
11256 if (ast_strlen_zero(p_refer_to)) {
11257 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
11258 return -2; /* Syntax error */
11260 h_refer_to = ast_strdupa(p_refer_to);
11261 refer_to = get_in_brackets(h_refer_to);
11262 if (pedanticsipchecking)
11263 ast_uri_decode(refer_to);
11265 if (!strncasecmp(refer_to, "sip:", 4)) {
11266 refer_to += 4; /* Skip sip: */
11267 } else if (!strncasecmp(refer_to, "sips:", 5)) {
11268 refer_to += 5;
11269 } else {
11270 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
11271 return -3;
11274 /* Get referred by header if it exists */
11275 p_referred_by = get_header(req, "Referred-By");
11277 /* Give useful transfer information to the dialplan */
11278 if (transferer->owner) {
11279 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
11280 if (peer) {
11281 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
11282 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
11286 if (!ast_strlen_zero(p_referred_by)) {
11287 char *lessthan;
11288 h_referred_by = ast_strdupa(p_referred_by);
11289 if (pedanticsipchecking)
11290 ast_uri_decode(h_referred_by);
11292 /* Store referrer's caller ID name */
11293 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
11294 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
11295 *(lessthan - 1) = '\0'; /* Space */
11298 referred_by_uri = get_in_brackets(h_referred_by);
11299 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
11300 referred_by_uri += 4; /* Skip sip: */
11301 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
11302 referred_by_uri += 5; /* Skip sips: */
11303 } else {
11304 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
11305 referred_by_uri = NULL;
11309 /* Check for arguments in the refer_to header */
11310 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
11311 *ptr++ = '\0';
11312 if (!strncasecmp(ptr, "REPLACES=", 9)) {
11313 char *to = NULL, *from = NULL;
11315 /* This is an attended transfer */
11316 referdata->attendedtransfer = 1;
11317 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
11318 ast_uri_decode(referdata->replaces_callid);
11319 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
11320 *ptr++ = '\0';
11323 if (ptr) {
11324 /* Find the different tags before we destroy the string */
11325 to = strcasestr(ptr, "to-tag=");
11326 from = strcasestr(ptr, "from-tag=");
11329 /* Grab the to header */
11330 if (to) {
11331 ptr = to + 7;
11332 if ((to = strchr(ptr, '&')))
11333 *to = '\0';
11334 if ((to = strchr(ptr, ';')))
11335 *to = '\0';
11336 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
11339 if (from) {
11340 ptr = from + 9;
11341 if ((to = strchr(ptr, '&')))
11342 *to = '\0';
11343 if ((to = strchr(ptr, ';')))
11344 *to = '\0';
11345 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
11348 if (!pedanticsipchecking)
11349 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
11350 else
11351 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
11355 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
11356 char *urioption = NULL, *domain;
11357 *ptr++ = '\0';
11359 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
11360 *urioption++ = '\0';
11362 domain = ptr;
11363 if ((ptr = strchr(domain, ':'))) /* Remove :port */
11364 *ptr = '\0';
11366 /* Save the domain for the dial plan */
11367 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
11368 if (urioption)
11369 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
11372 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
11373 *ptr = '\0';
11374 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
11376 if (referred_by_uri) {
11377 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
11378 *ptr = '\0';
11379 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
11380 } else {
11381 referdata->referred_by[0] = '\0';
11384 /* Determine transfer context */
11385 if (transferer->owner) /* Mimic behaviour in res_features.c */
11386 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
11388 /* By default, use the context in the channel sending the REFER */
11389 if (ast_strlen_zero(transfer_context)) {
11390 transfer_context = S_OR(transferer->owner->macrocontext,
11391 S_OR(transferer->context, default_context));
11394 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
11396 /* Either an existing extension or the parking extension */
11397 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
11398 if (sip_debug_test_pvt(transferer)) {
11399 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
11401 /* We are ready to transfer to the extension */
11402 return 0;
11404 if (sip_debug_test_pvt(transferer))
11405 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
11407 /* Failure, we can't find this extension */
11408 return -1;
11412 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
11413 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
11415 char tmp[256] = "", *c, *a;
11416 struct sip_request *req = oreq ? oreq : &p->initreq;
11417 struct sip_refer *referdata = NULL;
11418 const char *transfer_context = NULL;
11420 if (!p->refer && !sip_refer_allocate(p))
11421 return -1;
11423 referdata = p->refer;
11425 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
11426 c = get_in_brackets(tmp);
11428 if (pedanticsipchecking)
11429 ast_uri_decode(c);
11431 if (!strncasecmp(c, "sip:", 4)) {
11432 c += 4;
11433 } else if (!strncasecmp(c, "sips:", 5)) {
11434 c += 5;
11435 } else {
11436 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
11437 return -1;
11440 if ((a = strchr(c, ';'))) /* Remove arguments */
11441 *a = '\0';
11443 if ((a = strchr(c, '@'))) { /* Separate Domain */
11444 *a++ = '\0';
11445 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
11448 if (sip_debug_test_pvt(p))
11449 ast_verbose("Looking for %s in %s\n", c, p->context);
11451 if (p->owner) /* Mimic behaviour in res_features.c */
11452 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
11454 /* By default, use the context in the channel sending the REFER */
11455 if (ast_strlen_zero(transfer_context)) {
11456 transfer_context = S_OR(p->owner->macrocontext,
11457 S_OR(p->context, default_context));
11459 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
11460 /* This is a blind transfer */
11461 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
11462 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
11463 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
11464 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
11465 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
11466 /* Set new context */
11467 ast_string_field_set(p, context, transfer_context);
11468 return 0;
11469 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
11470 return 1;
11473 return -1;
11476 /*! \brief check received= and rport= in a SIP response.
11477 * If we get a response with received= and/or rport= in the Via:
11478 * line, use them as 'p->ourip' (see RFC 3581 for rport,
11479 * and RFC 3261 for received).
11480 * Using these two fields SIP can produce the correct
11481 * address and port in the SIP headers without the need for STUN.
11482 * The address part is also reused for the media sessions.
11483 * Note that ast_sip_ouraddrfor() still rewrites p->ourip
11484 * if you specify externip/seternaddr/stunaddr.
11486 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
11488 char via[256];
11489 char *cur, *opts;
11491 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
11493 /* Work on the leftmost value of the topmost Via header */
11494 opts = strchr(via, ',');
11495 if (opts)
11496 *opts = '\0';
11498 /* parse all relevant options */
11499 opts = strchr(via, ';');
11500 if (!opts)
11501 return; /* no options to parse */
11502 *opts++ = '\0';
11503 while ( (cur = strsep(&opts, ";")) ) {
11504 if (!strncmp(cur, "rport=", 6)) {
11505 int port = strtol(cur+6, NULL, 10);
11506 /* XXX add error checking */
11507 p->ourip.sin_port = ntohs(port);
11508 } else if (!strncmp(cur, "received=", 9)) {
11509 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
11510 ; /* XXX add error checking */
11515 /*! \brief check Via: header for hostname, port and rport request/answer */
11516 static void check_via(struct sip_pvt *p, struct sip_request *req)
11518 char via[512];
11519 char *c, *pt;
11520 struct hostent *hp;
11521 struct ast_hostent ahp;
11523 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
11525 /* Work on the leftmost value of the topmost Via header */
11526 c = strchr(via, ',');
11527 if (c)
11528 *c = '\0';
11530 /* Check for rport */
11531 c = strstr(via, ";rport");
11532 if (c && (c[6] != '=')) /* rport query, not answer */
11533 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
11535 c = strchr(via, ';');
11536 if (c)
11537 *c = '\0';
11539 c = strchr(via, ' ');
11540 if (c) {
11541 *c = '\0';
11542 c = ast_skip_blanks(c+1);
11543 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
11544 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
11545 return;
11547 pt = strchr(c, ':');
11548 if (pt)
11549 *pt++ = '\0'; /* remember port pointer */
11550 hp = ast_gethostbyname(c, &ahp);
11551 if (!hp) {
11552 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
11553 return;
11555 memset(&p->sa, 0, sizeof(p->sa));
11556 p->sa.sin_family = AF_INET;
11557 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
11558 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
11560 if (sip_debug_test_pvt(p)) {
11561 const struct sockaddr_in *dst = sip_real_dst(p);
11562 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
11567 /*! \brief Get caller id name from SIP headers */
11568 static char *get_calleridname(const char *input, char *output, size_t outputsize)
11570 const char *end = strchr(input, '<'); /* first_bracket */
11571 const char *tmp = strchr(input, '"'); /* first quote */
11572 int bytes = 0;
11573 int maxbytes = outputsize - 1;
11575 if (!end || end == input) /* we require a part in brackets */
11576 return NULL;
11578 end--; /* move just before "<" */
11580 if (tmp && tmp <= end) {
11581 /* The quote (tmp) precedes the bracket (end+1).
11582 * Find the matching quote and return the content.
11584 end = strchr(tmp+1, '"');
11585 if (!end)
11586 return NULL;
11587 bytes = (int) (end - tmp);
11588 /* protect the output buffer */
11589 if (bytes > maxbytes)
11590 bytes = maxbytes;
11591 ast_copy_string(output, tmp + 1, bytes);
11592 } else {
11593 /* No quoted string, or it is inside brackets. */
11594 /* clear the empty characters in the begining*/
11595 input = ast_skip_blanks(input);
11596 /* clear the empty characters in the end */
11597 while(*end && *end < 33 && end > input)
11598 end--;
11599 if (end >= input) {
11600 bytes = (int) (end - input) + 2;
11601 /* protect the output buffer */
11602 if (bytes > maxbytes)
11603 bytes = maxbytes;
11604 ast_copy_string(output, input, bytes);
11605 } else
11606 return NULL;
11608 return output;
11611 /*! \brief Get caller id number from Remote-Party-ID header field
11612 * Returns true if number should be restricted (privacy setting found)
11613 * output is set to NULL if no number found
11615 static int get_rpid_num(const char *input, char *output, int maxlen)
11617 char *start;
11618 char *end;
11620 start = strchr(input, ':');
11621 if (!start) {
11622 output[0] = '\0';
11623 return 0;
11625 start++;
11627 /* we found "number" */
11628 ast_copy_string(output, start, maxlen);
11629 output[maxlen-1] = '\0';
11631 end = strchr(output, '@');
11632 if (end)
11633 *end = '\0';
11634 else
11635 output[0] = '\0';
11636 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
11637 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
11639 return 0;
11643 * duplicate a list of channel variables, \return the copy.
11645 static struct ast_variable *copy_vars(struct ast_variable *src)
11647 struct ast_variable *res = NULL, *tmp, *v = NULL;
11649 for (v = src ; v ; v = v->next) {
11650 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
11651 tmp->next = res;
11652 res = tmp;
11655 return res;
11658 /*! \brief helper function for check_{user|peer}_ok() */
11659 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
11661 /* replace callerid if rpid found, and not restricted */
11662 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
11663 char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
11664 if (!ast_strlen_zero(calleridname))
11665 ast_string_field_set(p, cid_name, calleridname);
11666 if (ast_is_shrinkable_phonenumber(tmp))
11667 ast_shrink_phone_number(tmp);
11668 ast_string_field_set(p, cid_num, tmp);
11672 /*! \brief Validate peer authentication */
11673 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
11674 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
11675 struct sip_peer **authpeer,
11676 enum xmittype reliable,
11677 char *rpid_num, char *calleridname, char *uri2)
11679 enum check_auth_result res;
11680 int debug=sip_debug_test_addr(sin);
11681 struct sip_peer *peer;
11683 /* For subscribes, match on device name only; for other methods,
11684 * match on IP address-port of the incoming request.
11686 /* First find device on name */
11687 peer = find_peer(of, NULL, TRUE, FALSE);
11689 /* If not found, then find device on IP (if it's not a SUBSCRIBE) */
11690 if (!peer && sipmethod != SIP_SUBSCRIBE) {
11691 peer = find_peer(NULL, &p->recv, TRUE, FALSE);
11694 if (!peer) {
11695 if (debug)
11696 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
11697 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11698 return AUTH_DONT_KNOW;
11701 if (debug)
11702 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
11703 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11705 /* XXX what about p->prefs = peer->prefs; ? */
11706 /* Set Frame packetization */
11707 if (p->rtp) {
11708 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
11709 p->autoframing = peer->autoframing;
11712 /* Take the peer */
11713 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
11714 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
11716 /* Copy SIP extensions profile to peer */
11717 /* XXX is this correct before a successful auth ? */
11718 if (p->sipoptions)
11719 peer->sipoptions = p->sipoptions;
11721 replace_cid(p, rpid_num, calleridname);
11722 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
11724 ast_string_field_set(p, peersecret, peer->secret);
11725 ast_string_field_set(p, peermd5secret, peer->md5secret);
11726 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
11727 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
11728 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
11729 ast_string_field_set(p, parkinglot, peer->parkinglot);
11730 if (peer->callingpres) /* Peer calling pres setting will override RPID */
11731 p->callingpres = peer->callingpres;
11732 if (peer->maxms && peer->lastms)
11733 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
11734 else
11735 p->timer_t1 = peer->timer_t1;
11737 /* Set timer B to control transaction timeouts */
11738 if (peer->timer_b)
11739 p->timer_b = peer->timer_b;
11740 else
11741 p->timer_b = 64 * p->timer_t1;
11743 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
11744 /* Pretend there is no required authentication */
11745 ast_string_field_set(p, peersecret, NULL);
11746 ast_string_field_set(p, peermd5secret, NULL);
11748 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
11749 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
11750 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
11751 /* If we have a call limit, set flag */
11752 if (peer->call_limit)
11753 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
11754 ast_string_field_set(p, peername, peer->name);
11755 ast_string_field_set(p, authname, peer->name);
11757 /* copy channel vars */
11758 p->chanvars = copy_vars(peer->chanvars);
11759 if (authpeer) {
11760 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
11761 (*authpeer) = peer; /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
11764 if (!ast_strlen_zero(peer->username)) {
11765 ast_string_field_set(p, username, peer->username);
11766 /* Use the default username for authentication on outbound calls */
11767 /* XXX this takes the name from the caller... can we override ? */
11768 ast_string_field_set(p, authname, peer->username);
11770 if (!ast_strlen_zero(peer->cid_num)) {
11771 char *tmp = ast_strdupa(peer->cid_num);
11772 if (ast_is_shrinkable_phonenumber(tmp))
11773 ast_shrink_phone_number(tmp);
11774 ast_string_field_set(p, cid_num, tmp);
11776 if (!ast_strlen_zero(peer->cid_name))
11777 ast_string_field_set(p, cid_name, peer->cid_name);
11778 ast_string_field_set(p, fullcontact, peer->fullcontact);
11779 if (!ast_strlen_zero(peer->context))
11780 ast_string_field_set(p, context, peer->context);
11781 ast_string_field_set(p, peersecret, peer->secret);
11782 ast_string_field_set(p, peermd5secret, peer->md5secret);
11783 ast_string_field_set(p, language, peer->language);
11784 ast_string_field_set(p, accountcode, peer->accountcode);
11785 p->amaflags = peer->amaflags;
11786 p->callgroup = peer->callgroup;
11787 p->pickupgroup = peer->pickupgroup;
11788 p->capability = peer->capability;
11789 p->prefs = peer->prefs;
11790 p->jointcapability = peer->capability;
11791 if (p->peercapability)
11792 p->jointcapability &= p->peercapability;
11793 p->maxcallbitrate = peer->maxcallbitrate;
11794 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
11795 ast_rtp_destroy(p->vrtp);
11796 p->vrtp = NULL;
11798 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
11799 ast_rtp_destroy(p->trtp);
11800 p->trtp = NULL;
11802 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
11803 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
11804 p->noncodeccapability |= AST_RTP_DTMF;
11805 else
11806 p->noncodeccapability &= ~AST_RTP_DTMF;
11807 p->jointnoncodeccapability = p->noncodeccapability;
11808 if (p->t38.peercapability)
11809 p->t38.jointcapability &= p->t38.peercapability;
11811 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
11812 return res;
11816 /*! \brief Check if matching user or peer is defined
11817 Match user on From: user name and peer on IP/port
11818 This is used on first invite (not re-invites) and subscribe requests
11819 \return 0 on success, non-zero on failure
11821 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
11822 int sipmethod, char *uri, enum xmittype reliable,
11823 struct sockaddr_in *sin, struct sip_peer **authpeer)
11825 char from[256];
11826 char *dummy; /* dummy return value for parse_uri */
11827 char *domain; /* dummy return value for parse_uri */
11828 char *of, *of2;
11829 char rpid_num[50];
11830 const char *rpid;
11831 enum check_auth_result res;
11832 char calleridname[50];
11833 char *uri2 = ast_strdupa(uri);
11835 terminate_uri(uri2); /* trim extra stuff */
11837 ast_copy_string(from, get_header(req, "From"), sizeof(from));
11838 if (pedanticsipchecking)
11839 ast_uri_decode(from);
11840 /* XXX here tries to map the username for invite things */
11841 memset(calleridname, 0, sizeof(calleridname));
11842 get_calleridname(from, calleridname, sizeof(calleridname));
11843 if (calleridname[0])
11844 ast_string_field_set(p, cid_name, calleridname);
11846 rpid = get_header(req, "Remote-Party-ID");
11847 memset(rpid_num, 0, sizeof(rpid_num));
11848 if (!ast_strlen_zero(rpid))
11849 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
11851 of = get_in_brackets(from);
11852 if (ast_strlen_zero(p->exten)) {
11853 char *t = uri2;
11854 if (!strncasecmp(t, "sip:", 4))
11855 t+= 4;
11856 else if (!strncasecmp(t, "sips:", 5))
11857 t += 5;
11858 ast_string_field_set(p, exten, t);
11859 t = strchr(p->exten, '@');
11860 if (t)
11861 *t = '\0';
11862 if (ast_strlen_zero(p->our_contact))
11863 build_contact(p);
11865 /* save the URI part of the From header */
11866 ast_string_field_set(p, from, of);
11868 of2 = ast_strdupa(of);
11870 /* ignore all fields but name */
11871 if (p->socket.type == SIP_TRANSPORT_TLS) {
11872 if (parse_uri(of, "sips:", &of, &dummy, &domain, &dummy, &dummy)) {
11873 if (parse_uri(of2, "sip:", &of, &dummy, &domain, &dummy, &dummy))
11874 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
11876 } else {
11877 if (parse_uri(of, "sip:", &of, &dummy, &domain, &dummy, &dummy))
11878 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
11881 if (ast_strlen_zero(of)) {
11882 /* XXX note: the original code considered a missing @host
11883 * as a username-only URI. The SIP RFC (19.1.1) says that
11884 * this is wrong, and it should be considered as a domain-only URI.
11885 * For backward compatibility, we keep this block, but it is
11886 * really a mistake and should go away.
11888 of = domain;
11891 char *tmp = ast_strdupa(of);
11892 /* We need to be able to handle auth-headers looking like
11893 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
11895 tmp = strsep(&tmp, ";");
11896 if (ast_is_shrinkable_phonenumber(tmp))
11897 ast_shrink_phone_number(tmp);
11898 ast_string_field_set(p, cid_num, tmp);
11901 if (global_match_auth_username) {
11903 * XXX This is experimental code to grab the search key from the
11904 * Auth header's username instead of the 'From' name, if available.
11905 * Do not enable this block unless you understand the side effects (if any!)
11906 * Note, the search for "username" should be done in a more robust way.
11907 * Note2, at the moment we check both fields, though maybe we should
11908 * pick one or another depending on the request ? XXX
11910 const char *hdr = get_header(req, "Authorization");
11911 if (ast_strlen_zero(hdr))
11912 hdr = get_header(req, "Proxy-Authorization");
11914 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
11915 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
11916 of = from;
11917 of = strsep(&of, "\"");
11921 res = check_peer_ok(p, of, req, sipmethod, sin,
11922 authpeer, reliable, rpid_num, calleridname, uri2);
11923 if (res != AUTH_DONT_KNOW)
11924 return res;
11926 /* Finally, apply the guest policy */
11927 if (global_allowguest) {
11928 replace_cid(p, rpid_num, calleridname);
11929 res = AUTH_SUCCESSFUL;
11930 } else if (global_alwaysauthreject)
11931 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
11932 else
11933 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
11935 return res;
11938 /*! \brief Find user
11939 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
11941 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
11943 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
11946 /*! \brief Get text out of a SIP MESSAGE packet */
11947 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
11949 int x;
11950 int y;
11952 buf[0] = '\0';
11953 y = len - strlen(buf) - 5;
11954 if (y < 0)
11955 y = 0;
11956 for (x=0; x < req->lines; x++) {
11957 strncat(buf, req->line[x], y); /* safe */
11958 y -= strlen(req->line[x]) + 1;
11959 if (y < 0)
11960 y = 0;
11961 if (y != 0 && addnewline)
11962 strcat(buf, "\n"); /* safe */
11964 return 0;
11968 /*! \brief Receive SIP MESSAGE method messages
11969 \note We only handle messages within current calls currently
11970 Reference: RFC 3428 */
11971 static void receive_message(struct sip_pvt *p, struct sip_request *req)
11973 char buf[1400];
11974 struct ast_frame f;
11975 const char *content_type = get_header(req, "Content-Type");
11977 if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
11978 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
11979 if (!p->owner)
11980 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11981 return;
11984 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
11985 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
11986 transmit_response(p, "202 Accepted", req);
11987 if (!p->owner)
11988 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11989 return;
11992 if (p->owner) {
11993 if (sip_debug_test_pvt(p))
11994 ast_verbose("SIP Text message received: '%s'\n", buf);
11995 memset(&f, 0, sizeof(f));
11996 f.frametype = AST_FRAME_TEXT;
11997 f.subclass = 0;
11998 f.offset = 0;
11999 f.data.ptr = buf;
12000 f.datalen = strlen(buf);
12001 ast_queue_frame(p->owner, &f);
12002 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
12003 return;
12006 /* Message outside of a call, we do not support that */
12007 ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
12008 transmit_response(p, "405 Method Not Allowed", req);
12009 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12010 return;
12013 /*! \brief CLI Command to show calls within limits set by call_limit */
12014 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12016 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
12017 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
12018 char ilimits[40];
12019 char iused[40];
12020 int showall = FALSE;
12021 struct ao2_iterator i;
12022 struct sip_peer *peer;
12024 switch (cmd) {
12025 case CLI_INIT:
12026 e->command = "sip show inuse";
12027 e->usage =
12028 "Usage: sip show inuse [all]\n"
12029 " List all SIP devices usage counters and limits.\n"
12030 " Add option \"all\" to show all devices, not only those with a limit.\n";
12031 return NULL;
12032 case CLI_GENERATE:
12033 return NULL;
12036 if (a->argc < 3)
12037 return CLI_SHOWUSAGE;
12039 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
12040 showall = TRUE;
12042 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
12044 i = ao2_iterator_init(peers, 0);
12046 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
12047 ao2_lock(peer);
12048 if (peer->call_limit)
12049 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
12050 else
12051 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
12052 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
12053 if (showall || peer->call_limit)
12054 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
12055 ao2_unlock(peer);
12056 unref_peer(peer, "toss iterator pointer");
12059 return CLI_SUCCESS;
12060 #undef FORMAT
12061 #undef FORMAT2
12065 /*! \brief Convert transfer mode to text string */
12066 static char *transfermode2str(enum transfermodes mode)
12068 if (mode == TRANSFER_OPENFORALL)
12069 return "open";
12070 else if (mode == TRANSFER_CLOSED)
12071 return "closed";
12072 return "strict";
12075 static struct _map_x_s natmodes[] = {
12076 { SIP_NAT_NEVER, "No"},
12077 { SIP_NAT_ROUTE, "Route"},
12078 { SIP_NAT_ALWAYS, "Always"},
12079 { SIP_NAT_RFC3581, "RFC3581"},
12080 { -1, NULL}, /* terminator */
12083 /*! \brief Convert NAT setting to text string */
12084 static const char *nat2str(int nat)
12086 return map_x_s(natmodes, nat, "Unknown");
12089 #ifdef NOTUSED
12090 /* OEJ: This is not used, but may be useful in the future, so I don't want to
12091 delete it. Keeping it enabled generates compiler warnings.
12094 static struct _map_x_s natcfgmodes[] = {
12095 { SIP_NAT_NEVER, "never"},
12096 { SIP_NAT_ROUTE, "route"},
12097 { SIP_NAT_ALWAYS, "yes"},
12098 { SIP_NAT_RFC3581, "no"},
12099 { -1, NULL}, /* terminator */
12102 /*! \brief Convert NAT setting to text string appropriate for config files */
12103 static const char *nat2strconfig(int nat)
12105 return map_x_s(natcfgmodes, nat, "Unknown");
12107 #endif
12109 /*! \brief Report Peer status in character string
12110 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
12114 /* Session-Timer Modes */
12115 static struct _map_x_s stmodes[] = {
12116 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
12117 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
12118 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
12119 { -1, NULL},
12122 static const char *stmode2str(enum st_mode m)
12124 return map_x_s(stmodes, m, "Unknown");
12127 static enum st_mode str2stmode(const char *s)
12129 return map_s_x(stmodes, s, -1);
12132 /* Session-Timer Refreshers */
12133 static struct _map_x_s strefreshers[] = {
12134 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
12135 { SESSION_TIMER_REFRESHER_UAC, "uac"},
12136 { SESSION_TIMER_REFRESHER_UAS, "uas"},
12137 { -1, NULL},
12140 static const char *strefresher2str(enum st_refresher r)
12142 return map_x_s(strefreshers, r, "Unknown");
12145 static enum st_refresher str2strefresher(const char *s)
12147 return map_s_x(strefreshers, s, -1);
12151 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
12153 int res = 0;
12154 if (peer->maxms) {
12155 if (peer->lastms < 0) {
12156 ast_copy_string(status, "UNREACHABLE", statuslen);
12157 } else if (peer->lastms > peer->maxms) {
12158 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
12159 res = 1;
12160 } else if (peer->lastms) {
12161 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
12162 res = 1;
12163 } else {
12164 ast_copy_string(status, "UNKNOWN", statuslen);
12166 } else {
12167 ast_copy_string(status, "Unmonitored", statuslen);
12168 /* Checking if port is 0 */
12169 res = -1;
12171 return res;
12174 /*! \brief return Yes or No depending on the argument.
12175 * This is used in many places in CLI command, having a function to generate
12176 * this helps maintaining a consistent output (and possibly emitting the
12177 * output in other languages, at some point).
12179 static const char *cli_yesno(int x)
12181 return x ? "Yes" : "No";
12184 /*! \brief Show active TCP connections */
12185 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12187 struct sip_threadinfo *th;
12189 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
12190 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
12192 switch (cmd) {
12193 case CLI_INIT:
12194 e->command = "sip show tcp";
12195 e->usage =
12196 "Usage: sip show tcp\n"
12197 " Lists all active TCP/TLS sessions.\n";
12198 return NULL;
12199 case CLI_GENERATE:
12200 return NULL;
12203 if (a->argc != 3)
12204 return CLI_SHOWUSAGE;
12206 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
12207 AST_LIST_LOCK(&threadl);
12208 AST_LIST_TRAVERSE(&threadl, th, list) {
12209 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->ser->requestor.sin_addr),
12210 ntohs(th->ser->requestor.sin_port),
12211 get_transport(th->type),
12212 (th->ser->client ? "Client" : "Server"));
12215 AST_LIST_UNLOCK(&threadl);
12216 return CLI_SUCCESS;
12217 #undef FORMAT
12218 #undef FORMAT2
12221 /*! \brief Manager Action SIPShowRegistry description */
12222 static char mandescr_show_registry[] =
12223 "Description: Lists all registration requests and status\n"
12224 "Registrations will follow as separate events. followed by a final event called\n"
12225 "RegistrationsComplete.\n"
12226 "Variables: \n"
12227 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
12229 /*! \brief Show SIP registrations in the manager API */
12230 static int manager_show_registry(struct mansession *s, const struct message *m)
12232 const char *id = astman_get_header(m, "ActionID");
12233 char idtext[256] = "";
12234 char tmpdat[256] = "";
12235 int total = 0;
12236 struct ast_tm tm;
12238 if (!ast_strlen_zero(id))
12239 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12241 astman_send_listack(s, m, "Registrations will follow", "start");
12243 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
12244 ASTOBJ_RDLOCK(iterator);
12245 if (iterator->regtime.tv_sec) {
12246 ast_localtime(&iterator->regtime, &tm, NULL);
12247 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
12248 } else
12249 tmpdat[0] = '\0';
12250 astman_append(s,
12251 "Event: RegistryEntry\r\n"
12252 "Host: %s\r\n"
12253 "Port: %d\r\n"
12254 "Username: %s\r\n"
12255 "Refresh: %d\r\n"
12256 "State: %s\r\n"
12257 "Reg.Time: %s\r\n"
12258 "\r\n", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
12259 iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
12260 ASTOBJ_UNLOCK(iterator);
12261 total++;
12262 } while(0));
12264 astman_append(s,
12265 "Event: RegistrationsComplete\r\n"
12266 "EventList: Complete\r\n"
12267 "ListItems: %d\r\n"
12268 "%s"
12269 "\r\n", total, idtext);
12271 return 0;
12274 static char mandescr_show_peers[] =
12275 "Description: Lists SIP peers in text format with details on current status.\n"
12276 "Peerlist will follow as separate events, followed by a final event called\n"
12277 "PeerlistComplete.\n"
12278 "Variables: \n"
12279 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
12281 /*! \brief Show SIP peers in the manager API */
12282 /* Inspired from chan_iax2 */
12283 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
12285 const char *id = astman_get_header(m, "ActionID");
12286 const char *a[] = {"sip", "show", "peers"};
12287 char idtext[256] = "";
12288 int total = 0;
12290 if (!ast_strlen_zero(id))
12291 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12293 astman_send_listack(s, m, "Peer status list will follow", "start");
12294 /* List the peers in separate manager events */
12295 _sip_show_peers(-1, &total, s, m, 3, a);
12296 /* Send final confirmation */
12297 astman_append(s,
12298 "Event: PeerlistComplete\r\n"
12299 "EventList: Complete\r\n"
12300 "ListItems: %d\r\n"
12301 "%s"
12302 "\r\n", total, idtext);
12303 return 0;
12306 /*! \brief CLI Show Peers command */
12307 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12309 switch (cmd) {
12310 case CLI_INIT:
12311 e->command = "sip show peers";
12312 e->usage =
12313 "Usage: sip show peers [like <pattern>]\n"
12314 " Lists all known SIP peers.\n"
12315 " Optional regular expression pattern is used to filter the peer list.\n";
12316 return NULL;
12317 case CLI_GENERATE:
12318 return NULL;
12321 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
12324 int peercomparefunc(const void *a, const void *b);
12326 int peercomparefunc(const void *a, const void *b)
12328 struct sip_peer **ap = (struct sip_peer **)a;
12329 struct sip_peer **bp = (struct sip_peer **)b;
12330 return strcmp((*ap)->name, (*bp)->name);
12334 /*! \brief Execute sip show peers command */
12335 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
12337 regex_t regexbuf;
12338 int havepattern = FALSE;
12339 struct sip_peer *peer;
12340 struct ao2_iterator i;
12342 /* the last argument is left-aligned, so we don't need a size anyways */
12343 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
12344 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
12346 char name[256];
12347 int total_peers = 0;
12348 int peers_mon_online = 0;
12349 int peers_mon_offline = 0;
12350 int peers_unmon_offline = 0;
12351 int peers_unmon_online = 0;
12352 const char *id;
12353 char idtext[256] = "";
12354 int realtimepeers;
12355 int objcount = ao2_container_count(peers);
12356 struct sip_peer **peerarray;
12357 int k;
12360 realtimepeers = ast_check_realtime("sippeers");
12361 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
12363 if (s) { /* Manager - get ActionID */
12364 id = astman_get_header(m, "ActionID");
12365 if (!ast_strlen_zero(id))
12366 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12369 switch (argc) {
12370 case 5:
12371 if (!strcasecmp(argv[3], "like")) {
12372 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
12373 return CLI_SHOWUSAGE;
12374 havepattern = TRUE;
12375 } else
12376 return CLI_SHOWUSAGE;
12377 case 3:
12378 break;
12379 default:
12380 return CLI_SHOWUSAGE;
12383 if (!s) /* Normal list */
12384 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
12387 i = ao2_iterator_init(peers, 0);
12388 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
12389 ao2_lock(peer);
12390 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
12391 objcount--;
12392 ao2_unlock(peer);
12393 unref_peer(peer, "toss iterator peer ptr before continue");
12394 continue;
12397 peerarray[total_peers++] = peer;
12398 ao2_unlock(peer);
12401 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
12403 for(k=0; k < total_peers; k++) {
12404 char status[20] = "";
12405 char srch[2000];
12406 char pstatus;
12407 peer = peerarray[k];
12409 ao2_lock(peer);
12410 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
12411 ao2_unlock(peer);
12412 unref_peer(peer, "toss iterator peer ptr before continue");
12413 continue;
12416 if (!ast_strlen_zero(peer->username) && !s)
12417 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
12418 else
12419 ast_copy_string(name, peer->name, sizeof(name));
12421 pstatus = peer_status(peer, status, sizeof(status));
12422 if (pstatus == 1)
12423 peers_mon_online++;
12424 else if (pstatus == 0)
12425 peers_mon_offline++;
12426 else {
12427 if (peer->addr.sin_port == 0)
12428 peers_unmon_offline++;
12429 else
12430 peers_unmon_online++;
12433 snprintf(srch, sizeof(srch), FORMAT, name,
12434 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
12435 peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
12436 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
12437 peer->ha ? " A " : " ", /* permit/deny */
12438 ntohs(peer->addr.sin_port), status,
12439 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
12441 if (!s) {/* Normal CLI list */
12442 ast_cli(fd, FORMAT, name,
12443 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
12444 peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
12445 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
12446 peer->ha ? " A " : " ", /* permit/deny */
12448 ntohs(peer->addr.sin_port), status,
12449 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
12450 } else { /* Manager format */
12451 /* The names here need to be the same as other channels */
12452 astman_append(s,
12453 "Event: PeerEntry\r\n%s"
12454 "Channeltype: SIP\r\n"
12455 "ObjectName: %s\r\n"
12456 "ChanObjectType: peer\r\n" /* "peer" or "user" */
12457 "IPaddress: %s\r\n"
12458 "IPport: %d\r\n"
12459 "Dynamic: %s\r\n"
12460 "Natsupport: %s\r\n"
12461 "VideoSupport: %s\r\n"
12462 "TextSupport: %s\r\n"
12463 "ACL: %s\r\n"
12464 "Status: %s\r\n"
12465 "RealtimeDevice: %s\r\n\r\n",
12466 idtext,
12467 peer->name,
12468 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
12469 ntohs(peer->addr.sin_port),
12470 peer->host_dynamic ? "yes" : "no", /* Dynamic or not? */
12471 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
12472 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
12473 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no", /* TEXTSUPPORT=yes? */
12474 peer->ha ? "yes" : "no", /* permit/deny */
12475 status,
12476 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
12478 ao2_unlock(peer);
12479 unref_peer(peer, "toss iterator peer ptr");
12482 if (!s)
12483 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
12484 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
12486 if (havepattern)
12487 regfree(&regexbuf);
12489 if (total)
12490 *total = total_peers;
12492 ast_free(peerarray);
12494 return CLI_SUCCESS;
12495 #undef FORMAT
12496 #undef FORMAT2
12499 static int peer_dump_func(void *userobj, void *arg, int flags)
12501 struct sip_peer *peer = userobj;
12502 int refc = ao2_t_ref(userobj, 0, "");
12503 int *fd = arg;
12505 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
12506 peer->name, 0, refc);
12507 return 0;
12510 static int dialog_dump_func(void *userobj, void *arg, int flags)
12512 struct sip_pvt *pvt = userobj;
12513 int refc = ao2_t_ref(userobj, 0, "");
12514 int *fd = arg;
12516 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
12517 pvt->callid, 0, refc);
12518 return 0;
12522 /*! \brief List all allocated SIP Objects (realtime or static) */
12523 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12525 char tmp[256];
12527 switch (cmd) {
12528 case CLI_INIT:
12529 e->command = "sip show objects";
12530 e->usage =
12531 "Usage: sip show objects\n"
12532 " Lists status of known SIP objects\n";
12533 return NULL;
12534 case CLI_GENERATE:
12535 return NULL;
12538 if (a->argc != 3)
12539 return CLI_SHOWUSAGE;
12540 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
12541 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
12542 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
12543 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
12544 ast_cli(a->fd, "-= Dialog objects:\n\n");
12545 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
12546 return CLI_SUCCESS;
12548 /*! \brief Print call group and pickup group */
12549 static void print_group(int fd, ast_group_t group, int crlf)
12551 char buf[256];
12552 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
12555 /*! \brief mapping between dtmf flags and strings */
12556 static struct _map_x_s dtmfstr[] = {
12557 { SIP_DTMF_RFC2833, "rfc2833" },
12558 { SIP_DTMF_INFO, "info" },
12559 { SIP_DTMF_SHORTINFO, "shortinfo" },
12560 { SIP_DTMF_INBAND, "inband" },
12561 { SIP_DTMF_AUTO, "auto" },
12562 { -1, NULL }, /* terminator */
12565 /*! \brief Convert DTMF mode to printable string */
12566 static const char *dtmfmode2str(int mode)
12568 return map_x_s(dtmfstr, mode, "<error>");
12571 /*! \brief maps a string to dtmfmode, returns -1 on error */
12572 static int str2dtmfmode(const char *str)
12574 return map_s_x(dtmfstr, str, -1);
12577 static struct _map_x_s insecurestr[] = {
12578 { SIP_INSECURE_PORT, "port" },
12579 { SIP_INSECURE_INVITE, "invite" },
12580 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
12581 { 0, "no" },
12582 { -1, NULL }, /* terminator */
12585 /*! \brief Convert Insecure setting to printable string */
12586 static const char *insecure2str(int mode)
12588 return map_x_s(insecurestr, mode, "<error>");
12591 /*! \brief Destroy disused contexts between reloads
12592 Only used in reload_config so the code for regcontext doesn't get ugly
12594 static void cleanup_stale_contexts(char *new, char *old)
12596 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
12598 while ((oldcontext = strsep(&old, "&"))) {
12599 stalecontext = '\0';
12600 ast_copy_string(newlist, new, sizeof(newlist));
12601 stringp = newlist;
12602 while ((newcontext = strsep(&stringp, "&"))) {
12603 if (strcmp(newcontext, oldcontext) == 0) {
12604 /* This is not the context you're looking for */
12605 stalecontext = '\0';
12606 break;
12607 } else if (strcmp(newcontext, oldcontext)) {
12608 stalecontext = oldcontext;
12612 if (stalecontext)
12613 ast_context_destroy(ast_context_find(stalecontext), "SIP");
12617 /* this func is used with ao2_callback to unlink/delete all dialogs that
12618 are marked needdestroy. It will return CMP_MATCH for candidates, and they
12619 will be unlinked */
12621 /* TODO: Implement a queue and instead of marking a dialog
12622 to be destroyed, toss it into the queue. Have a separate
12623 thread do the locking and destruction */
12625 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
12627 struct sip_pvt *dialog = dialogobj;
12628 time_t *t = arg;
12630 /* log_show_lock(ao2_object_get_lockaddr(dialog)); this is an example of how to use log_show_lock() */
12631 if (sip_pvt_trylock(dialog)) {
12632 /* In very short-duration calls via sipp,
12633 this path gets executed fairly frequently (3% or so) even in low load
12634 situations; the routines we most commonly fight for a lock with:
12635 sip_answer (7 out of 9)
12636 sip_hangup (2 out of 9)
12638 ao2_unlock(dialogs);
12639 usleep(1);
12640 ao2_lock(dialogs);
12641 /* I had previously returned CMP_STOP here; but changed it to return
12642 a zero instead, because there is no need to stop at the first sign
12643 of trouble. The old algorithm would restart in such circumstances,
12644 but there is no need for this now in astobj2-land. We'll
12645 just skip over this element this time, and catch it on the
12646 next traversal, which is about once a second or so. See the
12647 ao2_callback call in do_monitor. We don't want the number of
12648 dialogs to back up too much between runs.
12650 return 0;
12653 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
12654 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
12655 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
12656 sip_pvt_unlock(dialog);
12657 return 0;
12660 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
12661 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
12662 sip_pvt_unlock(dialog);
12663 return 0;
12665 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
12666 check_rtp_timeout(dialog, *t);
12668 /* If we have sessions that needs to be destroyed, do it now */
12669 /* Check if we have outstanding requests not responsed to or an active call
12670 - if that's the case, wait with destruction */
12671 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
12672 sip_pvt_unlock(dialog);
12673 /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
12674 /* the CMP_MATCH will unlink this dialog from the dialog hash table */
12675 dialog_unlink_all(dialog, TRUE, FALSE);
12676 return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
12678 sip_pvt_unlock(dialog);
12679 return 0;
12682 /* this func is used with ao2_callback to unlink/delete all marked
12683 peers */
12684 static int peer_is_marked(void *peerobj, void *arg, int flags)
12686 struct sip_peer *peer = peerobj;
12687 return peer->the_mark ? CMP_MATCH : 0;
12690 /*! \brief Remove temporary realtime objects from memory (CLI) */
12691 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
12692 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12694 struct sip_peer *peer, *pi;
12695 int prunepeer = FALSE;
12696 int multi = FALSE;
12697 char *name = NULL;
12698 regex_t regexbuf;
12699 struct ao2_iterator i;
12701 if (cmd == CLI_INIT) {
12702 e->command = "sip prune realtime [peer|all] [all|like]";
12703 e->usage =
12704 "Usage: sip prune realtime [peer] [<name>|all|like <pattern>]\n"
12705 " Prunes object(s) from the cache.\n"
12706 " Optional regular expression pattern is used to filter the objects.\n";
12707 return NULL;
12708 } else if (cmd == CLI_GENERATE) {
12709 if (a->pos == 4) {
12710 if (strcasestr(a->line, "realtime peer"))
12711 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
12713 return NULL;
12715 switch (a->argc) {
12716 case 4:
12717 name = a->argv[3];
12718 /* we accept a name in position 3, but keywords are not good. */
12719 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
12720 return CLI_SHOWUSAGE;
12721 prunepeer = TRUE;
12722 if (!strcasecmp(name, "all")) {
12723 multi = TRUE;
12724 name = NULL;
12726 /* else a single name, already set */
12727 break;
12728 case 5:
12729 /* sip prune realtime {peer|like} name */
12730 name = a->argv[4];
12731 if (!strcasecmp(a->argv[3], "peer"))
12732 prunepeer = TRUE;
12733 else if (!strcasecmp(a->argv[3], "like")) {
12734 prunepeer = TRUE;
12735 multi = TRUE;
12736 } else
12737 return CLI_SHOWUSAGE;
12738 if (!strcasecmp(a->argv[4], "like"))
12739 return CLI_SHOWUSAGE;
12740 if (!multi && !strcasecmp(a->argv[4], "all")) {
12741 multi = TRUE;
12742 name = NULL;
12744 break;
12745 case 6:
12746 name = a->argv[5];
12747 multi = TRUE;
12748 /* sip prune realtime {peer} like name */
12749 if (strcasecmp(a->argv[4], "like"))
12750 return CLI_SHOWUSAGE;
12751 if (!strcasecmp(a->argv[3], "peer")) {
12752 prunepeer = TRUE;
12753 } else
12754 return CLI_SHOWUSAGE;
12755 break;
12756 default:
12757 return CLI_SHOWUSAGE;
12760 if (multi && name) {
12761 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
12762 return CLI_SHOWUSAGE;
12765 if (multi) {
12766 if (prunepeer) {
12767 int pruned = 0;
12769 i = ao2_iterator_init(peers, 0);
12770 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
12771 ao2_lock(pi);
12772 if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
12773 unref_peer(pi, "toss iterator peer ptr before continue");
12774 ao2_unlock(pi);
12775 continue;
12777 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12778 pi->the_mark = 1;
12779 pruned++;
12781 ao2_unlock(pi);
12782 unref_peer(pi, "toss iterator peer ptr");
12784 if (pruned) {
12785 ao2_t_callback(peers, OBJ_NODATA|OBJ_UNLINK, peer_is_marked, 0, "initiating callback to remove marked peers");
12786 ast_cli(a->fd, "%d peers pruned.\n", pruned);
12787 } else
12788 ast_cli(a->fd, "No peers found to prune.\n");
12790 } else {
12791 if (prunepeer) {
12792 struct sip_peer tmp;
12793 ast_copy_string(tmp.name, name, sizeof(tmp.name));
12794 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER|OBJ_UNLINK, "finding to unlink from peers"))) {
12795 if (peer->addr.sin_addr.s_addr) {
12796 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
12798 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12799 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
12800 /* put it back! */
12801 ao2_t_link(peers, peer, "link peer into peer table");
12802 if (peer->addr.sin_addr.s_addr) {
12803 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
12806 } else
12807 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
12808 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
12809 } else
12810 ast_cli(a->fd, "Peer '%s' not found.\n", name);
12814 return CLI_SUCCESS;
12817 /*! \brief Print codec list from preference to CLI/manager */
12818 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
12820 int x, codec;
12822 for(x = 0; x < 32 ; x++) {
12823 codec = ast_codec_pref_index(pref, x);
12824 if (!codec)
12825 break;
12826 ast_cli(fd, "%s", ast_getformatname(codec));
12827 ast_cli(fd, ":%d", pref->framing[x]);
12828 if (x < 31 && ast_codec_pref_index(pref, x + 1))
12829 ast_cli(fd, ",");
12831 if (!x)
12832 ast_cli(fd, "none");
12835 /*! \brief Print domain mode to cli */
12836 static const char *domain_mode_to_text(const enum domain_mode mode)
12838 switch (mode) {
12839 case SIP_DOMAIN_AUTO:
12840 return "[Automatic]";
12841 case SIP_DOMAIN_CONFIG:
12842 return "[Configured]";
12845 return "";
12848 /*! \brief CLI command to list local domains */
12849 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12851 struct domain *d;
12852 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
12854 switch (cmd) {
12855 case CLI_INIT:
12856 e->command = "sip show domains";
12857 e->usage =
12858 "Usage: sip show domains\n"
12859 " Lists all configured SIP local domains.\n"
12860 " Asterisk only responds to SIP messages to local domains.\n";
12861 return NULL;
12862 case CLI_GENERATE:
12863 return NULL;
12866 if (AST_LIST_EMPTY(&domain_list)) {
12867 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
12868 return CLI_SUCCESS;
12869 } else {
12870 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
12871 AST_LIST_LOCK(&domain_list);
12872 AST_LIST_TRAVERSE(&domain_list, d, list)
12873 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
12874 domain_mode_to_text(d->mode));
12875 AST_LIST_UNLOCK(&domain_list);
12876 ast_cli(a->fd, "\n");
12877 return CLI_SUCCESS;
12880 #undef FORMAT
12882 static char mandescr_show_peer[] =
12883 "Description: Show one SIP peer with details on current status.\n"
12884 "Variables: \n"
12885 " Peer: <name> The peer name you want to check.\n"
12886 " ActionID: <id> Optional action ID for this AMI transaction.\n";
12888 /*! \brief Show SIP peers in the manager API */
12889 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
12891 const char *a[4];
12892 const char *peer;
12894 peer = astman_get_header(m, "Peer");
12895 if (ast_strlen_zero(peer)) {
12896 astman_send_error(s, m, "Peer: <name> missing.\n");
12897 return 0;
12899 a[0] = "sip";
12900 a[1] = "show";
12901 a[2] = "peer";
12902 a[3] = peer;
12904 _sip_show_peer(1, -1, s, m, 4, a);
12905 astman_append(s, "\r\n\r\n" );
12906 return 0;
12909 /*! \brief Show one peer in detail */
12910 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12912 switch (cmd) {
12913 case CLI_INIT:
12914 e->command = "sip show peer";
12915 e->usage =
12916 "Usage: sip show peer <name> [load]\n"
12917 " Shows all details on one SIP peer and the current status.\n"
12918 " Option \"load\" forces lookup of peer in realtime storage.\n";
12919 return NULL;
12920 case CLI_GENERATE:
12921 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
12923 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
12926 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
12927 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
12929 struct sip_peer *peer;
12930 int load_realtime;
12932 if (argc < 4)
12933 return CLI_SHOWUSAGE;
12935 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
12936 if ((peer = find_peer(argv[3], NULL, load_realtime, FALSE))) {
12937 sip_poke_peer(peer, 1);
12938 unref_peer(peer, "qualify: done with peer");
12939 } else if (type == 0) {
12940 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
12941 } else {
12942 astman_send_error(s, m, "Peer not found\n");
12944 return CLI_SUCCESS;
12947 /*! \brief Qualify SIP peers in the manager API */
12948 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
12950 const char *a[4];
12951 const char *peer;
12953 peer = astman_get_header(m, "Peer");
12954 if (ast_strlen_zero(peer)) {
12955 astman_send_error(s, m, "Peer: <name> missing.\n");
12956 return 0;
12958 a[0] = "sip";
12959 a[1] = "qualify";
12960 a[2] = "peer";
12961 a[3] = peer;
12963 _sip_qualify_peer(1, -1, s, m, 4, a);
12964 astman_append(s, "\r\n\r\n" );
12965 return 0;
12968 /*! \brief Send an OPTIONS packet to a SIP peer */
12969 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12971 switch (cmd) {
12972 case CLI_INIT:
12973 e->command = "sip qualify peer";
12974 e->usage =
12975 "Usage: sip qualify peer <name> [load]\n"
12976 " Requests a response from one SIP peer and the current status.\n"
12977 " Option \"load\" forces lookup of peer in realtime storage.\n";
12978 return NULL;
12979 case CLI_GENERATE:
12980 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
12982 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
12985 /*! \brief list peer mailboxes to CLI */
12986 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
12988 struct sip_mailbox *mailbox;
12990 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
12991 ast_str_append(mailbox_str, 0, "%s%s%s%s",
12992 mailbox->mailbox,
12993 ast_strlen_zero(mailbox->context) ? "" : "@",
12994 S_OR(mailbox->context, ""),
12995 AST_LIST_NEXT(mailbox, entry) ? "," : "");
12999 /*! \brief Show one peer in detail (main function) */
13000 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13002 char status[30] = "";
13003 char cbuf[256];
13004 struct sip_peer *peer;
13005 char codec_buf[512];
13006 struct ast_codec_pref *pref;
13007 struct ast_variable *v;
13008 struct sip_auth *auth;
13009 int x = 0, codec = 0, load_realtime;
13010 int realtimepeers;
13012 realtimepeers = ast_check_realtime("sippeers");
13014 if (argc < 4)
13015 return CLI_SHOWUSAGE;
13017 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13018 peer = find_peer(argv[3], NULL, load_realtime, TRUE);
13019 if (s) { /* Manager */
13020 if (peer) {
13021 const char *id = astman_get_header(m, "ActionID");
13023 astman_append(s, "Response: Success\r\n");
13024 if (!ast_strlen_zero(id))
13025 astman_append(s, "ActionID: %s\r\n", id);
13026 } else {
13027 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
13028 astman_send_error(s, m, cbuf);
13029 return CLI_SUCCESS;
13032 if (peer && type==0 ) { /* Normal listing */
13033 struct ast_str *mailbox_str = ast_str_alloca(512);
13034 ast_cli(fd, "\n\n");
13035 ast_cli(fd, " * Name : %s\n", peer->name);
13036 if (realtimepeers) { /* Realtime is enabled */
13037 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
13039 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
13040 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
13041 for (auth = peer->auth; auth; auth = auth->next) {
13042 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
13043 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
13045 ast_cli(fd, " Context : %s\n", peer->context);
13046 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
13047 ast_cli(fd, " Language : %s\n", peer->language);
13048 if (!ast_strlen_zero(peer->accountcode))
13049 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
13050 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
13051 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
13052 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
13053 if (!ast_strlen_zero(peer->fromuser))
13054 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
13055 if (!ast_strlen_zero(peer->fromdomain))
13056 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
13057 ast_cli(fd, " Callgroup : ");
13058 print_group(fd, peer->callgroup, 0);
13059 ast_cli(fd, " Pickupgroup : ");
13060 print_group(fd, peer->pickupgroup, 0);
13061 peer_mailboxes_to_str(&mailbox_str, peer);
13062 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
13063 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
13064 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
13065 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
13066 if (peer->busy_level)
13067 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
13068 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
13069 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
13070 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
13071 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
13072 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
13073 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
13074 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
13075 ast_cli(fd, " T38 pt UDPTL : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)));
13076 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
13077 ast_cli(fd, " T38 pt RTP : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)));
13078 ast_cli(fd, " T38 pt TCP : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)));
13079 #endif
13080 ast_cli(fd, " CanReinvite : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
13081 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
13082 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
13083 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
13084 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
13085 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
13086 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
13087 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
13088 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
13089 if (peer->outboundproxy)
13090 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
13091 peer->outboundproxy->force ? "(forced)" : "");
13093 /* - is enumerated */
13094 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
13095 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
13096 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
13097 ast_cli(fd, " ToHost : %s\n", peer->tohost);
13098 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
13099 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
13100 ast_cli(fd, " Transport : %s\n", get_transport(peer->socket.type));
13101 if (!ast_strlen_zero(global_regcontext))
13102 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
13103 ast_cli(fd, " Def. Username: %s\n", peer->username);
13104 ast_cli(fd, " SIP Options : ");
13105 if (peer->sipoptions) {
13106 int lastoption = -1;
13107 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
13108 if (sip_options[x].id != lastoption) {
13109 if (peer->sipoptions & sip_options[x].id)
13110 ast_cli(fd, "%s ", sip_options[x].text);
13111 lastoption = x;
13114 } else
13115 ast_cli(fd, "(none)");
13117 ast_cli(fd, "\n");
13118 ast_cli(fd, " Codecs : ");
13119 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
13120 ast_cli(fd, "%s\n", codec_buf);
13121 ast_cli(fd, " Codec Order : (");
13122 print_codec_to_cli(fd, &peer->prefs);
13123 ast_cli(fd, ")\n");
13125 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
13126 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
13127 ast_cli(fd, " Status : ");
13128 peer_status(peer, status, sizeof(status));
13129 ast_cli(fd, "%s\n", status);
13130 ast_cli(fd, " Useragent : %s\n", peer->useragent);
13131 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
13132 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
13133 if (peer->chanvars) {
13134 ast_cli(fd, " Variables :\n");
13135 for (v = peer->chanvars ; v ; v = v->next)
13136 ast_cli(fd, " %s = %s\n", v->name, v->value);
13139 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
13140 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
13141 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
13142 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
13143 ast_cli(fd, "\n");
13144 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
13145 } else if (peer && type == 1) { /* manager listing */
13146 char buf[256];
13147 struct ast_str *mailbox_str = ast_str_alloca(512);
13148 astman_append(s, "Channeltype: SIP\r\n");
13149 astman_append(s, "ObjectName: %s\r\n", peer->name);
13150 astman_append(s, "ChanObjectType: peer\r\n");
13151 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
13152 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
13153 astman_append(s, "Context: %s\r\n", peer->context);
13154 astman_append(s, "Language: %s\r\n", peer->language);
13155 if (!ast_strlen_zero(peer->accountcode))
13156 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
13157 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
13158 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
13159 if (!ast_strlen_zero(peer->fromuser))
13160 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
13161 if (!ast_strlen_zero(peer->fromdomain))
13162 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
13163 astman_append(s, "Callgroup: ");
13164 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
13165 astman_append(s, "Pickupgroup: ");
13166 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
13167 peer_mailboxes_to_str(&mailbox_str, peer);
13168 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
13169 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
13170 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
13171 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
13172 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
13173 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
13174 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
13175 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
13176 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
13177 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
13178 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
13179 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
13180 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
13181 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
13182 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
13183 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
13184 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
13185 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
13186 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
13187 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
13188 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
13190 /* - is enumerated */
13191 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
13192 astman_append(s, "ToHost: %s\r\n", peer->tohost);
13193 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
13194 astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
13195 astman_append(s, "Default-Username: %s\r\n", peer->username);
13196 if (!ast_strlen_zero(global_regcontext))
13197 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
13198 astman_append(s, "Codecs: ");
13199 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
13200 astman_append(s, "%s\r\n", codec_buf);
13201 astman_append(s, "CodecOrder: ");
13202 pref = &peer->prefs;
13203 for(x = 0; x < 32 ; x++) {
13204 codec = ast_codec_pref_index(pref, x);
13205 if (!codec)
13206 break;
13207 astman_append(s, "%s", ast_getformatname(codec));
13208 if (x < 31 && ast_codec_pref_index(pref, x+1))
13209 astman_append(s, ",");
13212 astman_append(s, "\r\n");
13213 astman_append(s, "Status: ");
13214 peer_status(peer, status, sizeof(status));
13215 astman_append(s, "%s\r\n", status);
13216 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
13217 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
13218 astman_append(s, "QualifyFreq : %d ms\n", peer->qualifyfreq);
13219 if (peer->chanvars) {
13220 for (v = peer->chanvars ; v ; v = v->next) {
13221 astman_append(s, "ChanVariable:\n");
13222 astman_append(s, " %s,%s\r\n", v->name, v->value);
13226 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
13228 } else {
13229 ast_cli(fd, "Peer %s not found.\n", argv[3]);
13230 ast_cli(fd, "\n");
13233 return CLI_SUCCESS;
13236 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13238 char cbuf[2256];
13239 struct ast_cb_names cbnames = {9, { "retrans_pkt",
13240 "__sip_autodestruct",
13241 "expire_register",
13242 "auto_congest",
13243 "sip_reg_timeout",
13244 "sip_poke_peer_s",
13245 "sip_poke_noanswer",
13246 "sip_reregister",
13247 "sip_reinvite_retry"},
13248 { retrans_pkt,
13249 __sip_autodestruct,
13250 expire_register,
13251 auto_congest,
13252 sip_reg_timeout,
13253 sip_poke_peer_s,
13254 sip_poke_noanswer,
13255 sip_reregister,
13256 sip_reinvite_retry}};
13258 switch (cmd) {
13259 case CLI_INIT:
13260 e->command = "sip show sched";
13261 e->usage =
13262 "Usage: sip show sched\n"
13263 " Shows stats on what's in the sched queue at the moment\n";
13264 return NULL;
13265 case CLI_GENERATE:
13266 return NULL;
13268 ast_cli(a->fd, "\n");
13269 ast_sched_report(sched, cbuf, sizeof(cbuf), &cbnames);
13270 ast_cli(a->fd, "%s", cbuf);
13271 return CLI_SUCCESS;
13274 /*! \brief Show SIP Registry (registrations with other SIP proxies */
13275 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13277 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
13278 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
13279 char host[80];
13280 char tmpdat[256];
13281 struct ast_tm tm;
13282 int counter = 0;
13284 switch (cmd) {
13285 case CLI_INIT:
13286 e->command = "sip show registry";
13287 e->usage =
13288 "Usage: sip show registry\n"
13289 " Lists all registration requests and status.\n";
13290 return NULL;
13291 case CLI_GENERATE:
13292 return NULL;
13295 if (a->argc != 3)
13296 return CLI_SHOWUSAGE;
13297 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
13299 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
13300 ASTOBJ_RDLOCK(iterator);
13301 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
13302 if (iterator->regtime.tv_sec) {
13303 ast_localtime(&iterator->regtime, &tm, NULL);
13304 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
13305 } else
13306 tmpdat[0] = '\0';
13307 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
13308 ASTOBJ_UNLOCK(iterator);
13309 counter++;
13310 } while(0));
13311 ast_cli(a->fd, "%d SIP registrations.\n", counter);
13312 return CLI_SUCCESS;
13313 #undef FORMAT
13314 #undef FORMAT2
13317 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
13318 \note This function does not tell the SIP device what's going on,
13319 so use it with great care.
13321 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13323 struct sip_peer *peer;
13324 int load_realtime = 0;
13326 switch (cmd) {
13327 case CLI_INIT:
13328 e->command = "sip unregister";
13329 e->usage =
13330 "Usage: sip unregister <peer>\n"
13331 " Unregister (force expiration) a SIP peer from the registry\n";
13332 return NULL;
13333 case CLI_GENERATE:
13334 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
13337 if (a->argc != 3)
13338 return CLI_SHOWUSAGE;
13340 if ((peer = find_peer(a->argv[2], NULL, load_realtime, TRUE))) {
13341 if (peer->expire > 0) {
13342 expire_register(peer);
13343 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
13344 } else {
13345 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
13347 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
13348 } else {
13349 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
13352 return CLI_SUCCESS;
13355 /*! \brief Callback for show_chanstats */
13356 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
13358 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s (%-2.2s) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
13359 #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u\n"
13360 struct sip_pvt *cur = __cur;
13361 unsigned int rxcount;
13362 unsigned int txcount;
13363 char durbuf[10];
13364 int duration;
13365 int durh, durm, durs;
13366 struct ast_channel *c = cur->owner;
13367 struct __show_chan_arg *arg = __arg;
13368 int fd = arg->fd;
13371 if (cur->subscribed != NONE) /* Subscriptions */
13372 return 0; /* don't care, we scan all channels */
13374 if (!cur->rtp) {
13375 if (sipdebug)
13376 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n", ast_inet_ntoa(cur->sa.sin_addr), cur->callid, invitestate2string[cur->invitestate].desc, "-- No RTP active");
13377 return 0; /* don't care, we scan all channels */
13379 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
13380 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
13382 /* Find the duration of this channel */
13383 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
13384 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
13385 durh = duration / 3600;
13386 durm = (duration % 3600) / 60;
13387 durs = duration % 60;
13388 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
13389 } else {
13390 durbuf[0] = '\0';
13392 /* Print stats for every call with RTP */
13393 ast_cli(fd, FORMAT,
13394 ast_inet_ntoa(cur->sa.sin_addr),
13395 cur->callid,
13396 durbuf,
13397 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
13398 rxcount > (unsigned int) 100000 ? "K":" ",
13399 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS),
13400 rxcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) / rxcount * 100) : 0,
13401 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
13402 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
13403 txcount > (unsigned int) 100000 ? "K":" ",
13404 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS),
13405 txcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS)/ txcount * 100) : 0,
13406 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
13408 arg->numchans++;
13410 return 0; /* don't care, we scan all channels */
13413 /*! \brief SIP show channelstats CLI (main function) */
13414 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13416 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
13418 switch (cmd) {
13419 case CLI_INIT:
13420 e->command = "sip show channelstats";
13421 e->usage =
13422 "Usage: sip show channelstats\n"
13423 " Lists all currently active SIP channel's RTCP statistics.\n"
13424 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
13425 return NULL;
13426 case CLI_GENERATE:
13427 return NULL;
13430 if (a->argc != 3)
13431 return CLI_SHOWUSAGE;
13433 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "%", "Jitter", "Send: Pack", "Lost", "Jitter");
13434 /* iterate on the container and invoke the callback on each item */
13435 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
13436 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
13437 return CLI_SUCCESS;
13439 #undef FORMAT
13440 #undef FORMAT2
13442 /*! \brief List global settings for the SIP channel */
13443 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13445 int realtimepeers;
13446 int realtimeregs;
13447 char codec_buf[SIPBUFSIZE];
13448 const char *msg; /* temporary msg pointer */
13450 switch (cmd) {
13451 case CLI_INIT:
13452 e->command = "sip show settings";
13453 e->usage =
13454 "Usage: sip show settings\n"
13455 " Provides detailed list of the configuration of the SIP channel.\n";
13456 return NULL;
13457 case CLI_GENERATE:
13458 return NULL;
13462 realtimepeers = ast_check_realtime("sippeers");
13463 realtimeregs = ast_check_realtime("sipregs");
13465 if (a->argc != 3)
13466 return CLI_SHOWUSAGE;
13467 ast_cli(a->fd, "\n\nGlobal Settings:\n");
13468 ast_cli(a->fd, "----------------\n");
13469 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
13470 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
13471 ast_cli(a->fd, " TCP SIP Port: ");
13472 if (sip_tcp_desc.sin.sin_family != AF_INET) {
13473 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.sin.sin_port));
13474 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.sin.sin_addr));
13475 } else {
13476 ast_cli(a->fd, "Disabled\n");
13478 ast_cli(a->fd, " TLS SIP Port: ");
13479 if (default_tls_cfg.enabled != FALSE) {
13480 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.sin.sin_port));
13481 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.sin.sin_addr));
13482 } else {
13483 ast_cli(a->fd, "Disabled\n");
13485 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
13486 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
13487 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(autocreatepeer));
13488 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
13489 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(global_allowguest));
13490 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
13491 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
13492 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
13493 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
13494 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
13495 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
13496 ast_cli(a->fd, " Our auth realm %s\n", global_realm);
13497 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
13498 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
13499 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(global_alwaysauthreject));
13500 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(global_directrtpsetup));
13501 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
13502 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
13503 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
13504 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
13505 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(global_regextenonqualify));
13506 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
13507 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
13508 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
13509 ast_cli(a->fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
13510 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
13512 ast_cli(a->fd, " T38 fax pt UDPTL: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)));
13513 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
13514 ast_cli(a->fd, " T38 fax pt RTP: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP)));
13515 ast_cli(a->fd, " T38 fax pt TCP: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP)));
13516 #endif
13517 if (!realtimepeers && !realtimeregs)
13518 ast_cli(a->fd, " SIP realtime: Disabled\n" );
13519 else
13520 ast_cli(a->fd, " SIP realtime: Enabled\n" );
13521 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
13522 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
13523 ast_cli(a->fd, "---------------------------\n");
13524 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
13525 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
13526 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
13527 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
13528 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
13529 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
13530 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
13531 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
13532 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
13533 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
13534 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
13535 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
13536 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
13537 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
13539 ast_cli(a->fd, "\nNetwork Settings:\n");
13540 ast_cli(a->fd, "---------------------------\n");
13541 /* determine if/how SIP address can be remapped */
13542 if (localaddr == NULL)
13543 msg = "Disabled, no localnet list";
13544 else if (externip.sin_addr.s_addr == 0)
13545 msg = "Disabled, externip is 0.0.0.0";
13546 else if (stunaddr.sin_addr.s_addr != 0)
13547 msg = "Enabled using STUN";
13548 else if (!ast_strlen_zero(externhost))
13549 msg = "Enabled using externhost";
13550 else
13551 msg = "Enabled using externip";
13552 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
13553 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
13554 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
13555 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
13556 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
13558 struct ast_ha *d;
13559 const char *prefix = "Localnet:";
13560 char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
13562 for (d = localaddr; d ; prefix = "", d = d->next) {
13563 ast_cli(a->fd, " %-24s%s/%s\n",
13564 prefix, ast_inet_ntoa(d->netaddr),
13565 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
13568 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
13570 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
13571 ast_cli(a->fd, "---------------------------\n");
13572 ast_cli(a->fd, " Codecs: ");
13573 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
13574 ast_cli(a->fd, "%s\n", codec_buf);
13575 ast_cli(a->fd, " Codec Order: ");
13576 print_codec_to_cli(a->fd, &default_prefs);
13577 ast_cli(a->fd, "\n");
13578 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
13579 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
13580 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(compactheaders));
13581 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
13582 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
13583 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
13584 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
13585 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(global_srvlookup));
13586 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(pedanticsipchecking));
13587 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
13588 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
13589 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
13590 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
13591 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
13592 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(global_notifyringing));
13593 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(global_notifyhold));
13594 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
13595 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
13596 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
13597 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
13598 global_outboundproxy.force ? "(forced)" : "");
13599 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
13600 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
13601 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
13602 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
13603 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
13604 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
13605 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
13607 ast_cli(a->fd, "\nDefault Settings:\n");
13608 ast_cli(a->fd, "-----------------\n");
13609 ast_cli(a->fd, " Context: %s\n", default_context);
13610 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
13611 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
13612 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
13613 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
13614 ast_cli(a->fd, " Progress inband: %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
13615 ast_cli(a->fd, " Language: %s\n", default_language);
13616 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
13617 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
13618 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
13621 if (realtimepeers || realtimeregs) {
13622 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
13623 ast_cli(a->fd, "----------------------\n");
13624 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
13625 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
13626 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
13627 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
13628 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
13629 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
13630 ast_cli(a->fd, " Auto Clear: %d\n", global_rtautoclear);
13632 ast_cli(a->fd, "\n----\n");
13633 return CLI_SUCCESS;
13636 /*! \brief Show subscription type in string format */
13637 static const char *subscription_type2str(enum subscriptiontype subtype)
13639 int i;
13641 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
13642 if (subscription_types[i].type == subtype) {
13643 return subscription_types[i].text;
13646 return subscription_types[0].text;
13649 /*! \brief Find subscription type in array */
13650 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
13652 int i;
13654 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
13655 if (subscription_types[i].type == subtype) {
13656 return &subscription_types[i];
13659 return &subscription_types[0];
13663 * We try to structure all functions that loop on data structures as
13664 * a handler for individual entries, and a mainloop that iterates
13665 * on the main data structure. This way, moving the code to containers
13666 * that support iteration through callbacks will be a lot easier.
13669 #define FORMAT4 "%-15.15s %-10.10s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
13670 #define FORMAT3 "%-15.15s %-10.10s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
13671 #define FORMAT2 "%-15.15s %-10.10s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
13672 #define FORMAT "%-15.15s %-10.10s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
13674 /*! \brief callback for show channel|subscription */
13675 static int show_channels_cb(void *__cur, void *__arg, int flags)
13677 struct sip_pvt *cur = __cur;
13678 struct __show_chan_arg *arg = __arg;
13679 const struct sockaddr_in *dst = sip_real_dst(cur);
13681 /* XXX indentation preserved to reduce diff. Will be fixed later */
13682 if (cur->subscribed == NONE && !arg->subscriptions) {
13683 /* set if SIP transfer in progress */
13684 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
13685 char formatbuf[SIPBUFSIZE/2];
13687 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
13688 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
13689 cur->callid,
13690 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
13691 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
13692 cur->needdestroy ? "(d)" : "",
13693 cur->lastmsg ,
13694 referstatus
13696 arg->numchans++;
13698 if (cur->subscribed != NONE && arg->subscriptions) {
13699 struct ast_str *mailbox_str = ast_str_alloca(512);
13700 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
13701 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
13702 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
13703 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
13704 cur->callid,
13705 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
13706 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
13707 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
13708 subscription_type2str(cur->subscribed),
13709 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
13710 cur->expiry
13712 arg->numchans++;
13714 return 0; /* don't care, we scan all channels */
13717 /*! \brief CLI for show channels or subscriptions.
13718 * This is a new-style CLI handler so a single function contains
13719 * the prototype for the function, the 'generator' to produce multiple
13720 * entries in case it is required, and the actual handler for the command.
13722 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13724 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
13727 if (cmd == CLI_INIT) {
13728 e->command = "sip show {channels|subscriptions}";
13729 e->usage =
13730 "Usage: sip show channels\n"
13731 " Lists all currently active SIP calls (dialogs).\n"
13732 "Usage: sip show subscriptions\n"
13733 " Lists active SIP subscriptions.\n";
13734 return NULL;
13735 } else if (cmd == CLI_GENERATE)
13736 return NULL;
13738 if (a->argc != e->args)
13739 return CLI_SHOWUSAGE;
13740 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
13741 if (!arg.subscriptions)
13742 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
13743 else
13744 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
13746 /* iterate on the container and invoke the callback on each item */
13747 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
13749 /* print summary information */
13750 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
13751 (arg.subscriptions ? "subscription" : "dialog"),
13752 ESS(arg.numchans)); /* ESS(n) returns an "s" if n>1 */
13753 return CLI_SUCCESS;
13754 #undef FORMAT
13755 #undef FORMAT2
13756 #undef FORMAT3
13759 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
13760 * This is in charge of generating all strings that match a prefix in the
13761 * given position. As many functions of this kind, each invokation has
13762 * O(state) time complexity so be careful in using it.
13764 static char *complete_sipch(const char *line, const char *word, int pos, int state)
13766 int which=0;
13767 struct sip_pvt *cur;
13768 char *c = NULL;
13769 int wordlen = strlen(word);
13770 struct ao2_iterator i;
13772 if (pos != 3) {
13773 return NULL;
13776 i = ao2_iterator_init(dialogs, 0);
13778 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
13779 sip_pvt_lock(cur);
13780 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
13781 c = ast_strdup(cur->callid);
13782 sip_pvt_unlock(cur);
13783 dialog_unref(cur, "drop ref in iterator loop break");
13784 break;
13786 sip_pvt_unlock(cur);
13787 dialog_unref(cur, "drop ref in iterator loop");
13789 return c;
13793 /*! \brief Do completion on peer name */
13794 static char *complete_sip_peer(const char *word, int state, int flags2)
13796 char *result = NULL;
13797 int wordlen = strlen(word);
13798 int which = 0;
13799 struct ao2_iterator i = ao2_iterator_init(peers, 0);
13800 struct sip_peer *peer;
13802 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13803 /* locking of the object is not required because only the name and flags are being compared */
13804 if (!strncasecmp(word, peer->name, wordlen) &&
13805 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
13806 ++which > state)
13807 result = ast_strdup(peer->name);
13808 unref_peer(peer, "toss iterator peer ptr before break");
13809 if (result) {
13810 break;
13813 return result;
13816 /*! \brief Do completion on registered peer name */
13817 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
13819 char *result = NULL;
13820 int wordlen = strlen(word);
13821 int which = 0;
13822 struct ao2_iterator i;
13823 struct sip_peer *peer;
13825 i = ao2_iterator_init(peers, 0);
13826 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13827 if (!strncasecmp(word, peer->name, wordlen) &&
13828 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
13829 ++which > state && peer->expire > 0)
13830 result = ast_strdup(peer->name);
13831 if (result) {
13832 unref_peer(peer, "toss iterator peer ptr before break");
13833 break;
13835 unref_peer(peer, "toss iterator peer ptr");
13837 return result;
13840 /*! \brief Support routine for 'sip show history' CLI */
13841 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
13843 if (pos == 3)
13844 return complete_sipch(line, word, pos, state);
13846 return NULL;
13849 /*! \brief Support routine for 'sip show peer' CLI */
13850 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
13852 if (pos == 3) {
13853 return complete_sip_peer(word, state, 0);
13856 return NULL;
13859 /*! \brief Support routine for 'sip unregister' CLI */
13860 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
13862 if (pos == 2)
13863 return complete_sip_registered_peer(word, state, 0);
13865 return NULL;
13868 /*! \brief Support routine for 'sip notify' CLI */
13869 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
13871 char *c = NULL;
13873 if (pos == 2) {
13874 int which = 0;
13875 char *cat = NULL;
13876 int wordlen = strlen(word);
13878 /* do completion for notify type */
13880 if (!notify_types)
13881 return NULL;
13883 while ( (cat = ast_category_browse(notify_types, cat)) ) {
13884 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
13885 c = ast_strdup(cat);
13886 break;
13889 return c;
13892 if (pos > 2)
13893 return complete_sip_peer(word, state, 0);
13895 return NULL;
13898 /*! \brief Show details of one active dialog */
13899 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13901 struct sip_pvt *cur;
13902 size_t len;
13903 int found = 0;
13904 struct ao2_iterator i;
13906 switch (cmd) {
13907 case CLI_INIT:
13908 e->command = "sip show channel";
13909 e->usage =
13910 "Usage: sip show channel <call-id>\n"
13911 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
13912 return NULL;
13913 case CLI_GENERATE:
13914 return complete_sipch(a->line, a->word, a->pos, a->n);
13917 if (a->argc != 4)
13918 return CLI_SHOWUSAGE;
13919 len = strlen(a->argv[3]);
13921 i = ao2_iterator_init(dialogs, 0);
13923 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
13924 sip_pvt_lock(cur);
13926 if (!strncasecmp(cur->callid, a->argv[3], len)) {
13927 char formatbuf[SIPBUFSIZE/2];
13928 ast_cli(a->fd, "\n");
13929 if (cur->subscribed != NONE)
13930 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
13931 else
13932 ast_cli(a->fd, " * SIP Call\n");
13933 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
13934 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
13935 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
13936 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
13937 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
13938 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
13939 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
13940 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
13941 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
13942 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
13943 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
13944 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
13945 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
13946 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
13947 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
13948 ast_cli(a->fd, " Audio IP: %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
13949 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
13950 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
13951 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
13952 if (!ast_strlen_zero(cur->username))
13953 ast_cli(a->fd, " Username: %s\n", cur->username);
13954 if (!ast_strlen_zero(cur->peername))
13955 ast_cli(a->fd, " Peername: %s\n", cur->peername);
13956 if (!ast_strlen_zero(cur->uri))
13957 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
13958 if (!ast_strlen_zero(cur->cid_num))
13959 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
13960 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
13961 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
13962 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
13963 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
13964 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
13965 ast_cli(a->fd, " SIP Options: ");
13966 if (cur->sipoptions) {
13967 int x;
13968 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
13969 if (cur->sipoptions & sip_options[x].id)
13970 ast_cli(a->fd, "%s ", sip_options[x].text);
13972 ast_cli(a->fd, "\n");
13973 } else
13974 ast_cli(a->fd, "(none)\n");
13976 if (!cur->stimer)
13977 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
13978 else {
13979 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
13980 if (cur->stimer->st_active == TRUE) {
13981 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
13982 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
13983 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
13984 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
13985 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
13986 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
13987 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
13988 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
13989 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
13993 ast_cli(a->fd, "\n\n");
13995 found++;
13998 sip_pvt_unlock(cur);
14000 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
14003 if (!found)
14004 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
14006 return CLI_SUCCESS;
14009 /*! \brief Show history details of one dialog */
14010 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14012 struct sip_pvt *cur;
14013 size_t len;
14014 int found = 0;
14015 struct ao2_iterator i;
14017 switch (cmd) {
14018 case CLI_INIT:
14019 e->command = "sip show history";
14020 e->usage =
14021 "Usage: sip show history <call-id>\n"
14022 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
14023 return NULL;
14024 case CLI_GENERATE:
14025 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
14028 if (a->argc != 4)
14029 return CLI_SHOWUSAGE;
14031 if (!recordhistory)
14032 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
14034 len = strlen(a->argv[3]);
14036 i = ao2_iterator_init(dialogs, 0);
14037 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14038 sip_pvt_lock(cur);
14039 if (!strncasecmp(cur->callid, a->argv[3], len)) {
14040 struct sip_history *hist;
14041 int x = 0;
14043 ast_cli(a->fd, "\n");
14044 if (cur->subscribed != NONE)
14045 ast_cli(a->fd, " * Subscription\n");
14046 else
14047 ast_cli(a->fd, " * SIP Call\n");
14048 if (cur->history)
14049 AST_LIST_TRAVERSE(cur->history, hist, list)
14050 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
14051 if (x == 0)
14052 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
14053 found++;
14055 sip_pvt_unlock(cur);
14056 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
14059 if (!found)
14060 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
14062 return CLI_SUCCESS;
14065 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
14066 static void sip_dump_history(struct sip_pvt *dialog)
14068 int x = 0;
14069 struct sip_history *hist;
14070 static int errmsg = 0;
14072 if (!dialog)
14073 return;
14075 if (!option_debug && !sipdebug) {
14076 if (!errmsg) {
14077 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
14078 errmsg = 1;
14080 return;
14083 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
14084 if (dialog->subscribed)
14085 ast_debug(1, " * Subscription\n");
14086 else
14087 ast_debug(1, " * SIP Call\n");
14088 if (dialog->history)
14089 AST_LIST_TRAVERSE(dialog->history, hist, list)
14090 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
14091 if (!x)
14092 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
14093 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
14097 /*! \brief Receive SIP INFO Message */
14098 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
14100 char buf[1024];
14101 unsigned int event;
14102 const char *c = get_header(req, "Content-Type");
14104 /* Need to check the media/type */
14105 if (!strcasecmp(c, "application/dtmf-relay") ||
14106 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
14107 unsigned int duration = 0;
14109 if (!p->owner) { /* not a PBX call */
14110 transmit_response(p, "481 Call leg/transaction does not exist", req);
14111 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14112 return;
14115 /* Try getting the "signal=" part */
14116 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
14117 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
14118 transmit_response(p, "200 OK", req); /* Should return error */
14119 return;
14120 } else {
14121 ast_copy_string(buf, c, sizeof(buf));
14124 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
14125 duration = atoi(c);
14126 if (!duration)
14127 duration = 100; /* 100 ms */
14130 if (ast_strlen_zero(buf)) {
14131 transmit_response(p, "200 OK", req);
14132 return;
14135 if (buf[0] == '*')
14136 event = 10;
14137 else if (buf[0] == '#')
14138 event = 11;
14139 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
14140 event = 12 + buf[0] - 'A';
14141 else if (buf[0] == '!')
14142 event = 16;
14143 else
14144 event = atoi(buf);
14145 if (event == 16) {
14146 /* send a FLASH event */
14147 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
14148 ast_queue_frame(p->owner, &f);
14149 if (sipdebug)
14150 ast_verbose("* DTMF-relay event received: FLASH\n");
14151 } else {
14152 /* send a DTMF event */
14153 struct ast_frame f = { AST_FRAME_DTMF, };
14154 if (event < 10) {
14155 f.subclass = '0' + event;
14156 } else if (event < 11) {
14157 f.subclass = '*';
14158 } else if (event < 12) {
14159 f.subclass = '#';
14160 } else if (event < 16) {
14161 f.subclass = 'A' + (event - 12);
14163 f.len = duration;
14164 ast_queue_frame(p->owner, &f);
14165 if (sipdebug)
14166 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
14168 transmit_response(p, "200 OK", req);
14169 return;
14170 } else if (!strcasecmp(c, "application/dtmf")) {
14171 /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
14172 unsigned int duration = 0;
14174 if (!p->owner) { /* not a PBX call */
14175 transmit_response(p, "481 Call leg/transaction does not exist", req);
14176 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14177 return;
14180 get_msg_text(buf, sizeof(buf), req, TRUE);
14181 duration = 100; /* 100 ms */
14183 if (ast_strlen_zero(buf)) {
14184 transmit_response(p, "200 OK", req);
14185 return;
14187 event = atoi(buf);
14188 if (event == 16) {
14189 /* send a FLASH event */
14190 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
14191 ast_queue_frame(p->owner, &f);
14192 if (sipdebug)
14193 ast_verbose("* DTMF-relay event received: FLASH\n");
14194 } else {
14195 /* send a DTMF event */
14196 struct ast_frame f = { AST_FRAME_DTMF, };
14197 if (event < 10) {
14198 f.subclass = '0' + event;
14199 } else if (event < 11) {
14200 f.subclass = '*';
14201 } else if (event < 12) {
14202 f.subclass = '#';
14203 } else if (event < 16) {
14204 f.subclass = 'A' + (event - 12);
14206 f.len = duration;
14207 ast_queue_frame(p->owner, &f);
14208 if (sipdebug)
14209 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
14211 transmit_response(p, "200 OK", req);
14212 return;
14214 } else if (!strcasecmp(c, "application/media_control+xml")) {
14215 /* Eh, we'll just assume it's a fast picture update for now */
14216 if (p->owner)
14217 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
14218 transmit_response(p, "200 OK", req);
14219 return;
14220 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
14221 /* Client code (from SNOM phone) */
14222 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
14223 if (p->owner && p->owner->cdr)
14224 ast_cdr_setuserfield(p->owner, c);
14225 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
14226 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
14227 transmit_response(p, "200 OK", req);
14228 } else {
14229 transmit_response(p, "403 Forbidden", req);
14231 return;
14232 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
14233 /* INFO messages generated by some phones to start/stop recording
14234 on phone calls.
14235 OEJ: I think this should be something that is enabled/disabled
14236 per device. I don't want incoming callers to record calls in my
14237 pbx.
14239 /* first, get the feature string, if it exists */
14240 struct ast_call_feature *feat;
14241 int j;
14242 struct ast_frame f = { AST_FRAME_DTMF, };
14244 ast_rdlock_call_features();
14245 feat = ast_find_call_feature("automon");
14246 if (!feat || ast_strlen_zero(feat->exten)) {
14247 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
14248 /* 403 means that we don't support this feature, so don't request it again */
14249 transmit_response(p, "403 Forbidden", req);
14250 ast_unlock_call_features();
14251 return;
14253 /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
14254 f.len = 100;
14255 for (j=0; j < strlen(feat->exten); j++) {
14256 f.subclass = feat->exten[j];
14257 ast_queue_frame(p->owner, &f);
14258 if (sipdebug)
14259 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
14261 ast_unlock_call_features();
14263 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
14264 transmit_response(p, "200 OK", req);
14265 return;
14266 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
14267 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
14268 transmit_response(p, "200 OK", req);
14269 return;
14272 /* Other type of INFO message, not really understood by Asterisk */
14273 /* if (get_msg_text(buf, sizeof(buf), req)) { */
14275 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
14276 transmit_response(p, "415 Unsupported media type", req);
14277 return;
14280 /*! \brief Enable SIP Debugging for a single IP */
14281 static char *sip_do_debug_ip(int fd, char *arg)
14283 struct hostent *hp;
14284 struct ast_hostent ahp;
14285 int port = 0;
14286 char *p;
14288 p = arg;
14289 strsep(&p, ":");
14290 if (p)
14291 port = atoi(p);
14292 hp = ast_gethostbyname(arg, &ahp);
14293 if (hp == NULL)
14294 return CLI_SHOWUSAGE;
14296 debugaddr.sin_family = AF_INET;
14297 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
14298 debugaddr.sin_port = htons(port);
14299 if (port == 0)
14300 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
14301 else
14302 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
14304 sipdebug |= sip_debug_console;
14306 return CLI_SUCCESS;
14309 /*! \brief Turn on SIP debugging for a given peer */
14310 static char *sip_do_debug_peer(int fd, char *arg)
14312 struct sip_peer *peer = find_peer(arg, NULL, TRUE, TRUE);
14313 if (!peer)
14314 ast_cli(fd, "No such peer '%s'\n", arg);
14315 else if (peer->addr.sin_addr.s_addr == 0)
14316 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
14317 else {
14318 debugaddr.sin_family = AF_INET;
14319 debugaddr.sin_addr = peer->addr.sin_addr;
14320 debugaddr.sin_port = peer->addr.sin_port;
14321 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
14322 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
14323 sipdebug |= sip_debug_console;
14325 if (peer)
14326 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
14327 return CLI_SUCCESS;
14330 /*! \brief Turn on SIP debugging (CLI command) */
14331 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14333 int oldsipdebug = sipdebug & sip_debug_console;
14334 char *what;
14336 if (cmd == CLI_INIT) {
14337 e->command = "sip set debug {on|off|ip|peer}";
14338 e->usage =
14339 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
14340 " Globally disables dumping of SIP packets,\n"
14341 " or enables it either globally or for a (single)\n"
14342 " IP address or registered peer.\n";
14343 return NULL;
14344 } else if (cmd == CLI_GENERATE) {
14345 if (a->pos == 4 && strcasestr(a->line, " peer")) /* XXX should check on argv too */
14346 return complete_sip_peer(a->word, a->n, 0);
14347 return NULL;
14350 what = a->argv[e->args-1]; /* guaranteed to exist */
14351 if (a->argc == e->args) { /* on/off */
14352 if (!strcasecmp(what, "on")) {
14353 sipdebug |= sip_debug_console;
14354 sipdebug_text = 1; /*! \note this can be a special debug command - "sip debug text" or something */
14355 memset(&debugaddr, 0, sizeof(debugaddr));
14356 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
14357 return CLI_SUCCESS;
14358 } else if (!strcasecmp(what, "off")) {
14359 sipdebug &= ~sip_debug_console;
14360 sipdebug_text = 0;
14361 ast_cli(a->fd, "SIP Debugging Disabled\n");
14362 return CLI_SUCCESS;
14364 } else if (a->argc == e->args +1) {/* ip/peer */
14365 if (!strcasecmp(what, "ip"))
14366 return sip_do_debug_ip(a->fd, a->argv[e->args]);
14367 else if (!strcasecmp(what, "peer"))
14368 return sip_do_debug_peer(a->fd, a->argv[e->args]);
14370 return CLI_SHOWUSAGE; /* default, failure */
14373 /*! \brief Cli command to send SIP notify to peer */
14374 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14376 struct ast_variable *varlist;
14377 int i;
14379 switch (cmd) {
14380 case CLI_INIT:
14381 e->command = "sip notify";
14382 e->usage =
14383 "Usage: sip notify <type> <peer> [<peer>...]\n"
14384 " Send a NOTIFY message to a SIP peer or peers\n"
14385 " Message types are defined in sip_notify.conf\n";
14386 return NULL;
14387 case CLI_GENERATE:
14388 return complete_sipnotify(a->line, a->word, a->pos, a->n);
14391 if (a->argc < 4)
14392 return CLI_SHOWUSAGE;
14394 if (!notify_types) {
14395 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
14396 return CLI_FAILURE;
14399 varlist = ast_variable_browse(notify_types, a->argv[2]);
14401 if (!varlist) {
14402 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
14403 return CLI_FAILURE;
14406 for (i = 3; i < a->argc; i++) {
14407 struct sip_pvt *p;
14409 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
14410 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
14411 return CLI_FAILURE;
14414 if (create_addr(p, a->argv[i], NULL)) {
14415 /* Maybe they're not registered, etc. */
14416 dialog_unlink_all(p, TRUE, TRUE);
14417 dialog_unref(p, "unref dialog inside for loop" );
14418 /* sip_destroy(p); */
14419 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
14420 continue;
14423 /* Notify is outgoing call */
14424 ast_set_flag(&p->flags[0], SIP_OUTGOING);
14426 /* Recalculate our side, and recalculate Call ID */
14427 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
14428 build_via(p);
14429 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
14430 build_callid_pvt(p);
14431 ao2_t_link(dialogs, p, "Linking in new name");
14432 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
14433 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
14434 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
14435 transmit_notify_custom(p, varlist);
14438 return CLI_SUCCESS;
14441 /*! \brief Enable/Disable SIP History logging (CLI) - deprecated. use sip_set_history instead */
14442 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14444 switch (cmd) {
14445 case CLI_INIT:
14446 e->command = "sip history [off]";
14447 e->usage =
14448 "Usage: sip history [off]\n"
14449 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
14450 " Use 'sip show history' to view the history of a call number.\n";
14451 return NULL;
14452 case CLI_GENERATE:
14453 return NULL;
14456 if (a->argc < 2 || a->argc > 3) {
14457 return CLI_SHOWUSAGE;
14459 if (a->argc == 2) {
14460 recordhistory = TRUE;
14461 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
14462 } else {
14463 if (strncasecmp(a->argv[2], "off", 3))
14464 return CLI_SHOWUSAGE;
14465 recordhistory = FALSE;
14466 ast_cli(a->fd, "SIP History Recording Disabled\n");
14468 return CLI_SUCCESS;
14471 /*! \brief Enable/Disable SIP History logging (CLI) */
14472 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14474 switch (cmd) {
14475 case CLI_INIT:
14476 e->command = "sip set history {on|off}";
14477 e->usage =
14478 "Usage: sip history {on|off}\n"
14479 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
14480 " Use 'sip show history' to view the history of a call number.\n";
14481 return NULL;
14482 case CLI_GENERATE:
14483 return NULL;
14486 if (a->argc != e->args)
14487 return CLI_SHOWUSAGE;
14489 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
14490 recordhistory = TRUE;
14491 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
14492 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
14493 recordhistory = FALSE;
14494 ast_cli(a->fd, "SIP History Recording Disabled\n");
14495 } else {
14496 return CLI_SHOWUSAGE;
14498 return CLI_SUCCESS;
14501 /*! \brief Authenticate for outbound registration */
14502 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
14504 char *header, *respheader;
14505 char digest[1024];
14507 p->authtries++;
14508 auth_headers(code, &header, &respheader);
14509 memset(digest, 0, sizeof(digest));
14510 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
14511 /* There's nothing to use for authentication */
14512 /* No digest challenge in request */
14513 if (sip_debug_test_pvt(p) && p->registry)
14514 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
14515 /* No old challenge */
14516 return -1;
14518 if (p->do_history)
14519 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
14520 if (sip_debug_test_pvt(p) && p->registry)
14521 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
14522 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
14525 /*! \brief Add authentication on outbound SIP packet */
14526 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
14528 char *header, *respheader;
14529 char digest[1024];
14531 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
14532 return -2;
14534 p->authtries++;
14535 auth_headers(code, &header, &respheader);
14536 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
14537 memset(digest, 0, sizeof(digest));
14538 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
14539 /* No way to authenticate */
14540 return -1;
14542 /* Now we have a reply digest */
14543 p->options->auth = digest;
14544 p->options->authheader = respheader;
14545 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
14548 /*! \brief reply to authentication for outbound registrations
14549 \return Returns -1 if we have no auth
14550 \note This is used for register= servers in sip.conf, SIP proxies we register
14551 with for receiving calls from. */
14552 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
14554 char tmp[512];
14555 char *c;
14556 char oldnonce[256];
14558 /* table of recognised keywords, and places where they should be copied */
14559 const struct x {
14560 const char *key;
14561 const ast_string_field *field;
14562 } *i, keys[] = {
14563 { "realm=", &p->realm },
14564 { "nonce=", &p->nonce },
14565 { "opaque=", &p->opaque },
14566 { "qop=", &p->qop },
14567 { "domain=", &p->domain },
14568 { NULL, 0 },
14571 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
14572 if (ast_strlen_zero(tmp))
14573 return -1;
14574 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
14575 ast_log(LOG_WARNING, "missing Digest.\n");
14576 return -1;
14578 c = tmp + strlen("Digest ");
14579 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
14580 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
14581 for (i = keys; i->key != NULL; i++) {
14582 char *src, *separator;
14583 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
14584 continue;
14585 /* Found. Skip keyword, take text in quotes or up to the separator. */
14586 c += strlen(i->key);
14587 if (*c == '"') {
14588 src = ++c;
14589 separator = "\"";
14590 } else {
14591 src = c;
14592 separator = ",";
14594 strsep(&c, separator); /* clear separator and move ptr */
14595 ast_string_field_ptr_set(p, i->field, src);
14596 break;
14598 if (i->key == NULL) /* not found, try ',' */
14599 strsep(&c, ",");
14601 /* Reset nonce count */
14602 if (strcmp(p->nonce, oldnonce))
14603 p->noncecount = 0;
14605 /* Save auth data for following registrations */
14606 if (p->registry) {
14607 struct sip_registry *r = p->registry;
14609 if (strcmp(r->nonce, p->nonce)) {
14610 ast_string_field_set(r, realm, p->realm);
14611 ast_string_field_set(r, nonce, p->nonce);
14612 ast_string_field_set(r, domain, p->domain);
14613 ast_string_field_set(r, opaque, p->opaque);
14614 ast_string_field_set(r, qop, p->qop);
14615 r->noncecount = 0;
14618 return build_reply_digest(p, sipmethod, digest, digest_len);
14621 /*! \brief Build reply digest
14622 \return Returns -1 if we have no auth
14623 \note Build digest challenge for authentication of registrations and calls
14624 Also used for authentication of BYE
14626 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
14628 char a1[256];
14629 char a2[256];
14630 char a1_hash[256];
14631 char a2_hash[256];
14632 char resp[256];
14633 char resp_hash[256];
14634 char uri[256];
14635 char opaque[256] = "";
14636 char cnonce[80];
14637 const char *username;
14638 const char *secret;
14639 const char *md5secret;
14640 struct sip_auth *auth = NULL; /* Realm authentication */
14642 if (!ast_strlen_zero(p->domain))
14643 ast_copy_string(uri, p->domain, sizeof(uri));
14644 else if (!ast_strlen_zero(p->uri))
14645 ast_copy_string(uri, p->uri, sizeof(uri));
14646 else
14647 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
14649 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
14651 /* Check if we have separate auth credentials */
14652 if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
14653 auth = find_realm_authentication(authl, p->realm); /* If not, global list */
14655 if (auth) {
14656 ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
14657 username = auth->username;
14658 secret = auth->secret;
14659 md5secret = auth->md5secret;
14660 if (sipdebug)
14661 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
14662 } else {
14663 /* No authentication, use peer or register= config */
14664 username = p->authname;
14665 secret = p->peersecret;
14666 md5secret = p->peermd5secret;
14668 if (ast_strlen_zero(username)) /* We have no authentication */
14669 return -1;
14671 /* Calculate SIP digest response */
14672 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14673 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
14674 if (!ast_strlen_zero(md5secret))
14675 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14676 else
14677 ast_md5_hash(a1_hash, a1);
14678 ast_md5_hash(a2_hash, a2);
14680 p->noncecount++;
14681 if (!ast_strlen_zero(p->qop))
14682 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
14683 else
14684 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
14685 ast_md5_hash(resp_hash, resp);
14687 /* only include the opaque string if it's set */
14688 if (!ast_strlen_zero(p->opaque)) {
14689 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
14692 /* XXX We hard code our qop to "auth" for now. XXX */
14693 if (!ast_strlen_zero(p->qop))
14694 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
14695 else
14696 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
14698 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
14700 return 0;
14703 /*! \brief Read SIP header (dialplan function) */
14704 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
14706 struct sip_pvt *p;
14707 const char *content = NULL;
14708 AST_DECLARE_APP_ARGS(args,
14709 AST_APP_ARG(header);
14710 AST_APP_ARG(number);
14712 int i, number, start = 0;
14714 if (ast_strlen_zero(data)) {
14715 ast_log(LOG_WARNING, "This function requires a header name.\n");
14716 return -1;
14719 ast_channel_lock(chan);
14720 if (!IS_SIP_TECH(chan->tech)) {
14721 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
14722 ast_channel_unlock(chan);
14723 return -1;
14726 AST_STANDARD_APP_ARGS(args, data);
14727 if (!args.number) {
14728 number = 1;
14729 } else {
14730 sscanf(args.number, "%d", &number);
14731 if (number < 1)
14732 number = 1;
14735 p = chan->tech_pvt;
14737 /* If there is no private structure, this channel is no longer alive */
14738 if (!p) {
14739 ast_channel_unlock(chan);
14740 return -1;
14743 for (i = 0; i < number; i++)
14744 content = __get_header(&p->initreq, args.header, &start);
14746 if (ast_strlen_zero(content)) {
14747 ast_channel_unlock(chan);
14748 return -1;
14751 ast_copy_string(buf, content, len);
14752 ast_channel_unlock(chan);
14754 return 0;
14757 static struct ast_custom_function sip_header_function = {
14758 .name = "SIP_HEADER",
14759 .synopsis = "Gets the specified SIP header",
14760 .syntax = "SIP_HEADER(<name>[,<number>])",
14761 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
14762 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
14763 "that name to retrieve. Headers start at offset 1.\n",
14764 .read = func_header_read,
14767 /*! \brief Dial plan function to check if domain is local */
14768 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14770 if (ast_strlen_zero(data)) {
14771 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
14772 return -1;
14774 if (check_sip_domain(data, NULL, 0))
14775 ast_copy_string(buf, data, len);
14776 else
14777 buf[0] = '\0';
14778 return 0;
14781 static struct ast_custom_function checksipdomain_function = {
14782 .name = "CHECKSIPDOMAIN",
14783 .synopsis = "Checks if domain is a local domain",
14784 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
14785 .read = func_check_sipdomain,
14786 .desc = "This function checks if the domain in the argument is configured\n"
14787 "as a local SIP domain that this Asterisk server is configured to handle.\n"
14788 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
14789 "Check the domain= configuration in sip.conf\n",
14792 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
14793 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14795 struct sip_peer *peer;
14796 char *colname;
14798 if ((colname = strchr(data, ':'))) { /*! \todo Will be deprecated after 1.4 */
14799 static int deprecation_warning = 0;
14800 *colname++ = '\0';
14801 if (deprecation_warning++ % 10 == 0)
14802 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
14803 } else if ((colname = strchr(data, ',')))
14804 *colname++ = '\0';
14805 else
14806 colname = "ip";
14808 if (!(peer = find_peer(data, NULL, TRUE, TRUE)))
14809 return -1;
14811 if (!strcasecmp(colname, "ip")) {
14812 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
14813 } else if (!strcasecmp(colname, "port")) {
14814 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
14815 } else if (!strcasecmp(colname, "status")) {
14816 peer_status(peer, buf, len);
14817 } else if (!strcasecmp(colname, "language")) {
14818 ast_copy_string(buf, peer->language, len);
14819 } else if (!strcasecmp(colname, "regexten")) {
14820 ast_copy_string(buf, peer->regexten, len);
14821 } else if (!strcasecmp(colname, "limit")) {
14822 snprintf(buf, len, "%d", peer->call_limit);
14823 } else if (!strcasecmp(colname, "busylevel")) {
14824 snprintf(buf, len, "%d", peer->busy_level);
14825 } else if (!strcasecmp(colname, "curcalls")) {
14826 snprintf(buf, len, "%d", peer->inUse);
14827 } else if (!strcasecmp(colname, "accountcode")) {
14828 ast_copy_string(buf, peer->accountcode, len);
14829 } else if (!strcasecmp(colname, "callgroup")) {
14830 ast_print_group(buf, len, peer->callgroup);
14831 } else if (!strcasecmp(colname, "pickupgroup")) {
14832 ast_print_group(buf, len, peer->pickupgroup);
14833 } else if (!strcasecmp(colname, "useragent")) {
14834 ast_copy_string(buf, peer->useragent, len);
14835 } else if (!strcasecmp(colname, "mailbox")) {
14836 struct ast_str *mailbox_str = ast_str_alloca(512);
14837 peer_mailboxes_to_str(&mailbox_str, peer);
14838 ast_copy_string(buf, mailbox_str->str, len);
14839 } else if (!strcasecmp(colname, "context")) {
14840 ast_copy_string(buf, peer->context, len);
14841 } else if (!strcasecmp(colname, "expire")) {
14842 snprintf(buf, len, "%d", peer->expire);
14843 } else if (!strcasecmp(colname, "dynamic")) {
14844 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
14845 } else if (!strcasecmp(colname, "callerid_name")) {
14846 ast_copy_string(buf, peer->cid_name, len);
14847 } else if (!strcasecmp(colname, "callerid_num")) {
14848 ast_copy_string(buf, peer->cid_num, len);
14849 } else if (!strcasecmp(colname, "codecs")) {
14850 ast_getformatname_multiple(buf, len -1, peer->capability);
14851 } else if (!strncasecmp(colname, "chanvar[", 8)) {
14852 char *chanvar=colname + 8;
14853 struct ast_variable *v;
14855 chanvar = strsep(&chanvar, "]");
14856 for (v = peer->chanvars ; v ; v = v->next)
14857 if (strcasecmp(v->name, chanvar) == 0)
14858 ast_copy_string(buf, v->value, sizeof(buf));
14859 } else if (!strncasecmp(colname, "codec[", 6)) {
14860 char *codecnum;
14861 int index = 0, codec = 0;
14863 codecnum = colname + 6; /* move past the '[' */
14864 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
14865 index = atoi(codecnum);
14866 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
14867 ast_copy_string(buf, ast_getformatname(codec), len);
14871 unref_peer(peer, "unref_peer from function_sippeer, just before return");
14873 return 0;
14876 /*! \brief Structure to declare a dialplan function: SIPPEER */
14877 struct ast_custom_function sippeer_function = {
14878 .name = "SIPPEER",
14879 .synopsis = "Gets SIP peer information",
14880 .syntax = "SIPPEER(<peername>[,item])",
14881 .read = function_sippeer,
14882 .desc = "Valid items are:\n"
14883 "- ip (default) The IP address.\n"
14884 "- port The port number\n"
14885 "- mailbox The configured mailbox.\n"
14886 "- context The configured context.\n"
14887 "- expire The epoch time of the next expire.\n"
14888 "- dynamic Is it dynamic? (yes/no).\n"
14889 "- callerid_name The configured Caller ID name.\n"
14890 "- callerid_num The configured Caller ID number.\n"
14891 "- callgroup The configured Callgroup.\n"
14892 "- pickupgroup The configured Pickupgroup.\n"
14893 "- codecs The configured codecs.\n"
14894 "- status Status (if qualify=yes).\n"
14895 "- regexten Registration extension\n"
14896 "- limit Call limit (call-limit)\n"
14897 "- busylevel Configured call level for signalling busy\n"
14898 "- curcalls Current amount of calls \n"
14899 " Only available if call-limit is set\n"
14900 "- language Default language for peer\n"
14901 "- accountcode Account code for this peer\n"
14902 "- useragent Current user agent id for peer\n"
14903 "- chanvar[name] A channel variable configured with setvar for this peer.\n"
14904 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
14905 "\n"
14908 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
14909 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14911 struct sip_pvt *p;
14912 static int deprecated = 0;
14914 *buf = 0;
14916 if (!data) {
14917 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
14918 return -1;
14921 ast_channel_lock(chan);
14922 if (!IS_SIP_TECH(chan->tech)) {
14923 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
14924 ast_channel_unlock(chan);
14925 return -1;
14928 if (deprecated++ % 20 == 0) {
14929 /* Deprecated in 1.6.1 */
14930 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
14933 p = chan->tech_pvt;
14935 /* If there is no private structure, this channel is no longer alive */
14936 if (!p) {
14937 ast_channel_unlock(chan);
14938 return -1;
14941 if (!strcasecmp(data, "peerip")) {
14942 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
14943 } else if (!strcasecmp(data, "recvip")) {
14944 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
14945 } else if (!strcasecmp(data, "from")) {
14946 ast_copy_string(buf, p->from, len);
14947 } else if (!strcasecmp(data, "uri")) {
14948 ast_copy_string(buf, p->uri, len);
14949 } else if (!strcasecmp(data, "useragent")) {
14950 ast_copy_string(buf, p->useragent, len);
14951 } else if (!strcasecmp(data, "peername")) {
14952 ast_copy_string(buf, p->peername, len);
14953 } else if (!strcasecmp(data, "t38passthrough")) {
14954 if (p->t38.state == T38_DISABLED)
14955 ast_copy_string(buf, "0", sizeof("0"));
14956 else /* T38 is offered or enabled in this call */
14957 ast_copy_string(buf, "1", sizeof("1"));
14958 } else {
14959 ast_channel_unlock(chan);
14960 return -1;
14962 ast_channel_unlock(chan);
14964 return 0;
14967 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
14968 static struct ast_custom_function sipchaninfo_function = {
14969 .name = "SIPCHANINFO",
14970 .synopsis = "Gets the specified SIP parameter from the current channel",
14971 .syntax = "SIPCHANINFO(item)",
14972 .read = function_sipchaninfo_read,
14973 .desc = "Valid items are:\n"
14974 "- peerip The IP address of the peer.\n"
14975 "- recvip The source IP address of the peer.\n"
14976 "- from The URI from the From: header.\n"
14977 "- uri The URI from the Contact: header.\n"
14978 "- useragent The useragent.\n"
14979 "- peername The name of the peer.\n"
14980 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
14983 /*! \brief Parse 302 Moved temporalily response */
14984 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
14986 char tmp[SIPBUFSIZE];
14987 char *s, *e, *t;
14988 char *domain;
14990 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
14991 if ((t = strchr(tmp, ',')))
14992 *t = '\0';
14993 s = remove_uri_parameters(get_in_brackets(tmp));
14994 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
14995 if (!strncasecmp(s, "sip:", 4))
14996 s += 4;
14997 else if (!strncasecmp(s, "sips:", 5))
14998 s += 5;
14999 e = strchr(s, '/');
15000 if (e)
15001 *e = '\0';
15002 ast_debug(2, "Found promiscuous redirection to 'SIP/%s'\n", s);
15003 if (p->owner)
15004 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
15005 } else {
15006 e = strchr(tmp, '@');
15007 if (e) {
15008 *e++ = '\0';
15009 domain = e;
15010 } else {
15011 /* No username part */
15012 domain = tmp;
15014 e = strchr(tmp, '/'); /* WHEN do we hae a forward slash in the URI? */
15015 if (e)
15016 *e = '\0';
15018 if (!strncasecmp(s, "sip:", 4))
15019 s += 4;
15020 else if (!strncasecmp(s, "sips:", 5))
15021 s += 5;
15022 e = strchr(s, ';'); /* And username ; parameters? */
15023 if (e)
15024 *e = '\0';
15025 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
15026 if (p->owner) {
15027 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
15028 ast_string_field_set(p->owner, call_forward, s);
15033 /*! \brief Check pending actions on SIP call */
15034 static void check_pendings(struct sip_pvt *p)
15036 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
15037 /* if we can't BYE, then this is really a pending CANCEL */
15038 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
15039 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
15040 /* Actually don't destroy us yet, wait for the 487 on our original
15041 INVITE, but do set an autodestruct just in case we never get it. */
15042 else {
15043 /* We have a pending outbound invite, don't send someting
15044 new in-transaction */
15045 if (p->pendinginvite)
15046 return;
15048 /* Perhaps there is an SD change INVITE outstanding */
15049 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
15051 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
15052 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15053 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
15054 /* if we can't REINVITE, hold it for later */
15055 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
15056 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
15057 } else {
15058 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
15059 /* Didn't get to reinvite yet, so do it now */
15060 transmit_reinvite_with_sdp(p, FALSE, FALSE);
15061 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
15066 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
15067 to avoid race conditions between asterisk servers.
15068 Called from the scheduler.
15070 static int sip_reinvite_retry(const void *data)
15072 struct sip_pvt *p = (struct sip_pvt *) data;
15074 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
15075 p->waitid = -1;
15076 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
15077 return 0;
15081 /*! \brief Handle SIP response to INVITE dialogue */
15082 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
15084 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
15085 int res = 0;
15086 int xmitres = 0;
15087 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
15088 struct ast_channel *bridgepeer = NULL;
15089 char *p_hdrval;
15090 int rtn;
15092 if (reinvite)
15093 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
15094 else
15095 ast_debug(4, "SIP response %d to standard invite\n", resp);
15097 if (p->alreadygone) { /* This call is already gone */
15098 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
15099 return;
15102 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
15103 /* Don't auto congest anymore since we've gotten something useful back */
15104 AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
15106 /* RFC3261 says we must treat every 1xx response (but not 100)
15107 that we don't recognize as if it was 183.
15109 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
15110 resp = 183;
15112 /* Any response between 100 and 199 is PROCEEDING */
15113 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
15114 p->invitestate = INV_PROCEEDING;
15116 /* Final response, not 200 ? */
15117 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
15118 p->invitestate = INV_COMPLETED;
15121 switch (resp) {
15122 case 100: /* Trying */
15123 case 101: /* Dialog establishment */
15124 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
15125 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15126 check_pendings(p);
15127 break;
15129 case 180: /* 180 Ringing */
15130 case 182: /* 182 Queued */
15131 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
15132 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15133 if (!req->ignore && p->owner) {
15134 ast_queue_control(p->owner, AST_CONTROL_RINGING);
15135 if (p->owner->_state != AST_STATE_UP) {
15136 ast_setstate(p->owner, AST_STATE_RINGING);
15139 if (find_sdp(req)) {
15140 if (p->invitestate != INV_CANCELLED)
15141 p->invitestate = INV_EARLY_MEDIA;
15142 res = process_sdp(p, req, SDP_T38_NONE);
15143 if (!req->ignore && p->owner) {
15144 /* Queue a progress frame only if we have SDP in 180 or 182 */
15145 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
15148 check_pendings(p);
15149 break;
15151 case 183: /* Session progress */
15152 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
15153 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15154 /* Ignore 183 Session progress without SDP */
15155 if (find_sdp(req)) {
15156 if (p->invitestate != INV_CANCELLED)
15157 p->invitestate = INV_EARLY_MEDIA;
15158 res = process_sdp(p, req, SDP_T38_NONE);
15159 if (!req->ignore && p->owner) {
15160 /* Queue a progress frame */
15161 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
15164 check_pendings(p);
15165 break;
15167 case 200: /* 200 OK on invite - someone's answering our call */
15168 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
15169 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15170 p->authtries = 0;
15171 if (find_sdp(req)) {
15172 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
15173 if (!reinvite)
15174 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
15175 /* For re-invites, we try to recover */
15176 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15179 /* Parse contact header for continued conversation */
15180 /* When we get 200 OK, we know which device (and IP) to contact for this call */
15181 /* This is important when we have a SIP proxy between us and the phone */
15182 if (outgoing) {
15183 update_call_counter(p, DEC_CALL_RINGING);
15184 parse_ok_contact(p, req);
15185 if(set_address_from_contact(p)) {
15186 /* Bad contact - we don't know how to reach this device */
15187 /* We need to ACK, but then send a bye */
15188 /* OEJ: Possible issue that may need a check:
15189 If we have a proxy route between us and the device,
15190 should we care about resolving the contact
15191 or should we just send it?
15193 if (!req->ignore)
15194 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15197 /* Save Record-Route for any later requests we make on this dialogue */
15198 if (!reinvite)
15199 build_route(p, req, 1);
15202 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
15203 struct sip_pvt *bridgepvt = NULL;
15205 if (!bridgepeer->tech) {
15206 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
15207 break;
15209 if (IS_SIP_TECH(bridgepeer->tech)) {
15210 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
15211 if (bridgepvt->udptl) {
15212 if (p->t38.state == T38_ENABLED && bridgepvt->t38.state == T38_PEER_REINVITE) {
15213 sip_handle_t38_reinvite(bridgepeer, p, 0);
15214 ast_rtp_set_rtptimers_onhold(p->rtp);
15215 if (p->vrtp)
15216 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
15217 } else if (p->t38.state == T38_DISABLED && bridgepvt->t38.state == T38_ENABLED) {
15218 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
15219 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
15220 /* XXXX Should we really destroy this session here, without any response at all??? */
15221 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15223 } else {
15224 ast_debug(2, "Strange... The other side of the bridge does not have a udptl struct\n");
15225 sip_pvt_lock(bridgepvt);
15226 change_t38_state(bridgepvt, T38_DISABLED);
15227 sip_pvt_unlock(bridgepvt);
15228 change_t38_state(p, T38_DISABLED);
15230 } else {
15231 /* Other side is not a SIP channel */
15232 ast_debug(2, "Strange... The other side of the bridge is not a SIP channel\n");
15233 change_t38_state(p, T38_DISABLED);
15237 if (!req->ignore && p->owner) {
15238 if (!reinvite) {
15239 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
15240 if (global_callevents)
15241 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
15242 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
15243 p->owner->name, p->owner->uniqueid, "SIP", p->callid, p->fullcontact, p->peername);
15244 } else { /* RE-invite */
15245 ast_queue_frame(p->owner, &ast_null_frame);
15247 } else {
15248 /* It's possible we're getting an 200 OK after we've tried to disconnect
15249 by sending CANCEL */
15250 /* First send ACK, then send bye */
15251 if (!req->ignore)
15252 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15255 /* Check for Session-Timers related headers */
15256 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
15257 p_hdrval = (char*)get_header(req, "Session-Expires");
15258 if (!ast_strlen_zero(p_hdrval)) {
15259 /* UAS supports Session-Timers */
15260 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
15261 int tmp_st_interval = 0;
15262 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
15263 if (rtn != 0) {
15264 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15266 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
15267 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
15268 p->stimer->st_ref = tmp_st_ref;
15270 if (tmp_st_interval) {
15271 p->stimer->st_interval = tmp_st_interval;
15273 p->stimer->st_active = TRUE;
15274 p->stimer->st_active_peer_ua = TRUE;
15275 start_session_timer(p);
15276 } else {
15277 /* UAS doesn't support Session-Timers */
15278 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
15279 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
15280 p->stimer->st_active_peer_ua = FALSE;
15281 start_session_timer(p);
15287 /* If I understand this right, the branch is different for a non-200 ACK only */
15288 p->invitestate = INV_TERMINATED;
15289 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
15290 check_pendings(p);
15291 break;
15293 case 407: /* Proxy authentication */
15294 case 401: /* Www auth */
15295 /* First we ACK */
15296 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15297 if (p->options)
15298 p->options->auth_type = resp;
15300 /* Then we AUTH */
15301 ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
15302 if (!req->ignore) {
15303 if (p->authtries < MAX_AUTHTRIES)
15304 p->invitestate = INV_CALLING;
15305 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
15306 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
15307 p->needdestroy = 1;
15308 sip_alreadygone(p);
15309 if (p->owner)
15310 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15313 break;
15315 case 403: /* Forbidden */
15316 /* First we ACK */
15317 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15318 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
15319 if (!req->ignore && p->owner)
15320 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15321 p->needdestroy = 1;
15322 sip_alreadygone(p);
15323 break;
15325 case 404: /* Not found */
15326 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15327 if (p->owner && !req->ignore)
15328 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15329 sip_alreadygone(p);
15330 break;
15332 case 408: /* Request timeout */
15333 case 481: /* Call leg does not exist */
15334 /* Could be REFER caused INVITE with replaces */
15335 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
15336 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15337 if (p->owner)
15338 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15339 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15340 break;
15342 case 422: /* Session-Timers: Session interval too small */
15343 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15344 ast_string_field_set(p, theirtag, NULL);
15345 proc_422_rsp(p, req);
15346 break;
15348 case 487: /* Cancelled transaction */
15349 /* We have sent CANCEL on an outbound INVITE
15350 This transaction is already scheduled to be killed by sip_hangup().
15352 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15353 if (p->owner && !req->ignore) {
15354 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
15355 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
15356 } else if (!req->ignore) {
15357 update_call_counter(p, DEC_CALL_LIMIT);
15358 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
15359 p->needdestroy = 1;
15360 sip_alreadygone(p);
15362 break;
15363 case 488: /* Not acceptable here */
15364 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15365 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
15366 change_t38_state(p, T38_DISABLED);
15367 /* Try to reset RTP timers */
15368 ast_rtp_set_rtptimers_onhold(p->rtp);
15370 /* Trigger a reinvite back to audio */
15371 transmit_reinvite_with_sdp(p, FALSE, FALSE);
15372 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
15373 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
15374 right now we can't fall back to audio so totally abort.
15376 /* Try to reset RTP timers */
15377 ast_rtp_set_rtptimers_onhold(p->rtp);
15378 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
15380 change_t38_state(p, T38_DISABLED);
15381 /* The dialog is now terminated */
15382 if (p->owner && !req->ignore)
15383 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15384 p->needdestroy = 1;
15385 sip_alreadygone(p);
15386 } else {
15387 /* We can't set up this call, so give up */
15388 if (p->owner && !req->ignore)
15389 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15390 p->needdestroy = 1;
15391 /* If there's no dialog to end, then mark p as already gone */
15392 if (!reinvite)
15393 sip_alreadygone(p);
15395 break;
15396 case 491: /* Pending */
15397 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15398 if (p->owner && !req->ignore) {
15399 if (p->owner->_state != AST_STATE_UP) {
15400 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15401 p->needdestroy = 1;
15402 } else {
15403 /* This is a re-invite that failed. */
15404 /* Reset the flag after a while
15406 int wait = 3 + ast_random() % 5;
15407 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
15408 ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
15409 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
15412 break;
15414 case 501: /* Not implemented */
15415 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15416 if (p->owner)
15417 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15418 break;
15420 if (xmitres == XMIT_ERROR)
15421 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
15424 /* \brief Handle SIP response in NOTIFY transaction
15425 We've sent a NOTIFY, now handle responses to it
15427 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
15429 switch (resp) {
15430 case 200: /* Notify accepted */
15431 /* They got the notify, this is the end */
15432 if (p->owner) {
15433 if (!p->refer) {
15434 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
15435 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
15436 } else {
15437 ast_debug(4, "Got OK on REFER Notify message\n");
15439 } else {
15440 if (p->subscribed == NONE) {
15441 ast_debug(4, "Got 200 accepted on NOTIFY\n");
15442 p->needdestroy = 1;
15444 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
15445 /* Ready to send the next state we have on queue */
15446 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
15447 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
15450 break;
15451 case 401: /* Not www-authorized on SIP method */
15452 case 407: /* Proxy auth */
15453 if (!p->notify_headers) {
15454 break; /* Only device notify can use NOTIFY auth */
15456 ast_string_field_set(p, theirtag, NULL);
15457 if (ast_strlen_zero(p->authname)) {
15458 ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s:%d but we have no matching peer or realm auth!\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
15459 p->needdestroy = 1;
15461 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
15462 ast_log(LOG_NOTICE, "Failed to authenticate on NOTYFY to '%s'\n", get_header(&p->initreq, "From"));
15463 p->needdestroy = 1;
15465 break;
15469 /* \brief Handle SIP response in REFER transaction
15470 We've sent a REFER, now handle responses to it
15472 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
15474 /* If no refer structure exists, then do nothing */
15475 if (!p->refer)
15476 return;
15478 switch (resp) {
15479 case 202: /* Transfer accepted */
15480 /* We need to do something here */
15481 /* The transferee is now sending INVITE to target */
15482 p->refer->status = REFER_ACCEPTED;
15483 /* Now wait for next message */
15484 ast_debug(3, "Got 202 accepted on transfer\n");
15485 /* We should hang along, waiting for NOTIFY's here */
15486 break;
15488 case 401: /* Not www-authorized on SIP method */
15489 case 407: /* Proxy auth */
15490 if (ast_strlen_zero(p->authname)) {
15491 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
15492 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
15493 p->needdestroy = 1;
15495 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
15496 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
15497 p->refer->status = REFER_NOAUTH;
15498 p->needdestroy = 1;
15500 break;
15501 case 481: /* Call leg does not exist */
15503 /* A transfer with Replaces did not work */
15504 /* OEJ: We should Set flag, cancel the REFER, go back
15505 to original call - but right now we can't */
15506 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
15507 if (p->owner)
15508 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15509 p->needdestroy = 1;
15510 break;
15512 case 500: /* Server error */
15513 case 501: /* Method not implemented */
15514 /* Return to the current call onhold */
15515 /* Status flag needed to be reset */
15516 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
15517 p->needdestroy = 1;
15518 p->refer->status = REFER_FAILED;
15519 break;
15520 case 603: /* Transfer declined */
15521 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
15522 p->refer->status = REFER_FAILED;
15523 p->needdestroy = 1;
15524 break;
15528 /*! \brief Handle responses on REGISTER to services */
15529 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
15531 int expires, expires_ms;
15532 struct sip_registry *r;
15533 r=p->registry;
15535 switch (resp) {
15536 case 401: /* Unauthorized */
15537 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
15538 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
15539 p->needdestroy = 1;
15541 break;
15542 case 403: /* Forbidden */
15543 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
15544 AST_SCHED_DEL(sched, r->timeout);
15545 r->regstate = REG_STATE_NOAUTH;
15546 p->needdestroy = 1;
15547 break;
15548 case 404: /* Not found */
15549 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
15550 p->needdestroy = 1;
15551 if (r->call)
15552 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
15553 r->regstate = REG_STATE_REJECTED;
15554 AST_SCHED_DEL(sched, r->timeout);
15555 break;
15556 case 407: /* Proxy auth */
15557 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
15558 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
15559 p->needdestroy = 1;
15561 break;
15562 case 408: /* Request timeout */
15563 /* Got a timeout response, so reset the counter of failed responses */
15564 r->regattempts = 0;
15565 break;
15566 case 423: /* Interval too brief */
15567 r->expiry = atoi(get_header(req, "Min-Expires"));
15568 ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
15569 AST_SCHED_DEL(sched, r->timeout);
15570 r->timeout = -1;
15571 if (r->call) {
15572 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
15573 p->needdestroy = 1;
15575 if (r->expiry > max_expiry) {
15576 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
15577 r->expiry = default_expiry;
15578 r->regstate = REG_STATE_REJECTED;
15579 } else {
15580 r->regstate = REG_STATE_UNREGISTERED;
15581 transmit_register(r, SIP_REGISTER, NULL, NULL);
15583 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
15584 break;
15585 case 479: /* SER: Not able to process the URI - address is wrong in register*/
15586 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
15587 p->needdestroy = 1;
15588 if (r->call)
15589 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
15590 r->regstate = REG_STATE_REJECTED;
15591 AST_SCHED_DEL(sched, r->timeout);
15592 break;
15593 case 200: /* 200 OK */
15594 if (!r) {
15595 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
15596 p->needdestroy = 1;
15597 return 0;
15600 r->regstate = REG_STATE_REGISTERED;
15601 r->regtime = ast_tvnow(); /* Reset time of last succesful registration */
15602 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
15603 r->regattempts = 0;
15604 ast_debug(1, "Registration successful\n");
15605 if (r->timeout > -1) {
15606 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
15608 AST_SCHED_DEL(sched, r->timeout);
15609 if (r->call)
15610 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
15611 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
15612 /* Let this one hang around until we have all the responses */
15613 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15614 /* p->needdestroy = 1; */
15616 /* set us up for re-registering */
15617 /* figure out how long we got registered for */
15618 AST_SCHED_DEL(sched, r->expire);
15620 /* according to section 6.13 of RFC, contact headers override
15621 expires headers, so check those first */
15622 expires = 0;
15624 /* XXX todo: try to save the extra call */
15625 if (!ast_strlen_zero(get_header(req, "Contact"))) {
15626 const char *contact = NULL;
15627 const char *tmptmp = NULL;
15628 int start = 0;
15629 for(;;) {
15630 contact = __get_header(req, "Contact", &start);
15631 /* this loop ensures we get a contact header about our register request */
15632 if(!ast_strlen_zero(contact)) {
15633 if( (tmptmp=strstr(contact, p->our_contact))) {
15634 contact=tmptmp;
15635 break;
15637 } else
15638 break;
15640 tmptmp = strcasestr(contact, "expires=");
15641 if (tmptmp) {
15642 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
15643 expires = 0;
15647 if (!expires)
15648 expires=atoi(get_header(req, "expires"));
15649 if (!expires)
15650 expires=default_expiry;
15652 expires_ms = expires * 1000;
15653 if (expires <= EXPIRY_GUARD_LIMIT)
15654 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
15655 else
15656 expires_ms -= EXPIRY_GUARD_SECS * 1000;
15657 if (sipdebug)
15658 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
15660 r->refresh= (int) expires_ms / 1000;
15662 /* Schedule re-registration before we expire */
15663 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
15664 registry_unref(_data,"unref in REPLACE del fail"),
15665 registry_unref(r,"unref in REPLACE add fail"),
15666 registry_addref(r,"The Addition side of REPLACE"));
15667 /* it is clear that we would not want to destroy the registry entry if we just
15668 scheduled a callback and recorded it in there! */
15669 /* since we never bumped the count, we shouldn't decrement it! registry_unref(r, "unref registry ptr r"); if this gets deleted, p->registry will be a bad pointer! */
15671 return 1;
15674 /*! \brief Handle qualification responses (OPTIONS) */
15675 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
15677 struct sip_peer *peer = /* ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
15678 int statechanged, is_reachable, was_reachable;
15679 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
15682 * Compute the response time to a ping (goes in peer->lastms.)
15683 * -1 means did not respond, 0 means unknown,
15684 * 1..maxms is a valid response, >maxms means late response.
15686 if (pingtime < 1) /* zero = unknown, so round up to 1 */
15687 pingtime = 1;
15689 /* Now determine new state and whether it has changed.
15690 * Use some helper variables to simplify the writing
15691 * of the expressions.
15693 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
15694 is_reachable = pingtime <= peer->maxms;
15695 statechanged = peer->lastms == 0 /* yes, unknown before */
15696 || was_reachable != is_reachable;
15698 peer->lastms = pingtime;
15699 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
15700 if (statechanged) {
15701 const char *s = is_reachable ? "Reachable" : "Lagged";
15703 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
15704 peer->name, s, pingtime, peer->maxms);
15705 ast_device_state_changed("SIP/%s", peer->name);
15706 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15707 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
15708 peer->name, s, pingtime);
15709 if (is_reachable && global_regextenonqualify)
15710 register_peer_exten(peer, TRUE);
15713 p->needdestroy = 1;
15715 /* Try again eventually */
15716 AST_SCHED_REPLACE(peer->pokeexpire, sched,
15717 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
15718 sip_poke_peer_s, peer);
15719 /* unref_peer(peer, "unref relatedpeer ptr var at end of handle_response_peerpoke"); */
15722 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
15723 static void stop_media_flows(struct sip_pvt *p)
15725 /* Immediately stop RTP, VRTP and UDPTL as applicable */
15726 if (p->rtp)
15727 ast_rtp_stop(p->rtp);
15728 if (p->vrtp)
15729 ast_rtp_stop(p->vrtp);
15730 if (p->trtp)
15731 ast_rtp_stop(p->trtp);
15732 if (p->udptl)
15733 ast_udptl_stop(p->udptl);
15736 /*! \brief Handle SIP response in dialogue
15737 \note only called by handle_incoming */
15738 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
15740 struct ast_channel *owner;
15741 int sipmethod;
15742 int res = 1;
15743 const char *c = get_header(req, "Cseq");
15744 /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
15745 char *c_copy = ast_strdupa(c);
15746 /* Skip the Cseq and its subsequent spaces */
15747 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
15749 if (!msg)
15750 msg = "";
15752 sipmethod = find_sip_method(msg);
15754 owner = p->owner;
15755 if (owner)
15756 owner->hangupcause = hangup_sip2cause(resp);
15758 /* Acknowledge whatever it is destined for */
15759 if ((resp >= 100) && (resp <= 199))
15760 __sip_semi_ack(p, seqno, 0, sipmethod);
15761 else
15762 __sip_ack(p, seqno, 0, sipmethod);
15764 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
15765 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
15766 p->pendinginvite = 0;
15768 /* Get their tag if we haven't already */
15769 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
15770 char tag[128];
15772 gettag(req, "To", tag, sizeof(tag));
15773 ast_string_field_set(p, theirtag, tag);
15775 /* This needs to be configurable on a channel/peer level,
15776 not mandatory for all communication. Sadly enough, NAT implementations
15777 are not so stable so we can always rely on these headers.
15778 Temporarily disabled, while waiting for fix.
15779 Fix assigned to Rizzo :-)
15781 /* check_via_response(p, req); */
15782 if (p->relatedpeer && p->method == SIP_OPTIONS) {
15783 /* We don't really care what the response is, just that it replied back.
15784 Well, as long as it's not a 100 response... since we might
15785 need to hang around for something more "definitive" */
15786 if (resp != 100)
15787 handle_response_peerpoke(p, resp, req);
15788 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
15789 switch(resp) {
15790 case 100: /* 100 Trying */
15791 case 101: /* 101 Dialog establishment */
15792 if (sipmethod == SIP_INVITE)
15793 handle_response_invite(p, resp, rest, req, seqno);
15794 break;
15795 case 183: /* 183 Session Progress */
15796 if (sipmethod == SIP_INVITE)
15797 handle_response_invite(p, resp, rest, req, seqno);
15798 break;
15799 case 180: /* 180 Ringing */
15800 if (sipmethod == SIP_INVITE)
15801 handle_response_invite(p, resp, rest, req, seqno);
15802 break;
15803 case 182: /* 182 Queued */
15804 if (sipmethod == SIP_INVITE)
15805 handle_response_invite(p, resp, rest, req, seqno);
15806 break;
15807 case 200: /* 200 OK */
15808 p->authtries = 0; /* Reset authentication counter */
15809 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
15810 /* We successfully transmitted a message
15811 or a video update request in INFO */
15812 /* Nothing happens here - the message is inside a dialog */
15813 } else if (sipmethod == SIP_INVITE) {
15814 handle_response_invite(p, resp, rest, req, seqno);
15815 } else if (sipmethod == SIP_NOTIFY) {
15816 handle_response_notify(p, resp, rest, req, seqno);
15817 } else if (sipmethod == SIP_REGISTER)
15818 res = handle_response_register(p, resp, rest, req, seqno);
15819 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
15820 p->needdestroy = 1;
15821 break;
15822 case 202: /* Transfer accepted */
15823 if (sipmethod == SIP_REFER)
15824 handle_response_refer(p, resp, rest, req, seqno);
15825 break;
15826 case 401: /* Not www-authorized on SIP method */
15827 case 407: /* Proxy auth required */
15828 if (sipmethod == SIP_INVITE)
15829 handle_response_invite(p, resp, rest, req, seqno);
15830 else if (sipmethod == SIP_NOTIFY)
15831 handle_response_notify(p, resp, rest, req, seqno);
15832 else if (sipmethod == SIP_REFER)
15833 handle_response_refer(p, resp, rest, req, seqno);
15834 else if (p->registry && sipmethod == SIP_REGISTER)
15835 res = handle_response_register(p, resp, rest, req, seqno);
15836 else if (sipmethod == SIP_BYE) {
15837 if (p->options)
15838 p->options->auth_type = resp;
15839 if (ast_strlen_zero(p->authname)) {
15840 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
15841 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
15842 p->needdestroy = 1;
15843 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
15844 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
15845 p->needdestroy = 1;
15847 } else {
15848 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
15849 p->needdestroy = 1;
15851 break;
15852 case 403: /* Forbidden - we failed authentication */
15853 if (sipmethod == SIP_INVITE)
15854 handle_response_invite(p, resp, rest, req, seqno);
15855 else if (p->registry && sipmethod == SIP_REGISTER)
15856 res = handle_response_register(p, resp, rest, req, seqno);
15857 else {
15858 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
15859 p->needdestroy = 1;
15861 break;
15862 case 404: /* Not found */
15863 if (p->registry && sipmethod == SIP_REGISTER)
15864 res = handle_response_register(p, resp, rest, req, seqno);
15865 else if (sipmethod == SIP_INVITE)
15866 handle_response_invite(p, resp, rest, req, seqno);
15867 else if (owner)
15868 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15869 break;
15870 case 423: /* Interval too brief */
15871 if (sipmethod == SIP_REGISTER)
15872 res = handle_response_register(p, resp, rest, req, seqno);
15873 break;
15874 case 408: /* Request timeout - terminate dialog */
15875 if (sipmethod == SIP_INVITE)
15876 handle_response_invite(p, resp, rest, req, seqno);
15877 else if (sipmethod == SIP_REGISTER)
15878 res = handle_response_register(p, resp, rest, req, seqno);
15879 else if (sipmethod == SIP_BYE) {
15880 p->needdestroy = 1;
15881 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
15882 } else {
15883 if (owner)
15884 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15885 p->needdestroy = 1;
15887 break;
15889 case 422: /* Session-Timers: Session Interval Too Small */
15890 if (sipmethod == SIP_INVITE) {
15891 handle_response_invite(p, resp, rest, req, seqno);
15893 break;
15895 case 481: /* Call leg does not exist */
15896 if (sipmethod == SIP_INVITE) {
15897 handle_response_invite(p, resp, rest, req, seqno);
15898 } else if (sipmethod == SIP_REFER) {
15899 handle_response_refer(p, resp, rest, req, seqno);
15900 } else if (sipmethod == SIP_BYE) {
15901 /* The other side has no transaction to bye,
15902 just assume it's all right then */
15903 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
15904 } else if (sipmethod == SIP_CANCEL) {
15905 /* The other side has no transaction to cancel,
15906 just assume it's all right then */
15907 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
15908 } else {
15909 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
15910 /* Guessing that this is not an important request */
15912 break;
15913 case 487:
15914 if (sipmethod == SIP_INVITE)
15915 handle_response_invite(p, resp, rest, req, seqno);
15916 break;
15917 case 488: /* Not acceptable here - codec error */
15918 if (sipmethod == SIP_INVITE)
15919 handle_response_invite(p, resp, rest, req, seqno);
15920 break;
15921 case 491: /* Pending */
15922 if (sipmethod == SIP_INVITE)
15923 handle_response_invite(p, resp, rest, req, seqno);
15924 else {
15925 ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
15926 p->needdestroy = 1;
15928 break;
15929 case 501: /* Not Implemented */
15930 if (sipmethod == SIP_INVITE)
15931 handle_response_invite(p, resp, rest, req, seqno);
15932 else if (sipmethod == SIP_REFER)
15933 handle_response_refer(p, resp, rest, req, seqno);
15934 else
15935 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
15936 break;
15937 case 603: /* Declined transfer */
15938 if (sipmethod == SIP_REFER) {
15939 handle_response_refer(p, resp, rest, req, seqno);
15940 break;
15942 /* Fallthrough */
15943 default:
15944 if ((resp >= 300) && (resp < 700)) {
15945 /* Fatal response */
15946 if ((resp != 487))
15947 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
15949 if (sipmethod == SIP_INVITE)
15950 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
15952 /* XXX Locking issues?? XXX */
15953 switch(resp) {
15954 case 300: /* Multiple Choices */
15955 case 301: /* Moved permanently */
15956 case 302: /* Moved temporarily */
15957 case 305: /* Use Proxy */
15958 parse_moved_contact(p, req);
15959 /* Fall through */
15960 case 486: /* Busy here */
15961 case 600: /* Busy everywhere */
15962 case 603: /* Decline */
15963 if (p->owner)
15964 ast_queue_control(p->owner, AST_CONTROL_BUSY);
15965 break;
15966 case 482: /*!
15967 \note SIP is incapable of performing a hairpin call, which
15968 is yet another failure of not having a layer 2 (again, YAY
15969 IETF for thinking ahead). So we treat this as a call
15970 forward and hope we end up at the right place... */
15971 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
15972 if (p->owner)
15973 ast_string_field_build(p->owner, call_forward,
15974 "Local/%s@%s", p->username, p->context);
15975 /* Fall through */
15976 case 480: /* Temporarily Unavailable */
15977 case 404: /* Not Found */
15978 case 410: /* Gone */
15979 case 400: /* Bad Request */
15980 case 500: /* Server error */
15981 if (sipmethod == SIP_REFER) {
15982 handle_response_refer(p, resp, rest, req, seqno);
15983 break;
15985 /* Fall through */
15986 case 502: /* Bad gateway */
15987 case 503: /* Service Unavailable */
15988 case 504: /* Server Timeout */
15989 if (owner)
15990 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15991 break;
15992 default:
15993 /* Send hangup */
15994 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
15995 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
15996 break;
15998 /* ACK on invite */
15999 if (sipmethod == SIP_INVITE)
16000 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16001 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
16002 sip_alreadygone(p);
16003 if (!p->owner)
16004 p->needdestroy = 1;
16005 } else if ((resp >= 100) && (resp < 200)) {
16006 if (sipmethod == SIP_INVITE) {
16007 if (!req->ignore && sip_cancel_destroy(p))
16008 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16009 if (find_sdp(req))
16010 process_sdp(p, req, SDP_T38_NONE);
16011 if (p->owner) {
16012 /* Queue a progress frame */
16013 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16016 } else
16017 ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
16019 } else {
16020 /* Responses to OUTGOING SIP requests on INCOMING calls
16021 get handled here. As well as out-of-call message responses */
16022 if (req->debug)
16023 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
16025 if (sipmethod == SIP_INVITE && resp == 200) {
16026 /* Tags in early session is replaced by the tag in 200 OK, which is
16027 the final reply to our INVITE */
16028 char tag[128];
16030 gettag(req, "To", tag, sizeof(tag));
16031 ast_string_field_set(p, theirtag, tag);
16034 switch(resp) {
16035 case 200:
16036 if (sipmethod == SIP_INVITE) {
16037 handle_response_invite(p, resp, rest, req, seqno);
16038 } else if (sipmethod == SIP_CANCEL) {
16039 ast_debug(1, "Got 200 OK on CANCEL\n");
16041 /* Wait for 487, then destroy */
16042 } else if (sipmethod == SIP_NOTIFY) {
16043 /* They got the notify, this is the end */
16044 if (p->owner) {
16045 if (p->refer) {
16046 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
16047 } else
16048 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
16049 /* ast_queue_hangup(p->owner); Disabled */
16050 } else {
16051 if (!p->subscribed && !p->refer)
16052 p->needdestroy = 1;
16053 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
16054 /* Ready to send the next state we have on queue */
16055 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16056 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
16059 } else if (sipmethod == SIP_BYE)
16060 p->needdestroy = 1;
16061 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
16062 /* We successfully transmitted a message or
16063 a video update request in INFO */
16065 else if (sipmethod == SIP_BYE)
16066 /* Ok, we're ready to go */
16067 p->needdestroy = 1;
16068 break;
16069 case 202: /* Transfer accepted */
16070 if (sipmethod == SIP_REFER)
16071 handle_response_refer(p, resp, rest, req, seqno);
16072 break;
16073 case 401: /* www-auth */
16074 case 407:
16075 if (sipmethod == SIP_REFER)
16076 handle_response_refer(p, resp, rest, req, seqno);
16077 else if (sipmethod == SIP_INVITE)
16078 handle_response_invite(p, resp, rest, req, seqno);
16079 else if (sipmethod == SIP_BYE) {
16080 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
16081 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
16082 p->needdestroy = 1;
16085 break;
16086 case 481: /* Call leg does not exist */
16087 if (sipmethod == SIP_INVITE) {
16088 /* Re-invite failed */
16089 handle_response_invite(p, resp, rest, req, seqno);
16090 } else if (sipmethod == SIP_BYE) {
16091 p->needdestroy = 1;
16092 } else if (sipdebug) {
16093 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
16095 break;
16096 case 501: /* Not Implemented */
16097 if (sipmethod == SIP_INVITE)
16098 handle_response_invite(p, resp, rest, req, seqno);
16099 else if (sipmethod == SIP_REFER)
16100 handle_response_refer(p, resp, rest, req, seqno);
16101 break;
16102 case 603: /* Declined transfer */
16103 if (sipmethod == SIP_REFER) {
16104 handle_response_refer(p, resp, rest, req, seqno);
16105 break;
16107 /* Fallthrough */
16108 default: /* Errors without handlers */
16109 if ((resp >= 100) && (resp < 200)) {
16110 if (sipmethod == SIP_INVITE) { /* re-invite */
16111 if (!req->ignore && sip_cancel_destroy(p))
16112 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16115 if ((resp >= 300) && (resp < 700)) {
16116 if ((resp != 487))
16117 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
16118 switch(resp) {
16119 case 488: /* Not acceptable here - codec error */
16120 case 603: /* Decline */
16121 case 500: /* Server error */
16122 case 502: /* Bad gateway */
16123 case 503: /* Service Unavailable */
16124 case 504: /* Server timeout */
16126 /* re-invite failed */
16127 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
16128 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16129 break;
16132 break;
16138 /*! \brief Park SIP call support function
16139 Starts in a new thread, then parks the call
16140 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
16141 audio can't be heard before hangup
16143 static void *sip_park_thread(void *stuff)
16145 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
16146 struct sip_dual *d;
16147 struct sip_request req;
16148 int ext;
16149 int res;
16151 d = stuff;
16152 transferee = d->chan1;
16153 transferer = d->chan2;
16154 copy_request(&req, &d->req);
16155 if (d->req.data)
16156 ast_free(d->req.data);
16157 ast_free(d);
16159 if (!transferee || !transferer) {
16160 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
16161 return NULL;
16163 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
16165 ast_channel_lock(transferee);
16166 if (ast_do_masquerade(transferee)) {
16167 ast_log(LOG_WARNING, "Masquerade failed.\n");
16168 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
16169 ast_channel_unlock(transferee);
16170 return NULL;
16172 ast_channel_unlock(transferee);
16174 res = ast_park_call(transferee, transferer, 0, &ext);
16177 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
16178 if (!res) {
16179 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
16180 } else {
16181 /* Then tell the transferer what happened */
16182 sprintf(buf, "Call parked on extension '%d'", ext);
16183 transmit_message_with_text(transferer->tech_pvt, buf);
16185 #endif
16187 /* Any way back to the current call??? */
16188 /* Transmit response to the REFER request */
16189 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
16190 if (!res) {
16191 /* Transfer succeeded */
16192 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
16193 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
16194 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
16195 ast_hangup(transferer); /* This will cause a BYE */
16196 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
16197 } else {
16198 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
16199 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
16200 ast_debug(1, "SIP Call parked failed \n");
16201 /* Do not hangup call */
16203 return NULL;
16206 /*! \brief Park a call using the subsystem in res_features.c
16207 This is executed in a separate thread
16209 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
16211 struct sip_dual *d;
16212 struct ast_channel *transferee, *transferer;
16213 /* Chan2m: The transferer, chan1m: The transferee */
16214 pthread_t th;
16216 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
16217 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
16218 if ((!transferer) || (!transferee)) {
16219 if (transferee) {
16220 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16221 ast_hangup(transferee);
16223 if (transferer) {
16224 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16225 ast_hangup(transferer);
16227 return -1;
16230 /* Make formats okay */
16231 transferee->readformat = chan1->readformat;
16232 transferee->writeformat = chan1->writeformat;
16234 /* Prepare for taking over the channel */
16235 ast_channel_masquerade(transferee, chan1);
16237 /* Setup the extensions and such */
16238 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
16239 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
16240 transferee->priority = chan1->priority;
16242 /* We make a clone of the peer channel too, so we can play
16243 back the announcement */
16245 /* Make formats okay */
16246 transferer->readformat = chan2->readformat;
16247 transferer->writeformat = chan2->writeformat;
16249 /* Prepare for taking over the channel. Go ahead and grab this channel
16250 * lock here to avoid a deadlock with callbacks into the channel driver
16251 * that hold the channel lock and want the pvt lock. */
16252 while (ast_channel_trylock(chan2)) {
16253 struct sip_pvt *pvt = chan2->tech_pvt;
16254 sip_pvt_unlock(pvt);
16255 usleep(1);
16256 sip_pvt_lock(pvt);
16258 ast_channel_masquerade(transferer, chan2);
16259 ast_channel_unlock(chan2);
16261 /* Setup the extensions and such */
16262 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
16263 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
16264 transferer->priority = chan2->priority;
16266 ast_channel_lock(transferer);
16267 if (ast_do_masquerade(transferer)) {
16268 ast_log(LOG_WARNING, "Masquerade failed :(\n");
16269 ast_channel_unlock(transferer);
16270 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16271 ast_hangup(transferer);
16272 return -1;
16274 ast_channel_unlock(transferer);
16275 if (!transferer || !transferee) {
16276 if (!transferer) {
16277 ast_debug(1, "No transferer channel, giving up parking\n");
16279 if (!transferee) {
16280 ast_debug(1, "No transferee channel, giving up parking\n");
16282 return -1;
16284 if ((d = ast_calloc(1, sizeof(*d)))) {
16286 /* Save original request for followup */
16287 copy_request(&d->req, req);
16288 d->chan1 = transferee; /* Transferee */
16289 d->chan2 = transferer; /* Transferer */
16290 d->seqno = seqno;
16291 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
16292 /* Could not start thread */
16293 if (d->req.data)
16294 ast_free(d->req.data);
16295 ast_free(d); /* We don't need it anymore. If thread is created, d will be free'd
16296 by sip_park_thread() */
16297 return 0;
16300 return -1;
16303 /*! \brief Turn off generator data
16304 XXX Does this function belong in the SIP channel?
16306 static void ast_quiet_chan(struct ast_channel *chan)
16308 if (chan && chan->_state == AST_STATE_UP) {
16309 if (ast_test_flag(chan, AST_FLAG_MOH))
16310 ast_moh_stop(chan);
16311 else if (chan->generatordata)
16312 ast_deactivate_generator(chan);
16316 /*! \brief Attempt transfer of SIP call
16317 This fix for attended transfers on a local PBX */
16318 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
16320 int res = 0;
16321 struct ast_channel *peera = NULL,
16322 *peerb = NULL,
16323 *peerc = NULL,
16324 *peerd = NULL;
16327 /* We will try to connect the transferee with the target and hangup
16328 all channels to the transferer */
16329 ast_debug(4, "Sip transfer:--------------------\n");
16330 if (transferer->chan1)
16331 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
16332 else
16333 ast_debug(4, "-- No transferer first channel - odd??? \n");
16334 if (target->chan1)
16335 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
16336 else
16337 ast_debug(4, "-- No target first channel ---\n");
16338 if (transferer->chan2)
16339 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
16340 else
16341 ast_debug(4, "-- No bridged call to transferee\n");
16342 if (target->chan2)
16343 ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
16344 else
16345 ast_debug(4, "-- No target second channel ---\n");
16346 ast_debug(4, "-- END Sip transfer:--------------------\n");
16347 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
16348 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
16349 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
16350 peerc = transferer->chan2; /* Asterisk to Transferee */
16351 peerd = target->chan2; /* Asterisk to Target */
16352 ast_debug(3, "SIP transfer: Four channels to handle\n");
16353 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
16354 peera = target->chan1; /* Transferer to PBX -> target channel */
16355 peerb = transferer->chan1; /* Transferer to IVR*/
16356 peerc = target->chan2; /* Asterisk to Target */
16357 peerd = transferer->chan2; /* Nothing */
16358 ast_debug(3, "SIP transfer: Three channels to handle\n");
16361 if (peera && peerb && peerc && (peerb != peerc)) {
16362 ast_quiet_chan(peera); /* Stop generators */
16363 ast_quiet_chan(peerb);
16364 ast_quiet_chan(peerc);
16365 if (peerd)
16366 ast_quiet_chan(peerd);
16368 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
16369 if (ast_channel_masquerade(peerb, peerc)) {
16370 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
16371 res = -1;
16372 } else
16373 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
16374 return res;
16375 } else {
16376 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
16377 if (transferer->chan1)
16378 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
16379 if (target->chan1)
16380 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
16381 return -1;
16383 return 0;
16386 /*! \brief Get tag from packet
16388 * \return Returns the pointer to the provided tag buffer,
16389 * or NULL if the tag was not found.
16391 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
16393 const char *thetag;
16395 if (!tagbuf)
16396 return NULL;
16397 tagbuf[0] = '\0'; /* reset the buffer */
16398 thetag = get_header(req, header);
16399 thetag = strcasestr(thetag, ";tag=");
16400 if (thetag) {
16401 thetag += 5;
16402 ast_copy_string(tagbuf, thetag, tagbufsize);
16403 return strsep(&tagbuf, ";");
16405 return NULL;
16408 /*! \brief Handle incoming notifications */
16409 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
16411 /* This is mostly a skeleton for future improvements */
16412 /* Mostly created to return proper answers on notifications on outbound REFER's */
16413 int res = 0;
16414 const char *event = get_header(req, "Event");
16415 char *eventid = NULL;
16416 char *sep;
16418 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
16419 *sep++ = '\0';
16420 eventid = sep;
16423 if (sipdebug)
16424 ast_debug(2, "Got NOTIFY Event: %s\n", event);
16426 if (strcmp(event, "refer")) {
16427 /* We don't understand this event. */
16428 /* Here's room to implement incoming voicemail notifications :-) */
16429 transmit_response(p, "489 Bad event", req);
16430 res = -1;
16431 } else {
16432 /* Save nesting depth for now, since there might be other events we will
16433 support in the future */
16435 /* Handle REFER notifications */
16437 char buf[1024];
16438 char *cmd, *code;
16439 int respcode;
16440 int success = TRUE;
16442 /* EventID for each transfer... EventID is basically the REFER cseq
16444 We are getting notifications on a call that we transfered
16445 We should hangup when we are getting a 200 OK in a sipfrag
16446 Check if we have an owner of this event */
16448 /* Check the content type */
16449 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
16450 /* We need a sipfrag */
16451 transmit_response(p, "400 Bad request", req);
16452 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16453 return -1;
16456 /* Get the text of the attachment */
16457 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
16458 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
16459 transmit_response(p, "400 Bad request", req);
16460 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16461 return -1;
16465 From the RFC...
16466 A minimal, but complete, implementation can respond with a single
16467 NOTIFY containing either the body:
16468 SIP/2.0 100 Trying
16470 if the subscription is pending, the body:
16471 SIP/2.0 200 OK
16472 if the reference was successful, the body:
16473 SIP/2.0 503 Service Unavailable
16474 if the reference failed, or the body:
16475 SIP/2.0 603 Declined
16477 if the REFER request was accepted before approval to follow the
16478 reference could be obtained and that approval was subsequently denied
16479 (see Section 2.4.7).
16481 If there are several REFERs in the same dialog, we need to
16482 match the ID of the event header...
16484 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
16485 cmd = ast_skip_blanks(buf);
16486 code = cmd;
16487 /* We are at SIP/2.0 */
16488 while(*code && (*code > 32)) { /* Search white space */
16489 code++;
16491 *code++ = '\0';
16492 code = ast_skip_blanks(code);
16493 sep = code;
16494 sep++;
16495 while(*sep && (*sep > 32)) { /* Search white space */
16496 sep++;
16498 *sep++ = '\0'; /* Response string */
16499 respcode = atoi(code);
16500 switch (respcode) {
16501 case 100: /* Trying: */
16502 case 101: /* dialog establishment */
16503 /* Don't do anything yet */
16504 break;
16505 case 183: /* Ringing: */
16506 /* Don't do anything yet */
16507 break;
16508 case 200: /* OK: The new call is up, hangup this call */
16509 /* Hangup the call that we are replacing */
16510 break;
16511 case 301: /* Moved permenantly */
16512 case 302: /* Moved temporarily */
16513 /* Do we get the header in the packet in this case? */
16514 success = FALSE;
16515 break;
16516 case 503: /* Service Unavailable: The new call failed */
16517 /* Cancel transfer, continue the call */
16518 success = FALSE;
16519 break;
16520 case 603: /* Declined: Not accepted */
16521 /* Cancel transfer, continue the current call */
16522 success = FALSE;
16523 break;
16525 if (!success) {
16526 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
16529 /* Confirm that we received this packet */
16530 transmit_response(p, "200 OK", req);
16533 if (!p->lastinvite)
16534 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16536 return res;
16539 /*! \brief Handle incoming OPTIONS request
16540 An OPTIONS request should be answered like an INVITE from the same UA, including SDP
16542 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
16544 int res;
16546 /*! XXX get_destination assumes we're already authenticated. This means that a request from
16547 a known device (peer) will end up in the wrong context if this is out-of-dialog.
16548 However, we want to handle OPTIONS as light as possible, so we might want to have
16549 a configuration option whether we care or not. Some devices use this for testing
16550 capabilities, which means that we need to match device to answer with proper
16551 capabilities (including SDP).
16552 \todo Fix handle_request_options device handling with optional authentication
16553 (this needs to be fixed in 1.4 as well)
16556 if (p->lastinvite) {
16557 /* if this is a request in an active dialog, just confirm that the dialog exists. */
16558 transmit_response_with_allow(p, "200 OK", req, 0);
16559 return 0;
16562 res = get_destination(p, req);
16563 build_contact(p);
16565 if (ast_strlen_zero(p->context))
16566 ast_string_field_set(p, context, default_context);
16568 if (ast_shutting_down())
16569 transmit_response_with_allow(p, "503 Unavailable", req, 0);
16570 else if (res < 0)
16571 transmit_response_with_allow(p, "404 Not Found", req, 0);
16572 else
16573 transmit_response_with_allow(p, "200 OK", req, 0);
16575 /* Destroy if this OPTIONS was the opening request, but not if
16576 it's in the middle of a normal call flow. */
16577 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16579 return res;
16582 /*! \brief Handle the transfer part of INVITE with a replaces: header,
16583 meaning a target pickup or an attended transfer.
16584 Used only once.
16585 XXX 'ignore' is unused.
16587 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin)
16589 struct ast_frame *f;
16590 int earlyreplace = 0;
16591 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
16592 struct ast_channel *c = p->owner; /* Our incoming call */
16593 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
16594 struct ast_channel *targetcall; /* The bridge to the take-over target */
16596 struct ast_channel *test;
16598 /* Check if we're in ring state */
16599 if (replacecall->_state == AST_STATE_RING)
16600 earlyreplace = 1;
16602 /* Check if we have a bridge */
16603 if (!(targetcall = ast_bridged_channel(replacecall))) {
16604 /* We have no bridge */
16605 if (!earlyreplace) {
16606 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
16607 oneleggedreplace = 1;
16610 if (targetcall && targetcall->_state == AST_STATE_RINGING)
16611 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
16613 if (targetcall)
16614 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
16615 else
16616 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
16618 if (req->ignore) {
16619 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
16620 /* We should answer something here. If we are here, the
16621 call we are replacing exists, so an accepted
16622 can't harm */
16623 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
16624 /* Do something more clever here */
16625 ast_channel_unlock(c);
16626 sip_pvt_unlock(p->refer->refer_call);
16627 return 1;
16629 if (!c) {
16630 /* What to do if no channel ??? */
16631 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
16632 transmit_response_reliable(p, "503 Service Unavailable", req);
16633 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
16634 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16635 sip_pvt_unlock(p->refer->refer_call);
16636 return 1;
16638 append_history(p, "Xfer", "INVITE/Replace received");
16639 /* We have three channels to play with
16640 channel c: New incoming call
16641 targetcall: Call from PBX to target
16642 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
16643 replacecall: The owner of the previous
16644 We need to masq C into refer_call to connect to
16645 targetcall;
16646 If we are talking to internal audio stream, target call is null.
16649 /* Fake call progress */
16650 transmit_response(p, "100 Trying", req);
16651 ast_setstate(c, AST_STATE_RING);
16653 /* Masquerade the new call into the referred call to connect to target call
16654 Targetcall is not touched by the masq */
16656 /* Answer the incoming call and set channel to UP state */
16657 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
16659 ast_setstate(c, AST_STATE_UP);
16661 /* Stop music on hold and other generators */
16662 ast_quiet_chan(replacecall);
16663 ast_quiet_chan(targetcall);
16664 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
16665 /* Unlock clone, but not original (replacecall) */
16666 if (!oneleggedreplace)
16667 ast_channel_unlock(c);
16669 /* Unlock PVT */
16670 sip_pvt_unlock(p->refer->refer_call);
16672 /* Make sure that the masq does not free our PVT for the old call */
16673 if (! earlyreplace && ! oneleggedreplace )
16674 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
16676 /* Prepare the masquerade - if this does not happen, we will be gone */
16677 if(ast_channel_masquerade(replacecall, c))
16678 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
16679 else
16680 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
16682 /* The masquerade will happen as soon as someone reads a frame from the channel */
16684 /* C should now be in place of replacecall */
16685 /* ast_read needs to lock channel */
16686 ast_channel_unlock(c);
16688 if (earlyreplace || oneleggedreplace ) {
16689 /* Force the masq to happen */
16690 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
16691 ast_frfree(f);
16692 f = NULL;
16693 ast_debug(4, "Invite/Replace: Could successfully read frame from RING channel!\n");
16694 } else {
16695 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
16697 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16698 if (!oneleggedreplace)
16699 ast_channel_unlock(replacecall);
16700 } else { /* Bridged call, UP channel */
16701 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
16702 /* Masq ok */
16703 ast_frfree(f);
16704 f = NULL;
16705 ast_debug(3, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
16706 } else {
16707 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
16709 ast_channel_unlock(replacecall);
16711 sip_pvt_unlock(p->refer->refer_call);
16713 ast_setstate(c, AST_STATE_DOWN);
16714 ast_debug(4, "After transfer:----------------------------\n");
16715 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
16716 if (replacecall)
16717 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
16718 if (p->owner) {
16719 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
16720 test = ast_bridged_channel(p->owner);
16721 if (test)
16722 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
16723 else
16724 ast_debug(4, " -- No call bridged to C->owner \n");
16725 } else
16726 ast_debug(4, " -- No channel yet \n");
16727 ast_debug(4, "End After transfer:----------------------------\n");
16729 ast_channel_unlock(p->owner); /* Unlock new owner */
16730 if (!oneleggedreplace)
16731 sip_pvt_unlock(p); /* Unlock SIP structure */
16733 /* The call should be down with no ast_channel, so hang it up */
16734 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
16735 ast_hangup(c);
16736 return 0;
16740 /*! \brief Handle incoming INVITE request
16741 \note If the INVITE has a Replaces header, it is part of an
16742 * attended transfer. If so, we do not go through the dial
16743 * plan but tries to find the active call and masquerade
16744 * into it
16746 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, int *nounlock)
16748 int res = 1;
16749 int gotdest;
16750 const char *p_replaces;
16751 char *replace_id = NULL;
16752 const char *required;
16753 unsigned int required_profile = 0;
16754 struct ast_channel *c = NULL; /* New channel */
16755 int reinvite = 0;
16756 int rtn;
16758 const char *p_uac_se_hdr; /* UAC's Session-Expires header string */
16759 const char *p_uac_min_se; /* UAC's requested Min-SE interval (char string) */
16760 int uac_max_se = -1; /* UAC's Session-Expires in integer format */
16761 int uac_min_se = -1; /* UAC's Min-SE in integer format */
16762 int st_active = FALSE; /* Session-Timer on/off boolean */
16763 int st_interval = 0; /* Session-Timer negotiated refresh interval */
16764 enum st_refresher st_ref; /* Session-Timer session refresher */
16765 int dlg_min_se = -1;
16766 st_ref = SESSION_TIMER_REFRESHER_AUTO;
16768 /* Find out what they support */
16769 if (!p->sipoptions) {
16770 const char *supported = get_header(req, "Supported");
16771 if (!ast_strlen_zero(supported))
16772 parse_sip_options(p, supported);
16775 /* Find out what they require */
16776 required = get_header(req, "Require");
16777 if (!ast_strlen_zero(required)) {
16778 required_profile = parse_sip_options(NULL, required);
16779 if (required_profile && required_profile != SIP_OPT_REPLACES && required_profile != SIP_OPT_TIMER) {
16780 /* At this point we only support REPLACES and Session-Timer */
16781 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
16782 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
16783 p->invitestate = INV_COMPLETED;
16784 if (!p->lastinvite)
16785 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16786 return -1;
16790 /* The option tags may be present in Supported: or Require: headers.
16791 Include the Require: option tags for further processing as well */
16792 p->sipoptions |= required_profile;
16793 p->reqsipoptions = required_profile;
16795 /* Check if this is a loop */
16796 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
16797 /* This is a call to ourself. Send ourselves an error code and stop
16798 processing immediately, as SIP really has no good mechanism for
16799 being able to call yourself */
16800 /* If pedantic is on, we need to check the tags. If they're different, this is
16801 in fact a forked call through a SIP proxy somewhere. */
16802 transmit_response_reliable(p, "482 Loop Detected", req);
16803 p->invitestate = INV_COMPLETED;
16804 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16805 return 0;
16808 if (!req->ignore && p->pendinginvite) {
16809 /* We already have a pending invite. Sorry. You are on hold. */
16810 transmit_response_reliable(p, "491 Request Pending", req);
16811 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
16812 /* Don't destroy dialog here */
16813 return 0;
16816 p_replaces = get_header(req, "Replaces");
16817 if (!ast_strlen_zero(p_replaces)) {
16818 /* We have a replaces header */
16819 char *ptr;
16820 char *fromtag = NULL;
16821 char *totag = NULL;
16822 char *start, *to;
16823 int error = 0;
16825 if (p->owner) {
16826 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
16827 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
16828 /* Do not destroy existing call */
16829 return -1;
16832 if (sipdebug)
16833 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
16834 /* Create a buffer we can manipulate */
16835 replace_id = ast_strdupa(p_replaces);
16836 ast_uri_decode(replace_id);
16838 if (!p->refer && !sip_refer_allocate(p)) {
16839 transmit_response_reliable(p, "500 Server Internal Error", req);
16840 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
16841 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16842 p->invitestate = INV_COMPLETED;
16843 return -1;
16846 /* Todo: (When we find phones that support this)
16847 if the replaces header contains ";early-only"
16848 we can only replace the call in early
16849 stage, not after it's up.
16851 If it's not in early mode, 486 Busy.
16854 /* Skip leading whitespace */
16855 replace_id = ast_skip_blanks(replace_id);
16857 start = replace_id;
16858 while ( (ptr = strsep(&start, ";")) ) {
16859 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
16860 if ( (to = strcasestr(ptr, "to-tag=") ) )
16861 totag = to + 7; /* skip the keyword */
16862 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
16863 fromtag = to + 9; /* skip the keyword */
16864 fromtag = strsep(&fromtag, "&"); /* trim what ? */
16868 if (sipdebug)
16869 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id, fromtag ? fromtag : "<no from tag>", totag ? totag : "<no to tag>");
16872 /* Try to find call that we are replacing
16873 If we have a Replaces header, we need to cancel that call if we succeed with this call
16875 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
16876 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
16877 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
16878 error = 1;
16881 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
16883 /* The matched call is the call from the transferer to Asterisk .
16884 We want to bridge the bridged part of the call to the
16885 incoming invite, thus taking over the refered call */
16887 if (p->refer->refer_call == p) {
16888 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
16889 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
16890 transmit_response_reliable(p, "400 Bad request", req); /* The best way to not not accept the transfer */
16891 error = 1;
16894 if (!error && !p->refer->refer_call->owner) {
16895 /* Oops, someting wrong anyway, no owner, no call */
16896 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
16897 /* Check for better return code */
16898 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
16899 error = 1;
16902 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
16903 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
16904 transmit_response_reliable(p, "603 Declined (Replaces)", req);
16905 error = 1;
16908 if (error) { /* Give up this dialog */
16909 append_history(p, "Xfer", "INVITE/Replace Failed.");
16910 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16911 sip_pvt_unlock(p);
16912 if (p->refer->refer_call) {
16913 sip_pvt_unlock(p->refer->refer_call);
16914 ast_channel_unlock(p->refer->refer_call->owner);
16916 p->invitestate = INV_COMPLETED;
16917 return -1;
16921 /* Check if this is an INVITE that sets up a new dialog or
16922 a re-invite in an existing dialog */
16924 if (!req->ignore) {
16925 int newcall = (p->initreq.headers ? TRUE : FALSE);
16927 if (sip_cancel_destroy(p))
16928 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16929 /* This also counts as a pending invite */
16930 p->pendinginvite = seqno;
16931 check_via(p, req);
16933 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
16934 if (sipdebug)
16935 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
16936 if (!p->owner) { /* Not a re-invite */
16937 if (debug)
16938 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
16939 if (newcall)
16940 append_history(p, "Invite", "New call: %s", p->callid);
16941 parse_ok_contact(p, req);
16942 } else { /* Re-invite on existing call */
16943 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
16944 /* Handle SDP here if we already have an owner */
16945 if (find_sdp(req)) {
16946 if (process_sdp(p, req, SDP_T38_INITIATE)) {
16947 transmit_response_reliable(p, "488 Not acceptable here", req);
16948 if (!p->lastinvite)
16949 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16950 return -1;
16952 } else {
16953 p->jointcapability = p->capability;
16954 ast_debug(1, "Hm.... No sdp for the moment\n");
16956 if (p->do_history) /* This is a response, note what it was for */
16957 append_history(p, "ReInv", "Re-invite received");
16959 } else if (debug)
16960 ast_verbose("Ignoring this INVITE request\n");
16963 if (!p->lastinvite && !req->ignore && !p->owner) {
16964 /* This is a new invite */
16965 /* Handle authentication if this is our first invite */
16966 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
16967 if (res == AUTH_CHALLENGE_SENT) {
16968 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
16969 return 0;
16971 if (res < 0) { /* Something failed in authentication */
16972 if (res == AUTH_FAKE_AUTH) {
16973 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
16974 transmit_fake_auth_response(p, req, 1);
16975 } else {
16976 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
16977 transmit_response_reliable(p, "403 Forbidden", req);
16979 p->invitestate = INV_COMPLETED;
16980 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16981 ast_string_field_set(p, theirtag, NULL);
16982 return 0;
16985 /* We have a succesful authentication, process the SDP portion if there is one */
16986 if (find_sdp(req)) {
16987 if (process_sdp(p, req, SDP_T38_INITIATE)) {
16988 /* Unacceptable codecs */
16989 transmit_response_reliable(p, "488 Not acceptable here", req);
16990 p->invitestate = INV_COMPLETED;
16991 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16992 ast_debug(1, "No compatible codecs for this SIP call.\n");
16993 return -1;
16995 } else { /* No SDP in invite, call control session */
16996 p->jointcapability = p->capability;
16997 ast_debug(2, "No SDP in Invite, third party call control\n");
17000 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
17001 /* This seems redundant ... see !p-owner above */
17002 if (p->owner)
17003 ast_queue_frame(p->owner, &ast_null_frame);
17006 /* Initialize the context if it hasn't been already */
17007 if (ast_strlen_zero(p->context))
17008 ast_string_field_set(p, context, default_context);
17011 /* Check number of concurrent calls -vs- incoming limit HERE */
17012 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
17013 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
17014 if (res < 0) {
17015 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
17016 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
17017 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17018 p->invitestate = INV_COMPLETED;
17020 return 0;
17022 gotdest = get_destination(p, NULL); /* Get destination right away */
17023 get_rdnis(p, NULL); /* Get redirect information */
17024 extract_uri(p, req); /* Get the Contact URI */
17025 build_contact(p); /* Build our contact header */
17027 if (p->rtp) {
17028 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17029 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
17032 if (!replace_id && gotdest) { /* No matching extension found */
17033 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
17034 transmit_response_reliable(p, "484 Address Incomplete", req);
17035 else {
17036 char *decoded_exten = ast_strdupa(p->exten);
17038 transmit_response_reliable(p, "404 Not Found", req);
17039 ast_uri_decode(decoded_exten);
17040 ast_log(LOG_NOTICE, "Call from '%s' to extension"
17041 " '%s' rejected because extension not found.\n",
17042 S_OR(p->username, p->peername), decoded_exten);
17044 p->invitestate = INV_COMPLETED;
17045 update_call_counter(p, DEC_CALL_LIMIT);
17046 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17047 return 0;
17048 } else {
17050 /* If no extension was specified, use the s one */
17051 /* Basically for calling to IP/Host name only */
17052 if (ast_strlen_zero(p->exten))
17053 ast_string_field_set(p, exten, "s");
17054 /* Initialize our tag */
17056 make_our_tag(p->tag, sizeof(p->tag));
17057 /* First invitation - create the channel */
17058 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
17059 *recount = 1;
17061 /* Save Record-Route for any later requests we make on this dialogue */
17062 build_route(p, req, 0);
17064 if (c) {
17065 /* Pre-lock the call */
17066 ast_channel_lock(c);
17069 } else {
17070 if (sipdebug) {
17071 if (!req->ignore)
17072 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
17073 else
17074 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
17077 reinvite = 1;
17078 c = p->owner;
17081 /* Session-Timers */
17082 if (p->sipoptions == SIP_OPT_TIMER) {
17083 /* The UAC has requested session-timers for this session. Negotiate
17084 the session refresh interval and who will be the refresher */
17085 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
17087 /* Allocate Session-Timers struct w/in the dialog */
17088 if (!p->stimer)
17089 sip_st_alloc(p);
17091 /* Parse the Session-Expires header */
17092 p_uac_se_hdr = get_header(req, "Session-Expires");
17093 if (!ast_strlen_zero(p_uac_se_hdr)) {
17094 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
17095 if (rtn != 0) {
17096 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
17097 p->invitestate = INV_COMPLETED;
17098 if (!p->lastinvite) {
17099 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17101 return -1;
17105 /* Parse the Min-SE header */
17106 p_uac_min_se = get_header(req, "Min-SE");
17107 if (!ast_strlen_zero(p_uac_min_se)) {
17108 rtn = parse_minse(p_uac_min_se, &uac_min_se);
17109 if (rtn != 0) {
17110 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
17111 p->invitestate = INV_COMPLETED;
17112 if (!p->lastinvite) {
17113 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17115 return -1;
17119 dlg_min_se = st_get_se(p, FALSE);
17120 switch (st_get_mode(p)) {
17121 case SESSION_TIMER_MODE_ACCEPT:
17122 case SESSION_TIMER_MODE_ORIGINATE:
17123 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
17124 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
17125 p->invitestate = INV_COMPLETED;
17126 if (!p->lastinvite) {
17127 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17129 return -1;
17132 p->stimer->st_active_peer_ua = TRUE;
17133 st_active = TRUE;
17134 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
17135 st_ref = st_get_refresher(p);
17138 if (uac_max_se > 0) {
17139 int dlg_max_se = st_get_se(p, TRUE);
17140 if (dlg_max_se >= uac_min_se) {
17141 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
17142 } else {
17143 st_interval = uac_max_se;
17145 } else {
17146 st_interval = uac_min_se;
17148 break;
17150 case SESSION_TIMER_MODE_REFUSE:
17151 if (p->reqsipoptions == SIP_OPT_TIMER) {
17152 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
17153 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
17154 p->invitestate = INV_COMPLETED;
17155 if (!p->lastinvite) {
17156 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17158 return -1;
17160 break;
17162 default:
17163 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
17164 break;
17166 } else {
17167 /* The UAC did not request session-timers. Asterisk (UAS), will now decide
17168 (based on session-timer-mode in sip.conf) whether to run session-timers for
17169 this session or not. */
17170 switch (st_get_mode(p)) {
17171 case SESSION_TIMER_MODE_ORIGINATE:
17172 st_active = TRUE;
17173 st_interval = st_get_se(p, TRUE);
17174 st_ref = SESSION_TIMER_REFRESHER_UAS;
17175 p->stimer->st_active_peer_ua = FALSE;
17176 break;
17178 default:
17179 break;
17183 if (reinvite == 0) {
17184 /* Session-Timers: Start session refresh timer based on negotiation/config */
17185 if (st_active == TRUE) {
17186 p->stimer->st_active = TRUE;
17187 p->stimer->st_interval = st_interval;
17188 p->stimer->st_ref = st_ref;
17189 start_session_timer(p);
17191 } else {
17192 if (p->stimer->st_active == TRUE) {
17193 /* Session-Timers: A re-invite request sent within a dialog will serve as
17194 a refresh request, no matter whether the re-invite was sent for refreshing
17195 the session or modifying it.*/
17196 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
17198 /* The UAC may be adjusting the session-timers mid-session */
17199 if (st_interval > 0) {
17200 p->stimer->st_interval = st_interval;
17201 p->stimer->st_ref = st_ref;
17204 restart_session_timer(p);
17205 if (p->stimer->st_expirys > 0) {
17206 p->stimer->st_expirys--;
17211 if (!req->ignore && p)
17212 p->lastinvite = seqno;
17214 if (replace_id) { /* Attended transfer or call pickup - we're the target */
17215 /* Go and take over the target call */
17216 if (sipdebug)
17217 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
17218 return handle_invite_replaces(p, req, debug, seqno, sin);
17222 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
17223 switch(c->_state) {
17224 case AST_STATE_DOWN:
17225 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
17226 transmit_response(p, "100 Trying", req);
17227 p->invitestate = INV_PROCEEDING;
17228 ast_setstate(c, AST_STATE_RING);
17229 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
17230 enum ast_pbx_result res;
17232 res = ast_pbx_start(c);
17234 switch(res) {
17235 case AST_PBX_FAILED:
17236 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
17237 p->invitestate = INV_COMPLETED;
17238 transmit_response_reliable(p, "503 Unavailable", req);
17239 break;
17240 case AST_PBX_CALL_LIMIT:
17241 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
17242 p->invitestate = INV_COMPLETED;
17243 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
17244 break;
17245 case AST_PBX_SUCCESS:
17246 /* nothing to do */
17247 break;
17250 if (res) {
17252 /* Unlock locks so ast_hangup can do its magic */
17253 ast_channel_unlock(c);
17254 sip_pvt_unlock(p);
17255 ast_hangup(c);
17256 sip_pvt_lock(p);
17257 c = NULL;
17259 } else { /* Pickup call in call group */
17260 ast_channel_unlock(c);
17261 *nounlock = 1;
17262 if (ast_pickup_call(c)) {
17263 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
17264 transmit_response_reliable(p, "503 Unavailable", req);
17265 sip_alreadygone(p);
17266 /* Unlock locks so ast_hangup can do its magic */
17267 sip_pvt_unlock(p);
17268 c->hangupcause = AST_CAUSE_CALL_REJECTED;
17269 } else {
17270 sip_pvt_unlock(p);
17271 ast_setstate(c, AST_STATE_DOWN);
17272 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17274 p->invitestate = INV_COMPLETED;
17275 ast_hangup(c);
17276 sip_pvt_lock(p);
17277 c = NULL;
17279 break;
17280 case AST_STATE_RING:
17281 transmit_response(p, "100 Trying", req);
17282 p->invitestate = INV_PROCEEDING;
17283 break;
17284 case AST_STATE_RINGING:
17285 transmit_response(p, "180 Ringing", req);
17286 p->invitestate = INV_PROCEEDING;
17287 break;
17288 case AST_STATE_UP:
17289 ast_debug(2, "%s: This call is UP.... \n", c->name);
17291 transmit_response(p, "100 Trying", req);
17293 if (p->t38.state == T38_PEER_REINVITE) {
17294 struct ast_channel *bridgepeer = NULL;
17295 struct sip_pvt *bridgepvt = NULL;
17297 if ((bridgepeer = ast_bridged_channel(p->owner))) {
17298 /* We have a bridge, and this is re-invite to switchover to T38 so we send re-invite with T38 SDP, to other side of bridge*/
17299 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
17300 if (IS_SIP_TECH(bridgepeer->tech)) {
17301 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
17302 if (bridgepvt->t38.state == T38_DISABLED) {
17303 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
17304 /* Send re-invite to the bridged channel */
17305 sip_handle_t38_reinvite(bridgepeer, p, 1);
17306 } else { /* Something is wrong with peers udptl struct */
17307 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
17308 sip_pvt_lock(bridgepvt);
17309 change_t38_state(bridgepvt, T38_DISABLED);
17310 sip_pvt_unlock(bridgepvt);
17311 transmit_response_reliable(p, "488 Not acceptable here", req);
17314 } else {
17315 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
17316 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
17317 change_t38_state(p, T38_ENABLED);
17319 } else {
17320 /* Other side is not a SIP channel */
17321 transmit_response_reliable(p, "488 Not acceptable here", req);
17322 change_t38_state(p, T38_DISABLED);
17324 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
17325 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17327 } else {
17328 /* we are not bridged in a call */
17329 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
17330 change_t38_state(p, T38_ENABLED);
17332 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
17333 int sendok = TRUE;
17335 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
17336 /* so handle it here (re-invite other party to RTP) */
17337 struct ast_channel *bridgepeer = NULL;
17338 struct sip_pvt *bridgepvt = NULL;
17339 if ((bridgepeer = ast_bridged_channel(p->owner))) {
17340 if (IS_SIP_TECH(bridgepeer->tech) && !ast_check_hangup(bridgepeer)) {
17341 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
17342 /* Does the bridged peer have T38 ? */
17343 if (bridgepvt->t38.state == T38_ENABLED) {
17344 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
17345 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
17346 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
17347 sendok = FALSE;
17349 /* No bridged peer with T38 enabled*/
17352 /* Respond to normal re-invite */
17353 if (sendok) {
17354 /* If this is not a re-invite or something to ignore - it's critical */
17355 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
17358 p->invitestate = INV_TERMINATED;
17359 break;
17360 default:
17361 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
17362 transmit_response(p, "100 Trying", req);
17363 break;
17365 } else {
17366 if (p && (p->autokillid == -1)) {
17367 const char *msg;
17369 if (!p->jointcapability)
17370 msg = "488 Not Acceptable Here (codec error)";
17371 else {
17372 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
17373 msg = "503 Unavailable";
17375 transmit_response_reliable(p, msg, req);
17376 p->invitestate = INV_COMPLETED;
17377 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17380 return res;
17383 /*! \brief Find all call legs and bridge transferee with target
17384 * called from handle_request_refer */
17385 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
17387 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
17388 /* Chan 2: Call from Asterisk to target */
17389 int res = 0;
17390 struct sip_pvt *targetcall_pvt;
17392 /* Check if the call ID of the replaces header does exist locally */
17393 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
17394 transferer->refer->replaces_callid_fromtag))) {
17395 if (transferer->refer->localtransfer) {
17396 /* We did not find the refered call. Sorry, can't accept then */
17397 transmit_response(transferer, "202 Accepted", req);
17398 /* Let's fake a response from someone else in order
17399 to follow the standard */
17400 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
17401 append_history(transferer, "Xfer", "Refer failed");
17402 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
17403 transferer->refer->status = REFER_FAILED;
17404 return -1;
17406 /* Fall through for remote transfers that we did not find locally */
17407 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
17408 return 0;
17411 /* Ok, we can accept this transfer */
17412 transmit_response(transferer, "202 Accepted", req);
17413 append_history(transferer, "Xfer", "Refer accepted");
17414 if (!targetcall_pvt->owner) { /* No active channel */
17415 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
17416 /* Cancel transfer */
17417 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
17418 append_history(transferer, "Xfer", "Refer failed");
17419 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
17420 transferer->refer->status = REFER_FAILED;
17421 sip_pvt_unlock(targetcall_pvt);
17422 ast_channel_unlock(current->chan1);
17423 if (targetcall_pvt)
17424 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
17425 return -1;
17428 /* We have a channel, find the bridge */
17429 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
17430 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
17432 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
17433 /* Wrong state of new channel */
17434 if (target.chan2)
17435 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
17436 else if (target.chan1->_state != AST_STATE_RING)
17437 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
17438 else
17439 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
17442 /* Transfer */
17443 if (sipdebug) {
17444 if (current->chan2) /* We have two bridges */
17445 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
17446 else /* One bridge, propably transfer of IVR/voicemail etc */
17447 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
17450 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
17452 /* If we are performing an attended transfer and we have two channels involved then copy sound file information to play upon attended transfer completion */
17453 if (target.chan2) {
17454 const char *chan1_attended_sound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND"), *chan2_attended_sound = pbx_builtin_getvar_helper(target.chan2, "ATTENDED_TRANSFER_COMPLETE_SOUND");
17455 if (!ast_strlen_zero(chan1_attended_sound)) {
17456 pbx_builtin_setvar_helper(target.chan1, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
17458 if (!ast_strlen_zero(chan2_attended_sound)) {
17459 pbx_builtin_setvar_helper(target.chan2, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
17463 /* Perform the transfer */
17464 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
17465 transferer->owner->name,
17466 transferer->owner->uniqueid,
17467 transferer->callid,
17468 target.chan1->name,
17469 target.chan1->uniqueid);
17470 res = attempt_transfer(current, &target);
17471 sip_pvt_unlock(targetcall_pvt);
17472 if (res) {
17473 /* Failed transfer */
17474 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
17475 append_history(transferer, "Xfer", "Refer failed");
17476 if (targetcall_pvt->owner)
17477 ast_channel_unlock(targetcall_pvt->owner);
17478 /* Right now, we have to hangup, sorry. Bridge is destroyed */
17479 if (res != -2)
17480 ast_hangup(transferer->owner);
17481 else
17482 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
17483 } else {
17484 /* Transfer succeeded! */
17486 /* Tell transferer that we're done. */
17487 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
17488 append_history(transferer, "Xfer", "Refer succeeded");
17489 transferer->refer->status = REFER_200OK;
17490 if (targetcall_pvt->owner) {
17491 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
17492 ast_channel_unlock(targetcall_pvt->owner);
17495 if (targetcall_pvt)
17496 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
17497 return 1;
17501 /*! \brief Handle incoming REFER request */
17502 /*! \page SIP_REFER SIP transfer Support (REFER)
17504 REFER is used for call transfer in SIP. We get a REFER
17505 to place a new call with an INVITE somwhere and then
17506 keep the transferor up-to-date of the transfer. If the
17507 transfer fails, get back on line with the orginal call.
17509 - REFER can be sent outside or inside of a dialog.
17510 Asterisk only accepts REFER inside of a dialog.
17512 - If we get a replaces header, it is an attended transfer
17514 \par Blind transfers
17515 The transferor provides the transferee
17516 with the transfer targets contact. The signalling between
17517 transferer or transferee should not be cancelled, so the
17518 call is recoverable if the transfer target can not be reached
17519 by the transferee.
17521 In this case, Asterisk receives a TRANSFER from
17522 the transferor, thus is the transferee. We should
17523 try to set up a call to the contact provided
17524 and if that fails, re-connect the current session.
17525 If the new call is set up, we issue a hangup.
17526 In this scenario, we are following section 5.2
17527 in the SIP CC Transfer draft. (Transfer without
17528 a GRUU)
17530 \par Transfer with consultation hold
17531 In this case, the transferor
17532 talks to the transfer target before the transfer takes place.
17533 This is implemented with SIP hold and transfer.
17534 Note: The invite From: string could indicate a transfer.
17535 (Section 6. Transfer with consultation hold)
17536 The transferor places the transferee on hold, starts a call
17537 with the transfer target to alert them to the impending
17538 transfer, terminates the connection with the target, then
17539 proceeds with the transfer (as in Blind transfer above)
17541 \par Attended transfer
17542 The transferor places the transferee
17543 on hold, calls the transfer target to alert them,
17544 places the target on hold, then proceeds with the transfer
17545 using a Replaces header field in the Refer-to header. This
17546 will force the transfee to send an Invite to the target,
17547 with a replaces header that instructs the target to
17548 hangup the call between the transferor and the target.
17549 In this case, the Refer/to: uses the AOR address. (The same
17550 URI that the transferee used to establish the session with
17551 the transfer target (To: ). The Require: replaces header should
17552 be in the INVITE to avoid the wrong UA in a forked SIP proxy
17553 scenario to answer and have no call to replace with.
17555 The referred-by header is *NOT* required, but if we get it,
17556 can be copied into the INVITE to the transfer target to
17557 inform the target about the transferor
17559 "Any REFER request has to be appropriately authenticated.".
17561 We can't destroy dialogs, since we want the call to continue.
17564 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
17566 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
17567 /* Chan2: Call between asterisk and transferee */
17569 int res = 0;
17571 if (req->debug)
17572 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
17574 if (!p->owner) {
17575 /* This is a REFER outside of an existing SIP dialog */
17576 /* We can't handle that, so decline it */
17577 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
17578 transmit_response(p, "603 Declined (No dialog)", req);
17579 if (!req->ignore) {
17580 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
17581 sip_alreadygone(p);
17582 p->needdestroy = 1;
17584 return 0;
17588 /* Check if transfer is allowed from this device */
17589 if (p->allowtransfer == TRANSFER_CLOSED ) {
17590 /* Transfer not allowed, decline */
17591 transmit_response(p, "603 Declined (policy)", req);
17592 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
17593 /* Do not destroy SIP session */
17594 return 0;
17597 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
17598 /* Already have a pending REFER */
17599 transmit_response(p, "491 Request pending", req);
17600 append_history(p, "Xfer", "Refer failed. Request pending.");
17601 return 0;
17604 /* Allocate memory for call transfer data */
17605 if (!p->refer && !sip_refer_allocate(p)) {
17606 transmit_response(p, "500 Internal Server Error", req);
17607 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
17608 return -3;
17611 res = get_refer_info(p, req); /* Extract headers */
17613 p->refer->status = REFER_SENT;
17615 if (res != 0) {
17616 switch (res) {
17617 case -2: /* Syntax error */
17618 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
17619 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
17620 if (req->debug)
17621 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
17622 break;
17623 case -3:
17624 transmit_response(p, "603 Declined (Non sip: uri)", req);
17625 append_history(p, "Xfer", "Refer failed. Non SIP uri");
17626 if (req->debug)
17627 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
17628 break;
17629 default:
17630 /* Refer-to extension not found, fake a failed transfer */
17631 transmit_response(p, "202 Accepted", req);
17632 append_history(p, "Xfer", "Refer failed. Bad extension.");
17633 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
17634 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
17635 if (req->debug)
17636 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
17637 break;
17639 return 0;
17641 if (ast_strlen_zero(p->context))
17642 ast_string_field_set(p, context, default_context);
17644 /* If we do not support SIP domains, all transfers are local */
17645 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
17646 p->refer->localtransfer = 1;
17647 if (sipdebug)
17648 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
17649 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
17650 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
17651 p->refer->localtransfer = 1;
17652 } else if (sipdebug)
17653 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
17655 /* Is this a repeat of a current request? Ignore it */
17656 /* Don't know what else to do right now. */
17657 if (req->ignore)
17658 return res;
17660 /* If this is a blind transfer, we have the following
17661 channels to work with:
17662 - chan1, chan2: The current call between transferer and transferee (2 channels)
17663 - target_channel: A new call from the transferee to the target (1 channel)
17664 We need to stay tuned to what happens in order to be able
17665 to bring back the call to the transferer */
17667 /* If this is a attended transfer, we should have all call legs within reach:
17668 - chan1, chan2: The call between the transferer and transferee (2 channels)
17669 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
17670 We want to bridge chan2 with targetcall_pvt!
17672 The replaces call id in the refer message points
17673 to the call leg between Asterisk and the transferer.
17674 So we need to connect the target and the transferee channel
17675 and hangup the two other channels silently
17677 If the target is non-local, the call ID could be on a remote
17678 machine and we need to send an INVITE with replaces to the
17679 target. We basically handle this as a blind transfer
17680 and let the sip_call function catch that we need replaces
17681 header in the INVITE.
17685 /* Get the transferer's channel */
17686 current.chan1 = p->owner;
17688 /* Find the other part of the bridge (2) - transferee */
17689 current.chan2 = ast_bridged_channel(current.chan1);
17691 if (sipdebug)
17692 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
17694 if (!current.chan2 && !p->refer->attendedtransfer) {
17695 /* No bridged channel, propably IVR or echo or similar... */
17696 /* Guess we should masquerade or something here */
17697 /* Until we figure it out, refuse transfer of such calls */
17698 if (sipdebug)
17699 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
17700 p->refer->status = REFER_FAILED;
17701 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
17702 transmit_response(p, "603 Declined", req);
17703 return -1;
17706 if (current.chan2) {
17707 if (sipdebug)
17708 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
17710 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
17713 ast_set_flag(&p->flags[0], SIP_GOTREFER);
17715 /* Attended transfer: Find all call legs and bridge transferee with target*/
17716 if (p->refer->attendedtransfer) {
17717 if ((res = local_attended_transfer(p, &current, req, seqno)))
17718 return res; /* We're done with the transfer */
17719 /* Fall through for remote transfers that we did not find locally */
17720 if (sipdebug)
17721 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
17722 /* Fallthrough if we can't find the call leg internally */
17726 /* Parking a call */
17727 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
17728 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
17729 *nounlock = 1;
17730 ast_channel_unlock(current.chan1);
17731 copy_request(&current.req, req);
17732 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
17733 p->refer->status = REFER_200OK;
17734 append_history(p, "Xfer", "REFER to call parking.");
17735 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
17736 current.chan1->name,
17737 current.chan1->uniqueid,
17738 p->callid,
17739 current.chan2->name,
17740 current.chan2->uniqueid,
17741 p->refer->refer_to);
17742 if (sipdebug)
17743 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
17744 sip_park(current.chan2, current.chan1, req, seqno);
17745 return res;
17748 /* Blind transfers and remote attended xfers */
17749 transmit_response(p, "202 Accepted", req);
17751 if (current.chan1 && current.chan2) {
17752 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
17753 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
17755 if (current.chan2) {
17756 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
17757 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
17758 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
17759 /* One for the new channel */
17760 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
17761 /* Attended transfer to remote host, prepare headers for the INVITE */
17762 if (p->refer->referred_by)
17763 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
17765 /* Generate a Replaces string to be used in the INVITE during attended transfer */
17766 if (!ast_strlen_zero(p->refer->replaces_callid)) {
17767 char tempheader[SIPBUFSIZE];
17768 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
17769 p->refer->replaces_callid_totag ? ";to-tag=" : "",
17770 p->refer->replaces_callid_totag,
17771 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
17772 p->refer->replaces_callid_fromtag);
17773 if (current.chan2)
17774 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
17776 /* Must release lock now, because it will not longer
17777 be accessible after the transfer! */
17778 *nounlock = 1;
17779 ast_channel_unlock(current.chan1);
17781 /* Connect the call */
17783 /* FAKE ringing if not attended transfer */
17784 if (!p->refer->attendedtransfer)
17785 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
17787 /* For blind transfer, this will lead to a new call */
17788 /* For attended transfer to remote host, this will lead to
17789 a new SIP call with a replaces header, if the dial plan allows it
17791 if (!current.chan2) {
17792 /* We have no bridge, so we're talking with Asterisk somehow */
17793 /* We need to masquerade this call */
17794 /* What to do to fix this situation:
17795 * Set up the new call in a new channel
17796 * Let the new channel masq into this channel
17797 Please add that code here :-)
17799 p->refer->status = REFER_FAILED;
17800 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
17801 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
17802 append_history(p, "Xfer", "Refer failed (only bridged calls).");
17803 return -1;
17805 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
17808 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
17809 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
17810 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
17812 if (!res) {
17813 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
17814 current.chan1->name,
17815 current.chan1->uniqueid,
17816 p->callid,
17817 current.chan2->name,
17818 current.chan2->uniqueid,
17819 p->refer->refer_to, p->refer->refer_to_context);
17820 /* Success - we have a new channel */
17821 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
17822 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
17823 if (p->refer->localtransfer)
17824 p->refer->status = REFER_200OK;
17825 if (p->owner)
17826 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17827 append_history(p, "Xfer", "Refer succeeded.");
17828 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
17829 /* Do not hangup call, the other side do that when we say 200 OK */
17830 /* We could possibly implement a timer here, auto congestion */
17831 res = 0;
17832 } else {
17833 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
17834 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
17835 append_history(p, "Xfer", "Refer failed.");
17836 /* Failure of some kind */
17837 p->refer->status = REFER_FAILED;
17838 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
17839 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
17840 res = -1;
17842 return res;
17845 /*! \brief Handle incoming CANCEL request */
17846 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
17849 check_via(p, req);
17850 sip_alreadygone(p);
17852 /* At this point, we could have cancelled the invite at the same time
17853 as the other side sends a CANCEL. Our final reply with error code
17854 might not have been received by the other side before the CANCEL
17855 was sent, so let's just give up retransmissions and waiting for
17856 ACK on our error code. The call is hanging up any way. */
17857 if (p->invitestate == INV_TERMINATED)
17858 __sip_pretend_ack(p);
17859 else
17860 p->invitestate = INV_CANCELLED;
17862 if (p->owner && p->owner->_state == AST_STATE_UP) {
17863 /* This call is up, cancel is ignored, we need a bye */
17864 transmit_response(p, "200 OK", req);
17865 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
17866 return 0;
17869 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
17870 update_call_counter(p, DEC_CALL_LIMIT);
17872 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
17873 if (p->owner)
17874 ast_queue_hangup(p->owner);
17875 else
17876 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17877 if (p->initreq.len > 0) {
17878 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
17879 transmit_response(p, "200 OK", req);
17880 return 1;
17881 } else {
17882 transmit_response(p, "481 Call Leg Does Not Exist", req);
17883 return 0;
17887 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
17889 struct sip_pvt *p = chan->tech_pvt;
17890 char *all = "", *parse = ast_strdupa(preparse);
17891 int res = 0;
17892 AST_DECLARE_APP_ARGS(args,
17893 AST_APP_ARG(param);
17894 AST_APP_ARG(type);
17895 AST_APP_ARG(field);
17897 AST_STANDARD_APP_ARGS(args, parse);
17899 /* Sanity check */
17900 if (!IS_SIP_TECH(chan->tech)) {
17901 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
17902 return 0;
17905 memset(buf, 0, buflen);
17907 if (!strcasecmp(args.param, "peerip")) {
17908 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
17909 } else if (!strcasecmp(args.param, "recvip")) {
17910 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
17911 } else if (!strcasecmp(args.param, "from")) {
17912 ast_copy_string(buf, p->from, buflen);
17913 } else if (!strcasecmp(args.param, "uri")) {
17914 ast_copy_string(buf, p->uri, buflen);
17915 } else if (!strcasecmp(args.param, "useragent")) {
17916 ast_copy_string(buf, p->useragent, buflen);
17917 } else if (!strcasecmp(args.param, "peername")) {
17918 ast_copy_string(buf, p->peername, buflen);
17919 } else if (!strcasecmp(args.param, "t38passthrough")) {
17920 if (p->t38.state == T38_DISABLED) {
17921 ast_copy_string(buf, "0", sizeof("0"));
17922 } else { /* T38 is offered or enabled in this call */
17923 ast_copy_string(buf, "1", sizeof("1"));
17925 } else if (!strcasecmp(args.param, "rtpdest")) {
17926 struct sockaddr_in sin;
17928 if (ast_strlen_zero(args.type))
17929 args.type = "audio";
17931 if (!strcasecmp(args.type, "audio"))
17932 ast_rtp_get_peer(p->rtp, &sin);
17933 else if (!strcasecmp(args.type, "video"))
17934 ast_rtp_get_peer(p->vrtp, &sin);
17935 else if (!strcasecmp(args.type, "text"))
17936 ast_rtp_get_peer(p->trtp, &sin);
17937 else
17938 return -1;
17940 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
17941 } else if (!strcasecmp(args.param, "rtpqos")) {
17942 struct ast_rtp_quality qos;
17943 struct ast_rtp *rtp = p->rtp;
17945 memset(&qos, 0, sizeof(qos));
17947 if (ast_strlen_zero(args.type))
17948 args.type = "audio";
17949 if (ast_strlen_zero(args.field))
17950 args.field = "all";
17952 if (strcasecmp(args.type, "AUDIO") == 0) {
17953 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
17954 } else if (strcasecmp(args.type, "VIDEO") == 0) {
17955 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
17956 } else if (strcasecmp(args.type, "TEXT") == 0) {
17957 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
17958 } else {
17959 return -1;
17962 if (strcasecmp(args.field, "local_ssrc") == 0)
17963 snprintf(buf, buflen, "%u", qos.local_ssrc);
17964 else if (strcasecmp(args.field, "local_lostpackets") == 0)
17965 snprintf(buf, buflen, "%u", qos.local_lostpackets);
17966 else if (strcasecmp(args.field, "local_jitter") == 0)
17967 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
17968 else if (strcasecmp(args.field, "local_count") == 0)
17969 snprintf(buf, buflen, "%u", qos.local_count);
17970 else if (strcasecmp(args.field, "remote_ssrc") == 0)
17971 snprintf(buf, buflen, "%u", qos.remote_ssrc);
17972 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
17973 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
17974 else if (strcasecmp(args.field, "remote_jitter") == 0)
17975 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
17976 else if (strcasecmp(args.field, "remote_count") == 0)
17977 snprintf(buf, buflen, "%u", qos.remote_count);
17978 else if (strcasecmp(args.field, "rtt") == 0)
17979 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
17980 else if (strcasecmp(args.field, "all") == 0)
17981 ast_copy_string(buf, all, buflen);
17982 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
17984 else {
17985 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
17986 return -1;
17988 } else {
17989 res = -1;
17991 return res;
17994 /*! \brief Handle incoming BYE request */
17995 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
17997 struct ast_channel *c=NULL;
17998 int res;
17999 struct ast_channel *bridged_to;
18001 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
18002 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore && !p->owner) {
18003 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
18006 p->invitestate = INV_TERMINATED;
18008 copy_request(&p->initreq, req);
18009 if (sipdebug)
18010 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18011 check_via(p, req);
18012 sip_alreadygone(p);
18014 /* Get RTCP quality before end of call */
18015 if (p->do_history || p->owner) {
18016 struct ast_channel *bridge = ast_bridged_channel(p->owner);
18017 char *videoqos, *textqos;
18019 if (p->rtp) {
18020 if (p->do_history) {
18021 char *audioqos,
18022 *audioqos_jitter,
18023 *audioqos_loss,
18024 *audioqos_rtt;
18026 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
18027 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
18028 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
18029 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
18031 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
18032 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
18033 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
18034 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
18037 ast_rtp_set_vars(p->owner, p->rtp);
18040 if (bridge) {
18041 struct sip_pvt *q = bridge->tech_pvt;
18043 if (IS_SIP_TECH(bridge->tech) && q->rtp)
18044 ast_rtp_set_vars(bridge, q->rtp);
18047 if (p->vrtp) {
18048 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
18049 if (p->do_history)
18050 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
18051 if (p->owner)
18052 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
18055 if (p->trtp) {
18056 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
18057 if (p->do_history)
18058 append_history(p, "RTCPtext", "Quality:%s", textqos);
18059 if (p->owner)
18060 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
18064 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18065 stop_session_timer(p); /* Stop Session-Timer */
18067 if (!ast_strlen_zero(get_header(req, "Also"))) {
18068 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
18069 ast_inet_ntoa(p->recv.sin_addr));
18070 if (ast_strlen_zero(p->context))
18071 ast_string_field_set(p, context, default_context);
18072 res = get_also_info(p, req);
18073 if (!res) {
18074 c = p->owner;
18075 if (c) {
18076 bridged_to = ast_bridged_channel(c);
18077 if (bridged_to) {
18078 /* Don't actually hangup here... */
18079 ast_queue_control(c, AST_CONTROL_UNHOLD);
18080 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
18081 } else
18082 ast_queue_hangup(p->owner);
18084 } else {
18085 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
18086 if (p->owner)
18087 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18089 } else if (p->owner) {
18090 ast_queue_hangup(p->owner);
18091 ast_debug(3, "Received bye, issuing owner hangup\n");
18092 } else {
18093 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18094 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
18096 transmit_response(p, "200 OK", req);
18098 return 1;
18101 /*! \brief Handle incoming MESSAGE request */
18102 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
18104 if (!req->ignore) {
18105 if (req->debug)
18106 ast_verbose("Receiving message!\n");
18107 receive_message(p, req);
18108 } else
18109 transmit_response(p, "202 Accepted", req);
18110 return 1;
18113 static void add_peer_mwi_subs(struct sip_peer *peer)
18115 struct sip_mailbox *mailbox;
18117 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
18118 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
18119 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
18120 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
18121 AST_EVENT_IE_END);
18125 /*! \brief Handle incoming SUBSCRIBE request */
18126 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
18128 int gotdest;
18129 int res = 0;
18130 int firststate = AST_EXTENSION_REMOVED;
18131 struct sip_peer *authpeer = NULL;
18132 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
18133 const char *accept = get_header(req, "Accept");
18134 int resubscribe = (p->subscribed != NONE);
18135 char *temp, *event;
18136 struct ao2_iterator i;
18138 if (p->initreq.headers) {
18139 /* We already have a dialog */
18140 if (p->initreq.method != SIP_SUBSCRIBE) {
18141 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
18142 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
18143 transmit_response(p, "403 Forbidden (within dialog)", req);
18144 /* Do not destroy session, since we will break the call if we do */
18145 ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
18146 return 0;
18147 } else if (req->debug) {
18148 if (resubscribe)
18149 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
18150 else
18151 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
18155 /* Check if we have a global disallow setting on subscriptions.
18156 if so, we don't have to check peer settings after auth, which saves a lot of processing
18158 if (!global_allowsubscribe) {
18159 transmit_response(p, "403 Forbidden (policy)", req);
18160 p->needdestroy = 1;
18161 return 0;
18164 if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
18165 const char *to = get_header(req, "To");
18166 char totag[128];
18168 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
18169 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
18170 if (req->debug)
18171 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
18172 transmit_response(p, "481 Subscription does not exist", req);
18173 p->needdestroy = 1;
18174 return 0;
18177 /* Use this as the basis */
18178 if (req->debug)
18179 ast_verbose("Creating new subscription\n");
18181 copy_request(&p->initreq, req);
18182 if (sipdebug)
18183 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18184 check_via(p, req);
18185 } else if (req->debug && req->ignore)
18186 ast_verbose("Ignoring this SUBSCRIBE request\n");
18188 /* Find parameters to Event: header value and remove them for now */
18189 if (ast_strlen_zero(eventheader)) {
18190 transmit_response(p, "489 Bad Event", req);
18191 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
18192 p->needdestroy = 1;
18193 return 0;
18196 if ( (strchr(eventheader, ';'))) {
18197 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
18198 temp = strchr(event, ';');
18199 *temp = '\0'; /* Remove any options for now */
18200 /* We might need to use them later :-) */
18201 } else
18202 event = (char *) eventheader; /* XXX is this legal ? */
18204 /* Handle authentication */
18205 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
18206 /* if an authentication response was sent, we are done here */
18207 if (res == AUTH_CHALLENGE_SENT) /* authpeer = NULL here */
18208 return 0;
18209 if (res < 0) {
18210 if (res == AUTH_FAKE_AUTH) {
18211 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
18212 transmit_fake_auth_response(p, req, 1);
18213 } else {
18214 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
18215 transmit_response_reliable(p, "403 Forbidden", req);
18217 p->needdestroy = 1;
18218 return 0;
18221 /* At this point, authpeer cannot be NULL. Remember we hold a reference,
18222 * so we must release it when done.
18223 * XXX must remove all the checks for authpeer == NULL.
18226 /* Check if this device is allowed to subscribe at all */
18227 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
18228 transmit_response(p, "403 Forbidden (policy)", req);
18229 p->needdestroy = 1;
18230 if (authpeer)
18231 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
18232 return 0;
18235 /* Get destination right away */
18236 gotdest = get_destination(p, NULL);
18238 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
18239 parse_ok_contact(p, req);
18241 build_contact(p);
18242 if (strcmp(event, "message-summary") && gotdest) {
18243 transmit_response(p, "404 Not Found", req);
18244 p->needdestroy = 1;
18245 if (authpeer)
18246 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
18247 return 0;
18250 /* Initialize tag for new subscriptions */
18251 if (ast_strlen_zero(p->tag))
18252 make_our_tag(p->tag, sizeof(p->tag));
18254 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
18255 if (authpeer) /* We do not need the authpeer any more */
18256 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
18258 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
18259 /* Polycom phones only handle xpidf+xml, even if they say they can
18260 handle pidf+xml as well
18262 if (strstr(p->useragent, "Polycom")) {
18263 p->subscribed = XPIDF_XML;
18264 } else if (strstr(accept, "application/pidf+xml")) {
18265 p->subscribed = PIDF_XML; /* RFC 3863 format */
18266 } else if (strstr(accept, "application/dialog-info+xml")) {
18267 p->subscribed = DIALOG_INFO_XML;
18268 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
18269 } else if (strstr(accept, "application/cpim-pidf+xml")) {
18270 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
18271 } else if (strstr(accept, "application/xpidf+xml")) {
18272 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
18273 } else if (ast_strlen_zero(accept)) {
18274 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
18275 transmit_response(p, "489 Bad Event", req);
18277 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
18278 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
18279 p->needdestroy = 1;
18280 return 0;
18282 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
18283 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
18284 } else {
18285 /* Can't find a format for events that we know about */
18286 char mybuf[200];
18287 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", accept);
18288 transmit_response(p, mybuf, req);
18290 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
18291 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
18292 p->needdestroy = 1;
18293 return 0;
18295 } else if (!strcmp(event, "message-summary")) {
18296 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
18297 /* Format requested that we do not support */
18298 transmit_response(p, "406 Not Acceptable", req);
18299 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
18300 p->needdestroy = 1;
18301 if (authpeer)
18302 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
18303 return 0;
18305 /* Looks like they actually want a mailbox status
18306 This version of Asterisk supports mailbox subscriptions
18307 The subscribed URI needs to exist in the dial plan
18308 In most devices, this is configurable to the voicemailmain extension you use
18310 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
18311 transmit_response(p, "404 Not found (no mailbox)", req);
18312 p->needdestroy = 1;
18313 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
18314 if (authpeer)
18315 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
18316 return 0;
18319 p->subscribed = MWI_NOTIFICATION;
18320 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
18321 add_peer_mwi_subs(authpeer);
18323 if (authpeer->mwipvt && authpeer->mwipvt != p) { /* Destroy old PVT if this is a new one */
18324 /* We only allow one subscription per peer */
18325 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
18326 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
18327 /* sip_destroy(authpeer->mwipvt); */
18329 if (authpeer->mwipvt)
18330 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
18331 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p"); /* Link from peer to pvt UH- should this be dialog_ref()? */
18332 if (p->relatedpeer)
18333 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
18334 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer"); /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
18335 /* Do not release authpeer here */
18336 } else { /* At this point, Asterisk does not understand the specified event */
18337 transmit_response(p, "489 Bad Event", req);
18338 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
18339 p->needdestroy = 1;
18340 if (authpeer)
18341 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
18342 return 0;
18345 /* Add subscription for extension state from the PBX core */
18346 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
18347 if (p->stateid > -1) {
18348 ast_extension_state_del(p->stateid, cb_extensionstate);
18349 /* we need to dec the refcount, now that the extensionstate is removed */
18350 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
18352 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
18355 if (!req->ignore && p)
18356 p->lastinvite = seqno;
18357 if (p && !p->needdestroy) {
18358 p->expiry = atoi(get_header(req, "Expires"));
18360 /* check if the requested expiry-time is within the approved limits from sip.conf */
18361 if (p->expiry > max_expiry)
18362 p->expiry = max_expiry;
18363 if (p->expiry < min_expiry && p->expiry > 0)
18364 p->expiry = min_expiry;
18366 if (sipdebug) {
18367 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
18368 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
18369 else
18370 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
18372 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
18373 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18374 if (p->expiry > 0)
18375 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
18377 if (p->subscribed == MWI_NOTIFICATION) {
18378 transmit_response(p, "200 OK", req);
18379 if (p->relatedpeer) { /* Send first notification */
18380 ao2_lock(p->relatedpeer); /* was WRLOCK */
18381 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
18382 ao2_unlock(p->relatedpeer);
18384 } else {
18385 struct sip_pvt *p_old;
18387 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
18389 ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
18390 transmit_response(p, "404 Not found", req);
18391 p->needdestroy = 1;
18392 return 0;
18395 transmit_response(p, "200 OK", req);
18396 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
18397 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
18398 /* hide the 'complete' exten/context in the refer_to field for later display */
18399 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
18401 /* remove any old subscription from this peer for the same exten/context,
18402 as the peer has obviously forgotten about it and it's wasteful to wait
18403 for it to expire and send NOTIFY messages to the peer only to have them
18404 ignored (or generate errors)
18406 i = ao2_iterator_init(dialogs, 0);
18408 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18409 if (p_old == p) {
18410 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
18411 continue;
18413 if (p_old->initreq.method != SIP_SUBSCRIBE) {
18414 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
18415 continue;
18417 if (p_old->subscribed == NONE) {
18418 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
18419 continue;
18421 sip_pvt_lock(p_old);
18422 if (!strcmp(p_old->username, p->username)) {
18423 if (!strcmp(p_old->exten, p->exten) &&
18424 !strcmp(p_old->context, p->context)) {
18425 p_old->needdestroy = 1;
18426 sip_pvt_unlock(p_old);
18427 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
18428 break;
18431 sip_pvt_unlock(p_old);
18432 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
18435 if (!p->expiry)
18436 p->needdestroy = 1;
18438 return 1;
18441 /*! \brief Handle incoming REGISTER request */
18442 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
18444 enum check_auth_result res;
18446 /* Use this as the basis */
18447 copy_request(&p->initreq, req);
18448 if (sipdebug)
18449 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18450 check_via(p, req);
18451 if ((res = register_verify(p, sin, req, e)) < 0) {
18452 const char *reason;
18454 switch (res) {
18455 case AUTH_SECRET_FAILED:
18456 reason = "Wrong password";
18457 break;
18458 case AUTH_USERNAME_MISMATCH:
18459 reason = "Username/auth name mismatch";
18460 break;
18461 case AUTH_NOT_FOUND:
18462 reason = "No matching peer found";
18463 break;
18464 case AUTH_UNKNOWN_DOMAIN:
18465 reason = "Not a local domain";
18466 break;
18467 case AUTH_PEER_NOT_DYNAMIC:
18468 reason = "Peer is not supposed to register";
18469 break;
18470 case AUTH_ACL_FAILED:
18471 reason = "Device does not match ACL";
18472 break;
18473 case AUTH_BAD_TRANSPORT:
18474 reason = "Device not configured to use this transport type";
18475 break;
18476 default:
18477 reason = "Unknown failure";
18478 break;
18480 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
18481 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
18482 reason);
18483 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
18484 } else
18485 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
18487 if (res < 1) {
18488 /* Destroy the session, but keep us around for just a bit in case they don't
18489 get our 200 OK */
18490 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18492 return res;
18495 /*! \brief Handle incoming SIP requests (methods)
18496 \note This is where all incoming requests go first */
18497 /* called with p and p->owner locked */
18498 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
18500 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
18501 relatively static */
18502 const char *cmd;
18503 const char *cseq;
18504 const char *useragent;
18505 int seqno;
18506 int len;
18507 int respid;
18508 int res = 0;
18509 int debug = sip_debug_test_pvt(p);
18510 char *e;
18511 int error = 0;
18513 /* Get Method and Cseq */
18514 cseq = get_header(req, "Cseq");
18515 cmd = req->header[0];
18517 /* Must have Cseq */
18518 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
18519 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
18520 error = 1;
18522 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
18523 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
18524 error = 1;
18526 if (error) {
18527 if (!p->initreq.headers) /* New call */
18528 p->needdestroy = 1; /* Make sure we destroy this dialog */
18529 return -1;
18531 /* Get the command XXX */
18533 cmd = req->rlPart1;
18534 e = req->rlPart2;
18536 /* Save useragent of the client */
18537 useragent = get_header(req, "User-Agent");
18538 if (!ast_strlen_zero(useragent))
18539 ast_string_field_set(p, useragent, useragent);
18541 /* Find out SIP method for incoming request */
18542 if (req->method == SIP_RESPONSE) { /* Response to our request */
18543 /* When we get here, we know this is a SIP dialog where we've sent
18544 * a request and have a response, or at least get a response
18545 * within an existing dialog. Do some sanity checks, then
18546 * possibly process the request. In all cases, there function
18547 * terminates at the end of this block
18549 int ret = 0;
18551 if (p->ocseq < seqno && seqno != p->lastnoninvite) {
18552 ast_debug(1, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
18553 ret = -1;
18554 } else if (p->ocseq != seqno && seqno != p->lastnoninvite) {
18555 /* ignore means "don't do anything with it" but still have to
18556 * respond appropriately.
18557 * But in this case this is a response already, so we really
18558 * have nothing to do with this message, and even setting the
18559 * ignore flag is pointless.
18561 req->ignore = 1;
18562 append_history(p, "Ignore", "Ignoring this retransmit\n");
18563 } else if (e) {
18564 e = ast_skip_blanks(e);
18565 if (sscanf(e, "%d %n", &respid, &len) != 1) {
18566 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
18567 /* XXX maybe should do ret = -1; */
18568 } else if (respid <= 0) {
18569 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
18570 /* XXX maybe should do ret = -1; */
18571 } else { /* finally, something worth processing */
18572 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
18573 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
18574 extract_uri(p, req);
18575 handle_response(p, respid, e + len, req, seqno);
18578 return 0;
18581 /* New SIP request coming in
18582 (could be new request in existing SIP dialog as well...)
18585 p->method = req->method; /* Find out which SIP method they are using */
18586 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
18588 if (p->icseq && (p->icseq > seqno) ) {
18589 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
18590 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
18591 } else {
18592 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
18593 if (req->method != SIP_ACK)
18594 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
18595 return -1;
18597 } else if (p->icseq &&
18598 p->icseq == seqno &&
18599 req->method != SIP_ACK &&
18600 (p->method != SIP_CANCEL || p->alreadygone)) {
18601 /* ignore means "don't do anything with it" but still have to
18602 respond appropriately. We do this if we receive a repeat of
18603 the last sequence number */
18604 req->ignore = 1;
18605 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
18608 if (seqno >= p->icseq)
18609 /* Next should follow monotonically (but not necessarily
18610 incrementally -- thanks again to the genius authors of SIP --
18611 increasing */
18612 p->icseq = seqno;
18614 /* Find their tag if we haven't got it */
18615 if (ast_strlen_zero(p->theirtag)) {
18616 char tag[128];
18618 gettag(req, "From", tag, sizeof(tag));
18619 ast_string_field_set(p, theirtag, tag);
18621 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
18623 if (pedanticsipchecking) {
18624 /* If this is a request packet without a from tag, it's not
18625 correct according to RFC 3261 */
18626 /* Check if this a new request in a new dialog with a totag already attached to it,
18627 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
18628 if (!p->initreq.headers && req->has_to_tag) {
18629 /* If this is a first request and it got a to-tag, it is not for us */
18630 if (!req->ignore && req->method == SIP_INVITE) {
18631 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
18632 /* Will cease to exist after ACK */
18633 } else if (req->method != SIP_ACK) {
18634 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
18635 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18636 } else {
18637 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
18639 return res;
18643 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
18644 transmit_response(p, "400 Bad request", req);
18645 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18646 return -1;
18649 /* Handle various incoming SIP methods in requests */
18650 switch (p->method) {
18651 case SIP_OPTIONS:
18652 res = handle_request_options(p, req);
18653 break;
18654 case SIP_INVITE:
18655 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
18656 break;
18657 case SIP_REFER:
18658 res = handle_request_refer(p, req, debug, seqno, nounlock);
18659 break;
18660 case SIP_CANCEL:
18661 res = handle_request_cancel(p, req);
18662 break;
18663 case SIP_BYE:
18664 res = handle_request_bye(p, req);
18665 break;
18666 case SIP_MESSAGE:
18667 res = handle_request_message(p, req);
18668 break;
18669 case SIP_SUBSCRIBE:
18670 res = handle_request_subscribe(p, req, sin, seqno, e);
18671 break;
18672 case SIP_REGISTER:
18673 res = handle_request_register(p, req, sin, e);
18674 break;
18675 case SIP_INFO:
18676 if (req->debug)
18677 ast_verbose("Receiving INFO!\n");
18678 if (!req->ignore)
18679 handle_request_info(p, req);
18680 else /* if ignoring, transmit response */
18681 transmit_response(p, "200 OK", req);
18682 break;
18683 case SIP_NOTIFY:
18684 res = handle_request_notify(p, req, sin, seqno, e);
18685 break;
18686 case SIP_ACK:
18687 /* Make sure we don't ignore this */
18688 if (seqno == p->pendinginvite) {
18689 p->invitestate = INV_TERMINATED;
18690 p->pendinginvite = 0;
18691 __sip_ack(p, seqno, 1 /* response */, 0);
18692 if (find_sdp(req)) {
18693 if (process_sdp(p, req, SDP_T38_NONE))
18694 return -1;
18696 check_pendings(p);
18698 /* Got an ACK that we did not match. Ignore silently */
18699 if (!p->lastinvite && ast_strlen_zero(p->randdata))
18700 p->needdestroy = 1;
18701 break;
18702 default:
18703 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
18704 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
18705 cmd, ast_inet_ntoa(p->sa.sin_addr));
18706 /* If this is some new method, and we don't have a call, destroy it now */
18707 if (!p->initreq.headers)
18708 p->needdestroy = 1;
18709 break;
18711 return res;
18714 /*! \brief Read data from SIP socket
18715 \note sipsock_read locks the owner channel while we are processing the SIP message
18716 \return 1 on error, 0 on success
18717 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
18719 static int sipsock_read(int *id, int fd, short events, void *ignore)
18721 struct sip_request req;
18722 struct sockaddr_in sin = { 0, };
18723 int res;
18724 socklen_t len = sizeof(sin);
18725 static char readbuf[65535];
18727 memset(&req, 0, sizeof(req));
18728 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
18729 if (res < 0) {
18730 #if !defined(__FreeBSD__)
18731 if (errno == EAGAIN)
18732 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
18733 else
18734 #endif
18735 if (errno != ECONNREFUSED)
18736 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
18737 return 1;
18739 readbuf[res] = '\0';
18740 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
18741 return 1;
18742 ast_str_set(&req.data, 0, "%s", readbuf);
18743 if (res == sizeof(req.data) - 1) {
18744 ast_debug(1, "Received packet exceeds buffer. Data is possibly lost\n");
18745 req.data->str[sizeof(req.data) - 1] = '\0';
18746 } else
18747 req.data->str[res] = '\0';
18748 req.len = res;
18750 req.socket.fd = sipsock;
18751 req.socket.type = SIP_TRANSPORT_UDP;
18752 req.socket.ser = NULL;
18753 req.socket.port = bindaddr.sin_port;
18755 handle_request_do(&req, &sin);
18756 if (req.data) {
18757 ast_free(req.data);
18758 req.data = NULL;
18761 return 1;
18764 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
18766 struct sip_pvt *p;
18767 int recount = 0;
18768 int nounlock = 0;
18769 int lockretry;
18771 if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
18772 req->debug = 1;
18773 if (pedanticsipchecking)
18774 req->len = lws2sws(req->data->str, req->len); /* Fix multiline headers */
18775 if (req->debug) {
18776 ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n",
18777 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
18778 ntohs(sin->sin_port), req->data->str);
18781 if(parse_request(req) == -1) { /* Bad packet, can't parse */
18782 ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
18783 return 1;
18786 req->method = find_sip_method(req->rlPart1);
18788 if (req->debug)
18789 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
18791 if (req->headers < 2) { /* Must have at least two headers */
18792 ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
18793 return 1;
18796 /* Process request, with netlock held, and with usual deadlock avoidance */
18797 for (lockretry = 100; lockretry > 0; lockretry--) {
18798 ast_mutex_lock(&netlock);
18800 /* Find the active SIP dialog or create a new one */
18801 p = find_call(req, sin, req->method); /* returns p locked */
18802 if (p == NULL) {
18803 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
18804 ast_mutex_unlock(&netlock);
18805 return 1;
18808 copy_socket_data(&p->socket, &req->socket);
18810 /* Go ahead and lock the owner if it has one -- we may need it */
18811 /* becaues this is deadlock-prone, we need to try and unlock if failed */
18812 if (!p->owner || !ast_channel_trylock(p->owner))
18813 break; /* locking succeeded */
18814 ast_debug(1, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
18815 sip_pvt_unlock(p);
18816 if (lockretry != 1)
18817 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
18818 ast_mutex_unlock(&netlock);
18819 /* Sleep for a very short amount of time */
18820 usleep(1);
18822 p->recv = *sin;
18824 if (p->do_history) /* This is a request or response, note what it was for */
18825 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), req->rlPart2);
18827 if (!lockretry) {
18828 if (p->owner)
18829 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
18830 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
18831 if (req->method != SIP_ACK)
18832 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
18833 /* XXX We could add retry-after to make sure they come back */
18834 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
18835 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
18836 return 1;
18839 nounlock = 0;
18840 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
18841 /* Request failed */
18842 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
18845 if (recount)
18846 ast_update_use_count();
18848 if (p->owner && !nounlock)
18849 ast_channel_unlock(p->owner);
18850 sip_pvt_unlock(p);
18851 ast_mutex_unlock(&netlock);
18852 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
18853 return 1;
18856 /*! \brief Returns the port to use for this socket */
18857 static int sip_standard_port(struct sip_socket s)
18859 if (s.type & SIP_TRANSPORT_TLS)
18860 return s.port == htons(STANDARD_TLS_PORT);
18861 else
18862 return s.port == htons(STANDARD_SIP_PORT);
18865 /*! \todo document this function. */
18866 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
18868 struct sip_threadinfo *th;
18870 AST_LIST_LOCK(&threadl);
18871 AST_LIST_TRAVERSE(&threadl, th, list) {
18872 if ((s->sin_family == th->ser->requestor.sin_family) &&
18873 (s->sin_addr.s_addr == th->ser->requestor.sin_addr.s_addr) &&
18874 (s->sin_port == th->ser->requestor.sin_port)) {
18875 AST_LIST_UNLOCK(&threadl);
18876 return th->ser;
18879 AST_LIST_UNLOCK(&threadl);
18880 return NULL;
18883 /*! \todo document this function. */
18884 static int sip_prepare_socket(struct sip_pvt *p)
18886 struct sip_socket *s = &p->socket;
18887 static const char name[] = "SIP socket";
18888 struct ast_tcptls_session_instance *ser;
18889 struct server_args ca = {
18890 .name = name,
18891 .accept_fd = -1,
18894 if (s->fd != -1)
18895 return s->fd;
18897 if (p->outboundproxy && p->outboundproxy->transport) {
18898 s->type = p->outboundproxy->transport;
18901 if (s->type & SIP_TRANSPORT_UDP) {
18902 s->fd = sipsock;
18903 return s->fd;
18906 ca.sin = *(sip_real_dst(p));
18908 if ((ser = sip_tcp_locate(&ca.sin))) {
18909 s->fd = ser->fd;
18910 if (s->ser) {
18911 ao2_ref(s->ser, -1);
18912 s->ser = NULL;
18914 ao2_ref(ser, +1);
18915 s->ser = ser;
18916 return s->fd;
18919 if (s->ser && s->ser->parent->tls_cfg) {
18920 ca.tls_cfg = s->ser->parent->tls_cfg;
18921 } else {
18922 if (s->type & SIP_TRANSPORT_TLS) {
18923 ca.tls_cfg = ast_calloc(1, sizeof(*ca.tls_cfg));
18924 if (!ca.tls_cfg)
18925 return -1;
18926 memcpy(ca.tls_cfg, &default_tls_cfg, sizeof(*ca.tls_cfg));
18927 if (!ast_strlen_zero(p->tohost))
18928 ast_copy_string(ca.hostname, p->tohost, sizeof(ca.hostname));
18932 if (s->ser) {
18933 /* the pvt socket already has a server instance ... */
18934 } else {
18935 s->ser = ast_tcptls_client_start(&ca);
18938 if (!s->ser) {
18939 if (ca.tls_cfg)
18940 ast_free(ca.tls_cfg);
18941 return -1;
18944 s->fd = ca.accept_fd;
18946 /* Give the new thread a reference */
18947 ao2_ref(s->ser, +1);
18949 if (ast_pthread_create_background(&ca.master, NULL, sip_tcp_worker_fn, s->ser)) {
18950 ast_debug(1, "Unable to launch '%s'.", ca.name);
18951 ao2_ref(s->ser, -1);
18952 close(ca.accept_fd);
18953 s->fd = ca.accept_fd = -1;
18956 return s->fd;
18960 * \brief Small function to parse a config line for a host with a transport
18961 * i.e. tls://www.google.com:8056
18963 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
18965 char *port;
18967 if ((*hostname = strstr(line, "://"))) {
18968 *hostname += 3;
18970 if (!strncasecmp(line, "tcp", 3))
18971 *transport = SIP_TRANSPORT_TCP;
18972 else if (!strncasecmp(line, "tls", 3))
18973 *transport = SIP_TRANSPORT_TLS;
18974 else if (!strncasecmp(line, "udp", 3))
18975 *transport = SIP_TRANSPORT_UDP;
18976 else
18977 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
18978 } else {
18979 *hostname = line;
18980 *transport = SIP_TRANSPORT_UDP;
18983 if ((line = strrchr(*hostname, '@')))
18984 line++;
18985 else
18986 line = *hostname;
18988 if ((port = strrchr(line, ':'))) {
18989 *port++ = '\0';
18991 if (!sscanf(port, "%u", portnum)) {
18992 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
18993 port = NULL;
18997 if (!port) {
18998 if (*transport & SIP_TRANSPORT_TLS) {
18999 *portnum = STANDARD_TLS_PORT;
19000 } else {
19001 *portnum = STANDARD_SIP_PORT;
19005 return 0;
19009 * \brief Get cached MWI info
19010 * \retval 0 At least one message is waiting
19011 * \retval 1 no messages waiting
19013 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
19015 struct sip_mailbox *mailbox;
19017 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
19018 struct ast_event *event;
19019 event = ast_event_get_cached(AST_EVENT_MWI,
19020 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
19021 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
19022 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
19023 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
19024 AST_EVENT_IE_END);
19025 if (!event)
19026 continue;
19027 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
19028 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
19029 ast_event_destroy(event);
19032 return (*new || *old) ? 0 : 1;
19035 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
19036 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
19038 /* Called with peerl lock, but releases it */
19039 struct sip_pvt *p;
19040 int newmsgs = 0, oldmsgs = 0;
19042 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
19043 return 0;
19045 /* Do we have an IP address? If not, skip this peer */
19046 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
19047 return 0;
19049 if (event) {
19050 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
19051 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
19052 } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
19053 /* got it! Don't keep looking. */
19054 } else if (cache_only) {
19055 return 0;
19056 } else { /* Fall back to manually checking the mailbox */
19057 struct ast_str *mailbox_str = ast_str_alloca(512);
19058 peer_mailboxes_to_str(&mailbox_str, peer);
19059 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
19062 if (peer->mwipvt) {
19063 /* Base message on subscription */
19064 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
19065 } else {
19066 /* Build temporary dialog for this message */
19067 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
19068 return -1;
19069 if (create_addr_from_peer(p, peer)) {
19070 /* Maybe they're not registered, etc. */
19071 dialog_unlink_all(p, TRUE, TRUE);
19072 dialog_unref(p, "unref dialog p just created via sip_alloc");
19073 /* sip_destroy(p); */
19074 return 0;
19076 /* Recalculate our side, and recalculate Call ID */
19077 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
19078 build_via(p);
19079 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
19080 build_callid_pvt(p);
19081 ao2_t_link(dialogs, p, "Linking in under new name");
19082 /* Destroy this session after 32 secs */
19083 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19086 /* Send MWI */
19087 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19088 /* the following will decrement the refcount on p as it finishes */
19089 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
19090 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
19091 return 0;
19094 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
19095 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
19097 /* If we have no RTP or no active owner, no need to check timers */
19098 if (!dialog->rtp || !dialog->owner)
19099 return;
19100 /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
19102 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
19103 return;
19105 /* If the call is involved in a T38 fax session do not check RTP timeout */
19106 if (dialog->t38.state == T38_ENABLED)
19107 return;
19109 /* If we have no timers set, return now */
19110 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
19111 return;
19113 /* Check AUDIO RTP keepalives */
19114 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
19115 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
19116 /* Need to send an empty RTP packet */
19117 dialog->lastrtptx = time(NULL);
19118 ast_rtp_sendcng(dialog->rtp, 0);
19121 /*! \todo Check video RTP keepalives
19123 Do we need to move the lastrtptx to the RTP structure to have one for audio and one
19124 for video? It really does belong to the RTP structure.
19127 /* Check AUDIO RTP timers */
19128 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
19129 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
19131 /* Might be a timeout now -- see if we're on hold */
19132 struct sockaddr_in sin;
19133 ast_rtp_get_peer(dialog->rtp, &sin);
19134 if (sin.sin_addr.s_addr || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
19135 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
19136 /* Needs a hangup */
19137 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
19138 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
19139 sip_pvt_unlock(dialog);
19140 usleep(1);
19141 sip_pvt_lock(dialog);
19143 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
19144 dialog->owner->name, (long) (t - dialog->lastrtprx));
19145 /* Issue a softhangup */
19146 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
19147 ast_channel_unlock(dialog->owner);
19148 /* forget the timeouts for this call, since a hangup
19149 has already been requested and we don't want to
19150 repeatedly request hangups
19152 ast_rtp_set_rtptimeout(dialog->rtp, 0);
19153 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
19154 if (dialog->vrtp) {
19155 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
19156 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
19163 /*! \brief The SIP monitoring thread
19164 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
19165 (and thus do not have a separate thread) indefinitely
19167 static void *do_monitor(void *data)
19169 int res;
19170 time_t t;
19171 int reloading;
19173 /* Add an I/O event to our SIP UDP socket */
19174 if (sipsock > -1)
19175 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
19177 /* From here on out, we die whenever asked */
19178 for(;;) {
19179 /* Check for a reload request */
19180 ast_mutex_lock(&sip_reload_lock);
19181 reloading = sip_reloading;
19182 sip_reloading = FALSE;
19183 ast_mutex_unlock(&sip_reload_lock);
19184 if (reloading) {
19185 ast_verb(1, "Reloading SIP\n");
19186 sip_do_reload(sip_reloadreason);
19188 /* Change the I/O fd of our UDP socket */
19189 if (sipsock > -1) {
19190 if (sipsock_read_id)
19191 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
19192 else
19193 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
19194 } else if (sipsock_read_id) {
19195 ast_io_remove(io, sipsock_read_id);
19196 sipsock_read_id = NULL;
19200 /* Check for dialogs needing to be killed */
19201 t = time(NULL);
19202 /* don't scan the dialogs list if it hasn't been a reasonable period
19203 of time since the last time we did it (when MWI is being sent, we can
19204 get back to this point every millisecond or less)
19206 ao2_t_callback(dialogs, OBJ_UNLINK|OBJ_NODATA, dialog_needdestroy, &t, "callback to remove dialogs w/needdestroy");
19208 /* the old methodology would be to restart the search for dialogs to delete with every
19209 dialog that was found and destroyed, probably because the list contents would change,
19210 so we'd need to restart. This isn't the best thing to do with callbacks. */
19212 pthread_testcancel();
19213 /* Wait for sched or io */
19214 res = ast_sched_wait(sched);
19215 if ((res < 0) || (res > 1000))
19216 res = 1000;
19217 res = ast_io_wait(io, res);
19218 if (res > 20)
19219 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
19220 ast_mutex_lock(&monlock);
19221 if (res >= 0) {
19222 res = ast_sched_runq(sched);
19223 if (res >= 20)
19224 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
19226 ast_mutex_unlock(&monlock);
19229 /* Never reached */
19230 return NULL;
19233 /*! \brief Start the channel monitor thread */
19234 static int restart_monitor(void)
19236 /* If we're supposed to be stopped -- stay stopped */
19237 if (monitor_thread == AST_PTHREADT_STOP)
19238 return 0;
19239 ast_mutex_lock(&monlock);
19240 if (monitor_thread == pthread_self()) {
19241 ast_mutex_unlock(&monlock);
19242 ast_log(LOG_WARNING, "Cannot kill myself\n");
19243 return -1;
19245 if (monitor_thread != AST_PTHREADT_NULL) {
19246 /* Wake up the thread */
19247 pthread_kill(monitor_thread, SIGURG);
19248 } else {
19249 /* Start a new monitor */
19250 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
19251 ast_mutex_unlock(&monlock);
19252 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
19253 return -1;
19256 ast_mutex_unlock(&monlock);
19257 return 0;
19261 /*! \brief Session-Timers: Restart session timer */
19262 static void restart_session_timer(struct sip_pvt *p)
19264 if (!p->stimer) {
19265 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
19266 return;
19269 if (p->stimer->st_active == TRUE) {
19270 AST_SCHED_DEL(sched, p->stimer->st_schedid);
19271 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
19272 start_session_timer(p);
19277 /*! \brief Session-Timers: Stop session timer */
19278 static void stop_session_timer(struct sip_pvt *p)
19280 if (!p->stimer) {
19281 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
19282 return;
19285 if (p->stimer->st_active == TRUE) {
19286 p->stimer->st_active = FALSE;
19287 AST_SCHED_DEL(sched, p->stimer->st_schedid);
19288 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
19293 /*! \brief Session-Timers: Start session timer */
19294 static void start_session_timer(struct sip_pvt *p)
19296 if (!p->stimer) {
19297 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
19298 return;
19301 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, p);
19302 if (p->stimer->st_schedid < 0) {
19303 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
19305 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
19309 /*! \brief Session-Timers: Process session refresh timeout event */
19310 static int proc_session_timer(const void *vp)
19312 struct sip_pvt *p = (struct sip_pvt *) vp;
19313 int sendreinv = FALSE;
19315 if (!p->stimer) {
19316 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
19317 return 0;
19320 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
19322 if (!p->owner) {
19323 if (p->stimer->st_active == TRUE) {
19324 stop_session_timer(p);
19326 return 0;
19329 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
19330 return 0;
19333 switch (p->stimer->st_ref) {
19334 case SESSION_TIMER_REFRESHER_UAC:
19335 if (p->outgoing_call == TRUE) {
19336 sendreinv = TRUE;
19338 break;
19339 case SESSION_TIMER_REFRESHER_UAS:
19340 if (p->outgoing_call != TRUE) {
19341 sendreinv = TRUE;
19343 break;
19344 default:
19345 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
19346 return -1;
19349 if (sendreinv == TRUE) {
19350 transmit_reinvite_with_sdp(p, FALSE, TRUE);
19351 } else {
19352 p->stimer->st_expirys++;
19353 if (p->stimer->st_expirys >= 2) {
19354 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
19355 stop_session_timer(p);
19357 while (p->owner && ast_channel_trylock(p->owner)) {
19358 sip_pvt_unlock(p);
19359 usleep(1);
19360 sip_pvt_lock(p);
19363 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
19364 ast_channel_unlock(p->owner);
19367 return 1;
19371 /*! \brief Session-Timers: Function for parsing Min-SE header */
19372 int parse_minse (const char *p_hdrval, int *const p_interval)
19374 if (ast_strlen_zero(p_hdrval)) {
19375 ast_log(LOG_WARNING, "Null Min-SE header\n");
19376 return -1;
19379 *p_interval = 0;
19380 p_hdrval = ast_skip_blanks(p_hdrval);
19381 if (!sscanf(p_hdrval, "%d", p_interval)) {
19382 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
19383 return -1;
19386 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
19387 return 0;
19391 /*! \brief Session-Timers: Function for parsing Session-Expires header */
19392 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
19394 char *p_token;
19395 int ref_idx;
19396 char *p_se_hdr;
19398 if (ast_strlen_zero(p_hdrval)) {
19399 ast_log(LOG_WARNING, "Null Session-Expires header\n");
19400 return -1;
19403 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
19404 *p_interval = 0;
19406 p_se_hdr = ast_strdupa(p_hdrval);
19407 p_se_hdr = ast_skip_blanks(p_se_hdr);
19409 while ((p_token = strsep(&p_se_hdr, ";"))) {
19410 p_token = ast_skip_blanks(p_token);
19411 if (!sscanf(p_token, "%d", p_interval)) {
19412 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
19413 return -1;
19416 ast_debug(2, "Session-Expires: %d\n", *p_interval);
19418 if (!p_se_hdr)
19419 continue;
19421 ref_idx = strlen("refresher=");
19422 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
19423 p_se_hdr += ref_idx;
19424 p_se_hdr = ast_skip_blanks(p_se_hdr);
19426 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
19427 *p_ref = SESSION_TIMER_REFRESHER_UAC;
19428 ast_debug(2, "Refresher: UAC\n");
19429 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
19430 *p_ref = SESSION_TIMER_REFRESHER_UAS;
19431 ast_debug(2, "Refresher: UAS\n");
19432 } else {
19433 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
19434 return -1;
19436 break;
19439 return 0;
19443 /*! \brief Handle 422 response to INVITE with session-timer requested
19445 Session-Timers: An INVITE originated by Asterisk that asks for session-timers support
19446 from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
19447 server tells Asterisk that the session refresh interval offered by Asterisk is too low
19448 for them. The proc_422_rsp() function handles a 422 response. It extracts the Min-SE
19449 header that comes back in 422 and sends a new INVITE accordingly. */
19450 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
19452 int rtn;
19453 const char *p_hdrval;
19454 int minse;
19456 p_hdrval = get_header(rsp, "Min-SE");
19457 if (ast_strlen_zero(p_hdrval)) {
19458 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
19459 return;
19461 rtn = parse_minse(p_hdrval, &minse);
19462 if (rtn != 0) {
19463 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
19464 return;
19466 p->stimer->st_interval = minse;
19467 transmit_invite(p, SIP_INVITE, 1, 2);
19471 /*! \brief Get Max or Min SE (session timer expiry)
19472 * \param p pointer to the SIP dialog
19473 * \param max if true, get max se, otherwise min se
19475 int st_get_se(struct sip_pvt *p, int max)
19477 if (max == TRUE) {
19478 if (p->stimer->st_cached_max_se) {
19479 return p->stimer->st_cached_max_se;
19480 } else if (p->peername) {
19481 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, TRUE);
19482 if (pp) {
19483 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
19484 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
19485 return (p->stimer->st_cached_max_se);
19488 p->stimer->st_cached_max_se = global_max_se;
19489 return (p->stimer->st_cached_max_se);
19490 } else {
19491 if (p->stimer->st_cached_min_se) {
19492 return p->stimer->st_cached_min_se;
19493 } else if (p->peername) {
19494 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, TRUE);
19495 if (pp) {
19496 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
19497 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
19498 return (p->stimer->st_cached_min_se);
19501 p->stimer->st_cached_min_se = global_min_se;
19502 return (p->stimer->st_cached_min_se);
19507 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
19508 * \param p pointer to the SIP dialog
19510 enum st_refresher st_get_refresher(struct sip_pvt *p)
19512 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
19513 return p->stimer->st_cached_ref;
19515 if (p->peername) {
19516 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, TRUE);
19517 if (pp) {
19518 p->stimer->st_cached_ref = pp->stimer.st_ref;
19519 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
19520 return pp->stimer.st_ref;
19524 p->stimer->st_cached_ref = global_st_refresher;
19525 return global_st_refresher;
19529 /*! \brief Get the session-timer mode
19530 * \param p pointer to the SIP dialog
19532 enum st_mode st_get_mode(struct sip_pvt *p)
19534 if (!p->stimer)
19535 sip_st_alloc(p);
19537 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
19538 return p->stimer->st_cached_mode;
19540 if (p->peername) {
19541 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, TRUE);
19542 if (pp) {
19543 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
19544 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
19545 return pp->stimer.st_mode_oper;
19549 p->stimer->st_cached_mode = global_st_mode;
19550 return global_st_mode;
19554 /*! \brief React to lack of answer to Qualify poke */
19555 static int sip_poke_noanswer(const void *data)
19557 struct sip_peer *peer = (struct sip_peer *)data;
19559 peer->pokeexpire = -1;
19560 if (peer->lastms > -1) {
19561 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
19562 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
19563 if (global_regextenonqualify)
19564 register_peer_exten(peer, FALSE);
19566 if (peer->call) {
19567 dialog_unlink_all(peer->call, TRUE, TRUE);
19568 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
19569 /* peer->call = sip_destroy(peer->call);*/
19572 peer->lastms = -1;
19573 ast_device_state_changed("SIP/%s", peer->name);
19574 /* Try again quickly */
19575 AST_SCHED_REPLACE(peer->pokeexpire, sched,
19576 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
19577 return 0;
19580 /*! \brief Check availability of peer, also keep NAT open
19581 \note This is done with 60 seconds between each ping,
19582 unless forced by cli or manager. If peer is unreachable,
19583 we check every 10th second by default.
19585 static int sip_poke_peer(struct sip_peer *peer, int force)
19587 struct sip_pvt *p;
19588 int xmitres = 0;
19590 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
19591 /* IF we have no IP, or this isn't to be monitored, return
19592 immediately after clearing things out */
19593 AST_SCHED_DEL(sched, peer->pokeexpire);
19595 peer->lastms = 0;
19596 if (peer->call) {
19597 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
19599 return 0;
19601 if (peer->call) {
19602 if (sipdebug) {
19603 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
19605 dialog_unlink_all(peer->call, TRUE, TRUE);
19606 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
19607 /* peer->call = sip_destroy(peer->call); */
19609 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS))) {
19610 return -1;
19612 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
19614 p->sa = peer->addr;
19615 p->recv = peer->addr;
19616 p->socket = peer->socket;
19617 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
19618 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
19620 /* Send OPTIONs to peer's fullcontact */
19621 if (!ast_strlen_zero(peer->fullcontact))
19622 ast_string_field_set(p, fullcontact, peer->fullcontact);
19624 if (!ast_strlen_zero(peer->tohost))
19625 ast_string_field_set(p, tohost, peer->tohost);
19626 else
19627 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
19629 /* Recalculate our side, and recalculate Call ID */
19630 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
19631 build_via(p);
19632 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
19633 build_callid_pvt(p);
19634 ao2_t_link(dialogs, p, "Linking in under new name");
19636 AST_SCHED_DEL(sched, peer->pokeexpire);
19638 if (p->relatedpeer)
19639 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
19640 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
19641 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19642 #ifdef VOCAL_DATA_HACK
19643 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
19644 xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
19645 #else
19646 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
19647 #endif
19648 peer->ps = ast_tvnow();
19649 if (xmitres == XMIT_ERROR) {
19650 sip_poke_noanswer(peer); /* Immediately unreachable, network problems */
19651 } else if (!force) {
19652 AST_SCHED_REPLACE(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer);
19654 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
19655 return 0;
19658 /*! \brief Part of PBX channel interface
19659 \note
19660 \par Return values:---
19662 If we have qualify on and the device is not reachable, regardless of registration
19663 state we return AST_DEVICE_UNAVAILABLE
19665 For peers with call limit:
19666 - not registered AST_DEVICE_UNAVAILABLE
19667 - registered, no call AST_DEVICE_NOT_INUSE
19668 - registered, active calls AST_DEVICE_INUSE
19669 - registered, call limit reached AST_DEVICE_BUSY
19670 - registered, onhold AST_DEVICE_ONHOLD
19671 - registered, ringing AST_DEVICE_RINGING
19673 For peers without call limit:
19674 - not registered AST_DEVICE_UNAVAILABLE
19675 - registered AST_DEVICE_NOT_INUSE
19676 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
19678 Peers that does not have a known call and can't be reached by OPTIONS
19679 - unreachable AST_DEVICE_UNAVAILABLE
19681 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
19682 out a state by walking the channel list.
19684 The queue system (\ref app_queue.c) treats a member as "active"
19685 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
19687 When placing a call to the queue member, queue system sets a member to busy if
19688 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
19691 static int sip_devicestate(void *data)
19693 char *host;
19694 char *tmp;
19695 struct sip_peer *p;
19697 int res = AST_DEVICE_INVALID;
19699 /* make sure data is not null. Maybe unnecessary, but better be safe */
19700 host = ast_strdupa(data ? data : "");
19701 if ((tmp = strchr(host, '@')))
19702 host = tmp + 1;
19704 ast_debug(3, "Checking device state for peer %s\n", host);
19706 if ((p = find_peer(host, NULL, TRUE, TRUE))) {
19707 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
19708 /* we have an address for the peer */
19710 /* Check status in this order
19711 - Hold
19712 - Ringing
19713 - Busy (enforced only by call limit)
19714 - Inuse (we have a call)
19715 - Unreachable (qualify)
19716 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
19717 for registered devices */
19719 if (p->onHold)
19720 /* First check for hold or ring states */
19721 res = AST_DEVICE_ONHOLD;
19722 else if (p->inRinging) {
19723 if (p->inRinging == p->inUse)
19724 res = AST_DEVICE_RINGING;
19725 else
19726 res = AST_DEVICE_RINGINUSE;
19727 } else if (p->call_limit && (p->inUse == p->call_limit))
19728 /* check call limit */
19729 res = AST_DEVICE_BUSY;
19730 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
19731 /* We're forcing busy before we've reached the call limit */
19732 res = AST_DEVICE_BUSY;
19733 else if (p->call_limit && p->inUse)
19734 /* Not busy, but we do have a call */
19735 res = AST_DEVICE_INUSE;
19736 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
19737 /* We don't have a call. Are we reachable at all? Requires qualify= */
19738 res = AST_DEVICE_UNAVAILABLE;
19739 else /* Default reply if we're registered and have no other data */
19740 res = AST_DEVICE_NOT_INUSE;
19741 } else {
19742 /* there is no address, it's unavailable */
19743 res = AST_DEVICE_UNAVAILABLE;
19745 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
19746 } else {
19747 res = AST_DEVICE_UNKNOWN;
19750 return res;
19753 /*! \brief PBX interface function -build SIP pvt structure
19754 * SIP calls initiated by the PBX arrive here.
19756 * \verbatim
19757 * SIP Dial string syntax
19758 * SIP/exten@host!dnid
19759 * or SIP/host/exten!dnid
19760 * or SIP/host!dnid
19761 * \endverbatim
19763 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
19765 struct sip_pvt *p;
19766 struct ast_channel *tmpc = NULL;
19767 char *ext, *host;
19768 char tmp[256];
19769 char *dest = data;
19770 char *dnid;
19771 char *secret = NULL;
19772 char *md5secret = NULL;
19773 char *authname = NULL;
19774 int oldformat = format;
19776 /* mask request with some set of allowed formats.
19777 * XXX this needs to be fixed.
19778 * The original code uses AST_FORMAT_AUDIO_MASK, but it is
19779 * unclear what to use here. We have global_capabilities, which is
19780 * configured from sip.conf, and sip_tech.capabilities, which is
19781 * hardwired to all audio formats.
19783 format &= AST_FORMAT_AUDIO_MASK;
19784 if (!format) {
19785 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
19786 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
19787 return NULL;
19789 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
19791 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
19792 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
19793 *cause = AST_CAUSE_SWITCH_CONGESTION;
19794 return NULL;
19797 p->outgoing_call = TRUE;
19799 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
19800 dialog_unlink_all(p, TRUE, TRUE);
19801 dialog_unref(p, "unref dialog p from mem fail");
19802 /* sip_destroy(p); */
19803 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
19804 *cause = AST_CAUSE_SWITCH_CONGESTION;
19805 return NULL;
19808 /* Save the destination, the SIP dial string */
19809 ast_copy_string(tmp, dest, sizeof(tmp));
19812 /* Find DNID and take it away */
19813 dnid = strchr(tmp, '!');
19814 if (dnid != NULL) {
19815 *dnid++ = '\0';
19816 ast_string_field_set(p, todnid, dnid);
19819 /* Find at sign - @ */
19820 host = strchr(tmp, '@');
19821 if (host) {
19822 *host++ = '\0';
19823 ext = tmp;
19824 secret = strchr(ext, ':');
19825 if (secret) {
19826 *secret++ = '\0';
19827 md5secret = strchr(secret, ':');
19828 if (md5secret) {
19829 *md5secret++ = '\0';
19830 authname = strchr(md5secret, ':');
19831 if (authname)
19832 *authname++ = '\0';
19835 } else {
19836 ext = strchr(tmp, '/');
19837 if (ext)
19838 *ext++ = '\0';
19839 host = tmp;
19842 /* We now have
19843 host = peer name, DNS host name or DNS domain (for SRV)
19844 ext = extension (user part of URI)
19845 dnid = destination of the call (applies to the To: header)
19847 if (create_addr(p, host, NULL)) {
19848 *cause = AST_CAUSE_UNREGISTERED;
19849 ast_debug(3, "Cant create SIP call - target device not registred\n");
19850 dialog_unlink_all(p, TRUE, TRUE);
19851 dialog_unref(p, "unref dialog p UNREGISTERED");
19852 /* sip_destroy(p); */
19853 return NULL;
19855 if (ast_strlen_zero(p->peername) && ext)
19856 ast_string_field_set(p, peername, ext);
19857 /* Recalculate our side, and recalculate Call ID */
19858 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
19859 build_via(p);
19860 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
19861 build_callid_pvt(p);
19862 ao2_t_link(dialogs, p, "Linking in under new name");
19864 /* We have an extension to call, don't use the full contact here */
19865 /* This to enable dialing registered peers with extension dialling,
19866 like SIP/peername/extension
19867 SIP/peername will still use the full contact
19869 if (ext) {
19870 ast_string_field_set(p, username, ext);
19871 ast_string_field_set(p, fullcontact, NULL);
19873 if (secret && !ast_strlen_zero(secret))
19874 ast_string_field_set(p, peersecret, secret);
19876 if (md5secret && !ast_strlen_zero(md5secret))
19877 ast_string_field_set(p, peermd5secret, md5secret);
19879 if (authname && !ast_strlen_zero(authname))
19880 ast_string_field_set(p, authname, authname);
19881 #if 0
19882 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
19883 #endif
19884 p->prefcodec = oldformat; /* Format for this call */
19885 p->jointcapability = oldformat;
19886 sip_pvt_lock(p);
19887 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
19888 if (global_callevents)
19889 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
19890 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
19891 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
19892 sip_pvt_unlock(p);
19893 if (!tmpc) {
19894 dialog_unlink_all(p, TRUE, TRUE);
19895 /* sip_destroy(p); */
19897 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
19898 ast_update_use_count();
19899 restart_monitor();
19900 return tmpc;
19903 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
19904 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
19906 if (ast_strlen_zero(value))
19907 return;
19909 if (!ast_false(value)) {
19910 char buf[64];
19911 char *word, *next;
19913 ast_copy_string(buf, value, sizeof(buf));
19914 next = buf;
19915 while ((word = strsep(&next, ","))) {
19916 if (!strcasecmp(word, "port"))
19917 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
19918 else if (!strcasecmp(word, "invite"))
19919 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
19920 else
19921 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
19927 \brief Handle flag-type options common to configuration of devices - peers
19928 \param flags array of two struct ast_flags
19929 \param mask array of two struct ast_flags
19930 \param v linked list of config variables to process
19931 \returns non-zero if any config options were handled, zero otherwise
19933 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
19935 int res = 1;
19937 if (!strcasecmp(v->name, "trustrpid")) {
19938 ast_set_flag(&mask[0], SIP_TRUSTRPID);
19939 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
19940 } else if (!strcasecmp(v->name, "sendrpid")) {
19941 ast_set_flag(&mask[0], SIP_SENDRPID);
19942 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
19943 } else if (!strcasecmp(v->name, "g726nonstandard")) {
19944 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
19945 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
19946 } else if (!strcasecmp(v->name, "useclientcode")) {
19947 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
19948 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
19949 } else if (!strcasecmp(v->name, "dtmfmode")) {
19950 ast_set_flag(&mask[0], SIP_DTMF);
19951 ast_clear_flag(&flags[0], SIP_DTMF);
19952 if (!strcasecmp(v->value, "inband"))
19953 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
19954 else if (!strcasecmp(v->value, "rfc2833"))
19955 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
19956 else if (!strcasecmp(v->value, "info"))
19957 ast_set_flag(&flags[0], SIP_DTMF_INFO);
19958 else if (!strcasecmp(v->value, "shortinfo"))
19959 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
19960 else if (!strcasecmp(v->value, "auto"))
19961 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
19962 else {
19963 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
19964 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
19966 } else if (!strcasecmp(v->name, "nat")) {
19967 ast_set_flag(&mask[0], SIP_NAT);
19968 ast_clear_flag(&flags[0], SIP_NAT);
19969 if (!strcasecmp(v->value, "never"))
19970 ast_set_flag(&flags[0], SIP_NAT_NEVER);
19971 else if (!strcasecmp(v->value, "route"))
19972 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
19973 else if (ast_true(v->value))
19974 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
19975 else
19976 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
19977 } else if (!strcasecmp(v->name, "canreinvite")) {
19978 ast_set_flag(&mask[0], SIP_REINVITE);
19979 ast_clear_flag(&flags[0], SIP_REINVITE);
19980 if (ast_true(v->value)) {
19981 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
19982 } else if (!ast_false(v->value)) {
19983 char buf[64];
19984 char *word, *next = buf;
19986 ast_copy_string(buf, v->value, sizeof(buf));
19987 while ((word = strsep(&next, ","))) {
19988 if (!strcasecmp(word, "update")) {
19989 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
19990 } else if (!strcasecmp(word, "nonat")) {
19991 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
19992 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
19993 } else {
19994 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
19998 } else if (!strcasecmp(v->name, "insecure")) {
19999 ast_set_flag(&mask[0], SIP_INSECURE);
20000 ast_clear_flag(&flags[0], SIP_INSECURE);
20001 set_insecure_flags(&flags[0], v->value, v->lineno);
20002 } else if (!strcasecmp(v->name, "progressinband")) {
20003 ast_set_flag(&mask[0], SIP_PROG_INBAND);
20004 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
20005 if (ast_true(v->value))
20006 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
20007 else if (strcasecmp(v->value, "never"))
20008 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
20009 } else if (!strcasecmp(v->name, "promiscredir")) {
20010 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
20011 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
20012 } else if (!strcasecmp(v->name, "videosupport")) {
20013 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
20014 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
20015 } else if (!strcasecmp(v->name, "textsupport")) {
20016 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
20017 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
20018 res = 1;
20019 } else if (!strcasecmp(v->name, "allowoverlap")) {
20020 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
20021 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
20022 } else if (!strcasecmp(v->name, "allowsubscribe")) {
20023 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
20024 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
20025 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
20026 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
20027 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
20028 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
20029 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
20030 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
20031 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
20032 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
20033 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
20034 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
20035 #endif
20036 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
20037 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
20038 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
20039 } else if (!strcasecmp(v->name, "buggymwi")) {
20040 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
20041 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
20042 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
20043 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
20044 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
20045 } else
20046 res = 0;
20048 return res;
20051 /*! \brief Add SIP domain to list of domains we are responsible for */
20052 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
20054 struct domain *d;
20056 if (ast_strlen_zero(domain)) {
20057 ast_log(LOG_WARNING, "Zero length domain.\n");
20058 return 1;
20061 if (!(d = ast_calloc(1, sizeof(*d))))
20062 return 0;
20064 ast_copy_string(d->domain, domain, sizeof(d->domain));
20066 if (!ast_strlen_zero(context))
20067 ast_copy_string(d->context, context, sizeof(d->context));
20069 d->mode = mode;
20071 AST_LIST_LOCK(&domain_list);
20072 AST_LIST_INSERT_TAIL(&domain_list, d, list);
20073 AST_LIST_UNLOCK(&domain_list);
20075 if (sipdebug)
20076 ast_debug(1, "Added local SIP domain '%s'\n", domain);
20078 return 1;
20081 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
20082 static int check_sip_domain(const char *domain, char *context, size_t len)
20084 struct domain *d;
20085 int result = 0;
20087 AST_LIST_LOCK(&domain_list);
20088 AST_LIST_TRAVERSE(&domain_list, d, list) {
20089 if (strcasecmp(d->domain, domain))
20090 continue;
20092 if (len && !ast_strlen_zero(d->context))
20093 ast_copy_string(context, d->context, len);
20095 result = 1;
20096 break;
20098 AST_LIST_UNLOCK(&domain_list);
20100 return result;
20103 /*! \brief Clear our domain list (at reload) */
20104 static void clear_sip_domains(void)
20106 struct domain *d;
20108 AST_LIST_LOCK(&domain_list);
20109 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
20110 ast_free(d);
20111 AST_LIST_UNLOCK(&domain_list);
20115 /*! \brief Add realm authentication in list */
20116 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
20118 char authcopy[256];
20119 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
20120 char *stringp;
20121 struct sip_auth *a, *b, *auth;
20123 if (ast_strlen_zero(configuration))
20124 return authlist;
20126 ast_debug(1, "Auth config :: %s\n", configuration);
20128 ast_copy_string(authcopy, configuration, sizeof(authcopy));
20129 stringp = authcopy;
20131 username = stringp;
20132 realm = strrchr(stringp, '@');
20133 if (realm)
20134 *realm++ = '\0';
20135 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
20136 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
20137 return authlist;
20139 stringp = username;
20140 username = strsep(&stringp, ":");
20141 if (username) {
20142 secret = strsep(&stringp, ":");
20143 if (!secret) {
20144 stringp = username;
20145 md5secret = strsep(&stringp, "#");
20148 if (!(auth = ast_calloc(1, sizeof(*auth))))
20149 return authlist;
20151 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
20152 ast_copy_string(auth->username, username, sizeof(auth->username));
20153 if (secret)
20154 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
20155 if (md5secret)
20156 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
20158 /* find the end of the list */
20159 for (b = NULL, a = authlist; a ; b = a, a = a->next)
20161 if (b)
20162 b->next = auth; /* Add structure add end of list */
20163 else
20164 authlist = auth;
20166 ast_verb(3, "Added authentication for realm %s\n", realm);
20168 return authlist;
20172 /*! \brief Clear realm authentication list (at reload) */
20173 static int clear_realm_authentication(struct sip_auth *authlist)
20175 struct sip_auth *a = authlist;
20176 struct sip_auth *b;
20178 while (a) {
20179 b = a;
20180 a = a->next;
20181 ast_free(b);
20184 return 1;
20187 /*! \brief Find authentication for a specific realm */
20188 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
20190 struct sip_auth *a;
20192 for (a = authlist; a; a = a->next) {
20193 if (!strcasecmp(a->realm, realm))
20194 break;
20197 return a;
20200 /*! \brief
20201 * implement the setvar config line
20203 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
20205 struct ast_variable *tmpvar = NULL;
20206 char *varname = ast_strdupa(buf), *varval = NULL;
20208 if ((varval = strchr(varname, '='))) {
20209 *varval++ = '\0';
20210 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
20211 tmpvar->next = list;
20212 list = tmpvar;
20215 return list;
20218 /*! \brief Set peer defaults before configuring specific configurations */
20219 static void set_peer_defaults(struct sip_peer *peer)
20221 if (peer->expire == 0) {
20222 /* Don't reset expire or port time during reload
20223 if we have an active registration
20225 peer->expire = -1;
20226 peer->pokeexpire = -1;
20227 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
20228 peer->socket.type = SIP_TRANSPORT_UDP;
20229 peer->socket.fd = -1;
20231 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
20232 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
20233 strcpy(peer->context, default_context);
20234 strcpy(peer->subscribecontext, default_subscribecontext);
20235 strcpy(peer->language, default_language);
20236 strcpy(peer->mohinterpret, default_mohinterpret);
20237 strcpy(peer->mohsuggest, default_mohsuggest);
20238 peer->addr.sin_family = AF_INET;
20239 peer->defaddr.sin_family = AF_INET;
20240 peer->capability = global_capability;
20241 peer->maxcallbitrate = default_maxcallbitrate;
20242 peer->rtptimeout = global_rtptimeout;
20243 peer->rtpholdtimeout = global_rtpholdtimeout;
20244 peer->rtpkeepalive = global_rtpkeepalive;
20245 peer->allowtransfer = global_allowtransfer;
20246 peer->autoframing = global_autoframing;
20247 peer->qualifyfreq = global_qualifyfreq;
20248 if (global_callcounter)
20249 peer->call_limit=999;
20250 strcpy(peer->vmexten, default_vmexten);
20251 peer->secret[0] = '\0';
20252 peer->md5secret[0] = '\0';
20253 peer->cid_num[0] = '\0';
20254 peer->cid_name[0] = '\0';
20255 peer->fromdomain[0] = '\0';
20256 peer->fromuser[0] = '\0';
20257 peer->regexten[0] = '\0';
20258 peer->callgroup = 0;
20259 peer->pickupgroup = 0;
20260 peer->maxms = default_qualify;
20261 peer->prefs = default_prefs;
20262 peer->stimer.st_mode_oper = global_st_mode; /* Session-Timers */
20263 peer->stimer.st_ref = global_st_refresher;
20264 peer->stimer.st_min_se = global_min_se;
20265 peer->stimer.st_max_se = global_max_se;
20266 peer->timer_t1 = global_t1;
20267 peer->timer_b = global_timer_b;
20268 clear_peer_mailboxes(peer);
20271 /*! \brief Create temporary peer (used in autocreatepeer mode) */
20272 static struct sip_peer *temp_peer(const char *name)
20274 struct sip_peer *peer;
20276 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
20277 return NULL;
20279 ast_atomic_fetchadd_int(&apeerobjs, 1);
20280 set_peer_defaults(peer);
20282 ast_copy_string(peer->name, name, sizeof(peer->name));
20284 peer->selfdestruct = TRUE;
20285 peer->host_dynamic = TRUE;
20286 peer->prefs = default_prefs;
20287 reg_source_db(peer);
20289 return peer;
20292 /*! \todo document this function */
20293 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
20295 char *next, *mbox, *context;
20297 next = ast_strdupa(value);
20299 while ((mbox = context = strsep(&next, ","))) {
20300 struct sip_mailbox *mailbox;
20302 if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
20303 continue;
20305 strsep(&context, "@");
20306 if (ast_strlen_zero(mbox)) {
20307 ast_free(mailbox);
20308 continue;
20310 mailbox->mailbox = ast_strdup(mbox);
20311 mailbox->context = ast_strdup(context);
20313 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
20317 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
20318 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int ispeer)
20320 struct sip_peer *peer = NULL;
20321 struct ast_ha *oldha = NULL;
20322 int found=0;
20323 int firstpass=1;
20324 int format=0; /* Ama flags */
20325 time_t regseconds = 0;
20326 struct ast_flags peerflags[2] = {{(0)}};
20327 struct ast_flags mask[2] = {{(0)}};
20328 char callback[256] = "";
20329 struct sip_peer tmp_peer;
20330 const char *srvlookup = NULL;
20331 static int deprecation_warning = 1;
20332 struct ast_str *fullcontact = ast_str_alloca(sizeof(peer->fullcontact));
20334 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
20335 /* Note we do NOT use find_peer here, to avoid realtime recursion */
20336 /* We also use a case-sensitive comparison (unlike find_peer) so
20337 that case changes made to the peer name will be properly handled
20338 during reload
20340 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
20341 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER|OBJ_UNLINK, "find and unlink peer from peers table");
20344 if (peer) {
20345 /* Already in the list, remove it and it will be added back (or FREE'd) */
20346 found++;
20347 if (!(peer->the_mark))
20348 firstpass = 0;
20349 } else {
20350 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
20351 return NULL;
20353 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
20354 ast_atomic_fetchadd_int(&rpeerobjs, 1);
20355 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
20356 } else
20357 ast_atomic_fetchadd_int(&speerobjs, 1);
20360 peer->onlymatchonip = ispeer; /* If type=peer, don't match on caller ID for incoming calls */
20362 /* Note that our peer HAS had its reference count increased */
20363 if (firstpass) {
20364 peer->lastmsgssent = -1;
20365 oldha = peer->ha;
20366 peer->ha = NULL;
20367 set_peer_defaults(peer); /* Set peer defaults */
20369 if (!found && name)
20370 ast_copy_string(peer->name, name, sizeof(peer->name));
20372 /* If we have channel variables, remove them (reload) */
20373 if (peer->chanvars) {
20374 ast_variables_destroy(peer->chanvars);
20375 peer->chanvars = NULL;
20376 /* XXX should unregister ? */
20379 /* If we have realm authentication information, remove them (reload) */
20380 clear_realm_authentication(peer->auth);
20381 peer->auth = NULL;
20382 peer->transports = 0;
20383 peer->socket.type = 0;
20385 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
20386 if (handle_common_options(&peerflags[0], &mask[0], v))
20387 continue;
20388 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
20389 char *val = ast_strdupa(v->value);
20390 char *trans;
20392 while ((trans = strsep(&val, ","))) {
20393 trans = ast_skip_blanks(trans);
20395 if (!strncasecmp(trans, "udp", 3))
20396 peer->transports |= SIP_TRANSPORT_UDP;
20397 else if (!strncasecmp(trans, "tcp", 3))
20398 peer->transports |= SIP_TRANSPORT_TCP;
20399 else if (!strncasecmp(trans, "tls", 3))
20400 peer->transports |= SIP_TRANSPORT_TLS;
20401 else
20402 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
20404 if (!peer->socket.type) /*!< The first transport listed should be used for outgoing */
20405 peer->socket.type = peer->transports;
20407 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
20408 ast_get_time_t(v->value, &regseconds, 0, NULL);
20409 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
20410 inet_aton(v->value, &(peer->addr.sin_addr));
20411 } else if (realtime && !strcasecmp(v->name, "name"))
20412 ast_copy_string(peer->name, v->value, sizeof(peer->name));
20413 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
20414 /* Reconstruct field, because realtime separates our value at the ';' */
20415 if (fullcontact->used > 0) {
20416 ast_str_append(&fullcontact, 0, ";%s", v->value);
20417 } else {
20418 ast_str_set(&fullcontact, 0, "%s", v->value);
20420 } else if (!strcasecmp(v->name, "type")) {
20421 if (!strcasecmp(v->value, "peer"))
20422 peer->onlymatchonip = TRUE; /* For realtime support, add type=peer in the table */
20423 } else if (!strcasecmp(v->name, "secret"))
20424 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
20425 else if (!strcasecmp(v->name, "md5secret"))
20426 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
20427 else if (!strcasecmp(v->name, "auth"))
20428 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
20429 else if (!strcasecmp(v->name, "callerid")) {
20430 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
20431 } else if (!strcasecmp(v->name, "fullname")) {
20432 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
20433 } else if (!strcasecmp(v->name, "cid_number")) {
20434 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
20435 } else if (!strcasecmp(v->name, "context")) {
20436 ast_copy_string(peer->context, v->value, sizeof(peer->context));
20437 } else if (!strcasecmp(v->name, "subscribecontext")) {
20438 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
20439 } else if (!strcasecmp(v->name, "fromdomain")) {
20440 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
20441 } else if (!strcasecmp(v->name, "usereqphone")) {
20442 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
20443 } else if (!strcasecmp(v->name, "fromuser")) {
20444 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
20445 } else if (!strcasecmp(v->name, "outboundproxy")) {
20446 char *port, *next, *force, *proxyname;
20447 int forceopt = FALSE;
20448 /* Set peer channel variable */
20449 next = proxyname = ast_strdupa(v->value);
20450 if ((port = strchr(proxyname, ':'))) {
20451 *port++ = '\0';
20452 next = port;
20454 if ((force = strchr(next, ','))) {
20455 *force++ = '\0';
20456 forceopt = strcmp(force, "force");
20458 /* Allocate proxy object */
20459 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
20460 } else if (!strcasecmp(v->name, "host")) {
20461 if (!strcasecmp(v->value, "dynamic")) {
20462 /* They'll register with us */
20463 if (!found || !peer->host_dynamic) {
20464 /* Initialize stuff if this is a new peer, or if it used to
20465 * not be dynamic before the reload. */
20466 memset(&peer->addr.sin_addr, 0, 4);
20467 if (peer->addr.sin_port) {
20468 /* If we've already got a port, make it the default rather than absolute */
20469 peer->defaddr.sin_port = peer->addr.sin_port;
20470 peer->addr.sin_port = 0;
20473 peer->host_dynamic = TRUE;
20474 } else {
20475 /* Non-dynamic. Make sure we become that way if we're not */
20476 AST_SCHED_DEL(sched, peer->expire);
20477 peer->host_dynamic = FALSE;
20478 srvlookup = v->value;
20480 } else if (!strcasecmp(v->name, "defaultip")) {
20481 if (ast_get_ip(&peer->defaddr, v->value)) {
20482 unref_peer(peer, "unref_peer: from build_peer defaultip");
20483 return NULL;
20485 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
20486 int ha_error = 0;
20488 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
20489 if (ha_error)
20490 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
20491 } else if (!strcasecmp(v->name, "port")) {
20492 if (!realtime && peer->host_dynamic)
20493 peer->defaddr.sin_port = htons(atoi(v->value));
20494 else
20495 peer->addr.sin_port = htons(atoi(v->value));
20496 } else if (!strcasecmp(v->name, "callingpres")) {
20497 peer->callingpres = ast_parse_caller_presentation(v->value);
20498 if (peer->callingpres == -1)
20499 peer->callingpres = atoi(v->value);
20500 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) { /* "username" is deprecated */
20501 ast_copy_string(peer->username, v->value, sizeof(peer->username));
20502 if (!strcasecmp(v->name, "username")) {
20503 if (deprecation_warning) {
20504 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
20505 deprecation_warning = 0;
20507 peer->deprecated_username = 1;
20509 } else if (!strcasecmp(v->name, "language")) {
20510 ast_copy_string(peer->language, v->value, sizeof(peer->language));
20511 } else if (!strcasecmp(v->name, "regexten")) {
20512 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
20513 } else if (!strcasecmp(v->name, "callbackextension")) {
20514 ast_copy_string(callback, v->value, sizeof(callback));
20515 } else if (!strcasecmp(v->name, "callcounter")) {
20516 peer->call_limit = ast_true(v->value) ? 999 : 0;
20517 } else if (!strcasecmp(v->name, "call-limit")) {
20518 peer->call_limit = atoi(v->value);
20519 if (peer->call_limit < 0)
20520 peer->call_limit = 0;
20521 } else if (!strcasecmp(v->name, "busylevel")) {
20522 peer->busy_level = atoi(v->value);
20523 if (peer->busy_level < 0)
20524 peer->busy_level = 0;
20525 } else if (!strcasecmp(v->name, "amaflags")) {
20526 format = ast_cdr_amaflags2int(v->value);
20527 if (format < 0) {
20528 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
20529 } else {
20530 peer->amaflags = format;
20532 } else if (!strcasecmp(v->name, "accountcode")) {
20533 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
20534 } else if (!strcasecmp(v->name, "mohinterpret")) {
20535 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
20536 } else if (!strcasecmp(v->name, "mohsuggest")) {
20537 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
20538 } else if (!strcasecmp(v->name, "parkinglot")) {
20539 ast_copy_string(peer->parkinglot, v->value, sizeof(peer->parkinglot));
20540 } else if (!strcasecmp(v->name, "mailbox")) {
20541 add_peer_mailboxes(peer, v->value);
20542 } else if (!strcasecmp(v->name, "hasvoicemail")) {
20543 /* People expect that if 'hasvoicemail' is set, that the mailbox will
20544 * be also set, even if not explicitly specified. */
20545 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
20546 add_peer_mailboxes(peer, name);
20548 } else if (!strcasecmp(v->name, "subscribemwi")) {
20549 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
20550 } else if (!strcasecmp(v->name, "vmexten")) {
20551 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
20552 } else if (!strcasecmp(v->name, "callgroup")) {
20553 peer->callgroup = ast_get_group(v->value);
20554 } else if (!strcasecmp(v->name, "allowtransfer")) {
20555 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
20556 } else if (!strcasecmp(v->name, "pickupgroup")) {
20557 peer->pickupgroup = ast_get_group(v->value);
20558 } else if (!strcasecmp(v->name, "allow")) {
20559 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
20560 if (error)
20561 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
20562 } else if (!strcasecmp(v->name, "disallow")) {
20563 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
20564 if (error)
20565 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
20566 } else if (!strcasecmp(v->name, "registertrying")) {
20567 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
20568 } else if (!strcasecmp(v->name, "autoframing")) {
20569 peer->autoframing = ast_true(v->value);
20570 } else if (!strcasecmp(v->name, "rtptimeout")) {
20571 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
20572 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
20573 peer->rtptimeout = global_rtptimeout;
20575 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
20576 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
20577 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
20578 peer->rtpholdtimeout = global_rtpholdtimeout;
20580 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
20581 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
20582 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
20583 peer->rtpkeepalive = global_rtpkeepalive;
20585 } else if (!strcasecmp(v->name, "timert1")) {
20586 if ((sscanf(v->value, "%d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
20587 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
20588 peer->timer_t1 = global_t1;
20590 /* Note that Timer B is dependent upon T1 and MUST NOT be lower
20591 * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
20592 if (peer->timer_b < peer->timer_t1 * 64) {
20593 peer->timer_b = peer->timer_t1 * 64;
20595 } else if (!strcasecmp(v->name, "timerb")) {
20596 if ((sscanf(v->value, "%d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
20597 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
20598 peer->timer_b = global_timer_b;
20600 if (peer->timer_b < peer->timer_t1 * 64) {
20601 static int warning = 0;
20602 if (warning++ % 20 == 0) {
20603 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
20606 } else if (!strcasecmp(v->name, "setvar")) {
20607 peer->chanvars = add_var(v->value, peer->chanvars);
20608 } else if (!strcasecmp(v->name, "qualify")) {
20609 if (!strcasecmp(v->value, "no")) {
20610 peer->maxms = 0;
20611 } else if (!strcasecmp(v->value, "yes")) {
20612 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
20613 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
20614 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
20615 peer->maxms = 0;
20617 } else if (!strcasecmp(v->name, "qualifyfreq")) {
20618 int i;
20619 if (sscanf(v->value, "%d", &i) == 1)
20620 peer->qualifyfreq = i * 1000;
20621 else {
20622 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
20623 peer->qualifyfreq = global_qualifyfreq;
20625 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
20626 peer->maxcallbitrate = atoi(v->value);
20627 if (peer->maxcallbitrate < 0)
20628 peer->maxcallbitrate = default_maxcallbitrate;
20629 } else if (!strcasecmp(v->name, "session-timers")) {
20630 int i = (int) str2stmode(v->value);
20631 if (i < 0) {
20632 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
20633 peer->stimer.st_mode_oper = global_st_mode;
20634 } else {
20635 peer->stimer.st_mode_oper = i;
20637 } else if (!strcasecmp(v->name, "session-expires")) {
20638 if (sscanf(v->value, "%d", &peer->stimer.st_max_se) != 1) {
20639 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
20640 peer->stimer.st_max_se = global_max_se;
20642 } else if (!strcasecmp(v->name, "session-minse")) {
20643 if (sscanf(v->value, "%d", &peer->stimer.st_min_se) != 1) {
20644 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
20645 peer->stimer.st_min_se = global_min_se;
20647 if (peer->stimer.st_min_se < 90) {
20648 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
20649 peer->stimer.st_min_se = global_min_se;
20651 } else if (!strcasecmp(v->name, "session-refresher")) {
20652 int i = (int) str2strefresher(v->value);
20653 if (i < 0) {
20654 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
20655 peer->stimer.st_ref = global_st_refresher;
20656 } else {
20657 peer->stimer.st_ref = i;
20662 if (!peer->socket.type) {
20663 peer->transports = SIP_TRANSPORT_UDP;
20664 peer->socket.type = SIP_TRANSPORT_UDP;
20667 if (fullcontact->used > 0) {
20668 ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
20669 peer->rt_fromcontact = TRUE;
20672 if (srvlookup && peer->dnsmgr == NULL) {
20673 char transport[MAXHOSTNAMELEN];
20674 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
20676 if (ast_dnsmgr_lookup(srvlookup, &peer->addr, &peer->dnsmgr, global_srvlookup ? transport : NULL)) {
20677 unref_peer(peer, "getting rid of a peer pointer");
20678 return NULL;
20681 ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
20684 if (!peer->addr.sin_port)
20685 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
20687 if (!peer->socket.port)
20688 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
20690 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
20691 time_t nowtime = time(NULL);
20693 if ((nowtime - regseconds) > 0) {
20694 destroy_association(peer);
20695 memset(&peer->addr, 0, sizeof(peer->addr));
20696 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
20699 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
20700 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
20701 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
20702 global_allowsubscribe = TRUE; /* No global ban any more */
20703 if (!found && peer->host_dynamic && !peer->is_realtime)
20704 reg_source_db(peer);
20706 /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
20707 * subscribe to it now. */
20708 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
20709 !AST_LIST_EMPTY(&peer->mailboxes)) {
20710 add_peer_mwi_subs(peer);
20711 /* Send MWI from the event cache only. This is so we can send initial
20712 * MWI if app_voicemail got loaded before chan_sip. If it is the other
20713 * way, then we will get events when app_voicemail gets loaded. */
20714 sip_send_mwi_to_peer(peer, NULL, 1);
20716 peer->the_mark = 0;
20718 ast_free_ha(oldha);
20719 if (!ast_strlen_zero(callback)) { /* build string from peer info */
20720 char *reg_string;
20722 asprintf(&reg_string, "%s:%s@%s/%s", peer->username, peer->secret, peer->tohost, callback);
20723 if (reg_string) {
20724 sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
20725 ast_free(reg_string);
20728 return peer;
20731 static int peer_markall_func(void *device, void *arg, int flags)
20733 struct sip_peer *peer = device;
20734 peer->the_mark = 1;
20735 return 0;
20738 /*! \brief Re-read SIP.conf config file
20739 \note This function reloads all config data, except for
20740 active peers (with registrations). They will only
20741 change configuration data at restart, not at reload.
20742 SIP debug and recordhistory state will not change
20744 static int reload_config(enum channelreloadreason reason)
20746 struct ast_config *cfg, *ucfg;
20747 struct ast_variable *v;
20748 struct sip_peer *peer;
20749 char *cat, *stringp, *context, *oldregcontext;
20750 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
20751 struct ast_flags dummy[2];
20752 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : CONFIG_FLAG_FILEUNCHANGED };
20753 int auto_sip_domains = FALSE;
20754 struct sockaddr_in old_bindaddr = bindaddr;
20755 int registry_count = 0, peer_count = 0;
20756 time_t run_start, run_end;
20758 run_start = time(0);
20759 ast_unload_realtime("sipregs");
20760 ast_unload_realtime("sippeers");
20761 cfg = ast_config_load(config, config_flags);
20763 /* We *must* have a config file otherwise stop immediately */
20764 if (!cfg) {
20765 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
20766 return -1;
20767 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
20768 ucfg = ast_config_load("users.conf", config_flags);
20769 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
20770 return 1;
20771 /* Must reread both files, because one changed */
20772 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
20773 cfg = ast_config_load(config, config_flags);
20774 } else {
20775 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
20776 ucfg = ast_config_load("users.conf", config_flags);
20779 /* Initialize tcp sockets */
20780 memset(&sip_tcp_desc.sin, 0, sizeof(sip_tcp_desc.sin));
20781 memset(&sip_tls_desc.sin, 0, sizeof(sip_tls_desc.sin));
20783 sip_tcp_desc.sin.sin_family = AF_INET; /* Default: Enable TCP sessions */
20784 default_tls_cfg.enabled = FALSE; /* Default: Disable TLS */
20786 sip_tcp_desc.sin.sin_port = htons(STANDARD_SIP_PORT);
20787 sip_tls_desc.sin.sin_port = htons(STANDARD_TLS_PORT);
20789 if (reason != CHANNEL_MODULE_LOAD) {
20790 ast_debug(4, "--------------- SIP reload started\n");
20792 clear_realm_authentication(authl);
20793 clear_sip_domains();
20794 authl = NULL;
20796 /* First, destroy all outstanding registry calls */
20797 /* This is needed, since otherwise active registry entries will not be destroyed */
20798 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do { /* regl is locked */
20800 /* avoid a deadlock in the unlink_all call, if iterator->call's (a dialog) registry entry
20801 is this registry entry. In other words, if the dialog we are pointing to points back to
20802 us, then if we get a lock on this object, and try to UNREF it, we will deadlock, because
20803 we already ... NO. This is not the problem. */
20804 ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
20805 if (iterator->call) {
20806 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
20807 /* This will also remove references to the registry */
20808 dialog_unlink_all(iterator->call, TRUE, TRUE);
20809 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
20810 /* iterator->call = sip_destroy(iterator->call); */
20812 ASTOBJ_UNLOCK(iterator);
20814 } while(0));
20816 /* Then, actually destroy users and registry */
20817 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
20818 ast_debug(4, "--------------- Done destroying registry list\n");
20819 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, 0, "callback to mark all peers");
20822 /* Reset certificate handling for TLS sessions */
20823 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
20824 default_tls_cfg.cipher = ast_strdup("");
20825 default_tls_cfg.cafile = ast_strdup("");
20826 default_tls_cfg.capath = ast_strdup("");
20828 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
20829 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
20830 oldregcontext = oldcontexts;
20832 /* Clear all flags before setting default values */
20833 /* Preserve debugging settings for console */
20834 sipdebug &= sip_debug_console;
20835 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
20836 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
20838 /* Reset IP addresses */
20839 memset(&bindaddr, 0, sizeof(bindaddr));
20840 memset(&stunaddr, 0, sizeof(stunaddr));
20841 memset(&internip, 0, sizeof(internip));
20843 /* Free memory for local network address mask */
20844 ast_free_ha(localaddr);
20845 memset(&localaddr, 0, sizeof(localaddr));
20846 memset(&externip, 0, sizeof(externip));
20847 memset(&default_prefs, 0 , sizeof(default_prefs));
20848 memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
20849 global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
20850 global_outboundproxy.ip.sin_family = AF_INET; /*!< Type of address: IPv4 */
20851 global_outboundproxy.force = FALSE; /*!< Don't force proxy usage, use route: headers */
20852 ourport_tcp = STANDARD_SIP_PORT;
20853 ourport_tls = STANDARD_TLS_PORT;
20854 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
20855 global_srvlookup = DEFAULT_SRVLOOKUP;
20856 global_tos_sip = DEFAULT_TOS_SIP;
20857 global_tos_audio = DEFAULT_TOS_AUDIO;
20858 global_tos_video = DEFAULT_TOS_VIDEO;
20859 global_tos_text = DEFAULT_TOS_TEXT;
20860 global_cos_sip = DEFAULT_COS_SIP;
20861 global_cos_audio = DEFAULT_COS_AUDIO;
20862 global_cos_video = DEFAULT_COS_VIDEO;
20863 global_cos_text = DEFAULT_COS_TEXT;
20865 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
20866 externexpire = 0; /* Expiration for DNS re-issuing */
20867 externrefresh = 10;
20869 /* Reset channel settings to default before re-configuring */
20870 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
20871 global_regcontext[0] = '\0';
20872 global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
20873 global_notifyringing = DEFAULT_NOTIFYRINGING;
20874 global_notifyhold = FALSE; /*!< Keep track of hold status for a peer */
20875 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
20876 global_alwaysauthreject = 0;
20877 global_allowsubscribe = FALSE;
20878 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
20879 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
20880 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
20881 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
20882 ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
20883 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
20884 compactheaders = DEFAULT_COMPACTHEADERS;
20885 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
20886 global_regattempts_max = 0;
20887 pedanticsipchecking = DEFAULT_PEDANTIC;
20888 autocreatepeer = DEFAULT_AUTOCREATEPEER;
20889 global_autoframing = 0;
20890 global_allowguest = DEFAULT_ALLOWGUEST;
20891 global_callcounter = DEFAULT_CALLCOUNTER;
20892 global_match_auth_username = FALSE; /*!< Match auth username if available instead of From: Default off. */
20893 global_rtptimeout = 0;
20894 global_rtpholdtimeout = 0;
20895 global_rtpkeepalive = 0;
20896 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
20897 global_rtautoclear = 120;
20898 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for all devices: TRUE */
20899 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for all devices: TRUE */
20900 sip_cfg.peer_rtupdate = TRUE;
20902 /* Session-Timers */
20903 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
20904 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
20905 global_min_se = DEFAULT_MIN_SE;
20906 global_max_se = DEFAULT_MAX_SE;
20908 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
20909 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
20910 default_subscribecontext[0] = '\0';
20911 default_language[0] = '\0';
20912 default_fromdomain[0] = '\0';
20913 default_qualify = DEFAULT_QUALIFY;
20914 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
20915 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
20916 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
20917 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
20918 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
20919 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
20920 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
20922 /* Debugging settings, always default to off */
20923 dumphistory = FALSE;
20924 recordhistory = FALSE;
20925 sipdebug &= ~sip_debug_config;
20927 /* Misc settings for the channel */
20928 global_relaxdtmf = FALSE;
20929 global_callevents = FALSE;
20930 global_authfailureevents = FALSE;
20931 global_t1 = SIP_TIMER_T1;
20932 global_timer_b = 64 * SIP_TIMER_T1;
20933 global_t1min = DEFAULT_T1MIN;
20934 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
20936 global_matchexterniplocally = FALSE;
20938 /* Copy the default jb config over global_jbconf */
20939 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
20941 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
20942 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
20945 /* Read the [general] config section of sip.conf (or from realtime config) */
20946 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
20947 if (handle_common_options(&global_flags[0], &dummy[0], v))
20948 continue;
20949 /* handle jb conf */
20950 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
20951 continue;
20953 if (!strcasecmp(v->name, "context")) {
20954 ast_copy_string(default_context, v->value, sizeof(default_context));
20955 } else if (!strcasecmp(v->name, "subscribecontext")) {
20956 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
20957 } else if (!strcasecmp(v->name, "callcounter")) {
20958 global_callcounter = ast_true(v->value) ? 1 : 0;
20959 } else if (!strcasecmp(v->name, "allowguest")) {
20960 global_allowguest = ast_true(v->value) ? 1 : 0;
20961 } else if (!strcasecmp(v->name, "realm")) {
20962 ast_copy_string(global_realm, v->value, sizeof(global_realm));
20963 } else if (!strcasecmp(v->name, "useragent")) {
20964 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
20965 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
20966 } else if (!strcasecmp(v->name, "sdpsession")) {
20967 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
20968 } else if (!strcasecmp(v->name, "sdpowner")) {
20969 /* Field cannot contain spaces */
20970 if (!strstr(v->value, " "))
20971 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
20972 else
20973 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
20974 } else if (!strcasecmp(v->name, "allowtransfer")) {
20975 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
20976 } else if (!strcasecmp(v->name, "rtcachefriends")) {
20977 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
20978 } else if (!strcasecmp(v->name, "rtsavesysname")) {
20979 sip_cfg.rtsave_sysname = ast_true(v->value);
20980 } else if (!strcasecmp(v->name, "rtupdate")) {
20981 sip_cfg.peer_rtupdate = ast_true(v->value);
20982 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
20983 sip_cfg.ignore_regexpire = ast_true(v->value);
20984 } else if (!strcasecmp(v->name, "timert1")) {
20985 /* Defaults to 500ms, but RFC 3261 states that it is recommended
20986 * for the value to be set higher, though a lower value is only
20987 * allowed on private networks unconnected to the Internet. */
20988 global_t1 = atoi(v->value);
20989 /* Note that timer B is dependent on the value of T1 */
20990 global_timer_b = global_t1 * 64;
20991 } else if (!strcasecmp(v->name, "t1min")) {
20992 global_t1min = atoi(v->value);
20993 } else if (!strcasecmp(v->name, "tcpenable")) {
20994 sip_tcp_desc.sin.sin_family = ast_false(v->value) ? 0 : AF_INET;
20995 ast_debug(2, "Enabling TCP socket for listening\n");
20996 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
20997 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.sin))
20998 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
20999 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
21000 } else if (!strcasecmp(v->name, "tlsenable")) {
21001 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
21002 sip_tls_desc.sin.sin_family = AF_INET;
21003 } else if (!strcasecmp(v->name, "tlscertfile")) {
21004 ast_free(default_tls_cfg.certfile);
21005 default_tls_cfg.certfile = ast_strdup(v->value);
21006 } else if (!strcasecmp(v->name, "tlscipher")) {
21007 ast_free(default_tls_cfg.cipher);
21008 default_tls_cfg.cipher = ast_strdup(v->value);
21009 } else if (!strcasecmp(v->name, "tlscafile")) {
21010 ast_free(default_tls_cfg.cafile);
21011 default_tls_cfg.cafile = ast_strdup(v->value);
21012 } else if (!strcasecmp(v->name, "tlscapath")) {
21013 ast_free(default_tls_cfg.capath);
21014 default_tls_cfg.capath = ast_strdup(v->value);
21015 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
21016 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
21017 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
21018 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
21019 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
21020 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.sin))
21021 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
21022 } else if (!strcasecmp(v->name, "rtautoclear")) {
21023 int i = atoi(v->value);
21024 if (i > 0)
21025 global_rtautoclear = i;
21026 else
21027 i = 0;
21028 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
21029 } else if (!strcasecmp(v->name, "usereqphone")) {
21030 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
21031 } else if (!strcasecmp(v->name, "relaxdtmf")) {
21032 global_relaxdtmf = ast_true(v->value);
21033 } else if (!strcasecmp(v->name, "vmexten")) {
21034 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
21035 } else if (!strcasecmp(v->name, "rtptimeout")) {
21036 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
21037 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
21038 global_rtptimeout = 0;
21040 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
21041 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
21042 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
21043 global_rtpholdtimeout = 0;
21045 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
21046 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
21047 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
21048 global_rtpkeepalive = 0;
21050 } else if (!strcasecmp(v->name, "compactheaders")) {
21051 compactheaders = ast_true(v->value);
21052 } else if (!strcasecmp(v->name, "notifymimetype")) {
21053 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
21054 } else if (!strcasecmp(v->name, "directrtpsetup")) {
21055 global_directrtpsetup = ast_true(v->value);
21056 } else if (!strcasecmp(v->name, "notifyringing")) {
21057 global_notifyringing = ast_true(v->value);
21058 } else if (!strcasecmp(v->name, "notifyhold")) {
21059 global_notifyhold = ast_true(v->value);
21060 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
21061 global_alwaysauthreject = ast_true(v->value);
21062 } else if (!strcasecmp(v->name, "mohinterpret")) {
21063 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
21064 } else if (!strcasecmp(v->name, "mohsuggest")) {
21065 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
21066 } else if (!strcasecmp(v->name, "language")) {
21067 ast_copy_string(default_language, v->value, sizeof(default_language));
21068 } else if (!strcasecmp(v->name, "regcontext")) {
21069 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
21070 stringp = newcontexts;
21071 /* Let's remove any contexts that are no longer defined in regcontext */
21072 cleanup_stale_contexts(stringp, oldregcontext);
21073 /* Create contexts if they don't exist already */
21074 while ((context = strsep(&stringp, "&"))) {
21075 ast_copy_string(used_context, context, sizeof(used_context));
21076 ast_context_find_or_create(NULL, NULL, context, "SIP");
21078 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
21079 } else if (!strcasecmp(v->name, "regextenonqualify")) {
21080 global_regextenonqualify = ast_true(v->value);
21081 } else if (!strcasecmp(v->name, "callerid")) {
21082 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
21083 } else if (!strcasecmp(v->name, "fromdomain")) {
21084 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
21085 } else if (!strcasecmp(v->name, "outboundproxy")) {
21086 int portnum;
21087 char *tok, *proxyname;
21089 if (ast_strlen_zero(v->value)) {
21090 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
21091 continue;
21094 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
21096 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &global_outboundproxy.transport);
21098 global_outboundproxy.ip.sin_port = htons(portnum);
21100 if ((tok = strtok(NULL, ","))) {
21101 global_outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
21102 } else {
21103 global_outboundproxy.force = FALSE;
21106 if (ast_strlen_zero(proxyname)) {
21107 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
21108 global_outboundproxy.name[0] = '\0';
21109 continue;
21112 ast_copy_string(global_outboundproxy.name, proxyname, sizeof(global_outboundproxy.name));
21113 } else if (!strcasecmp(v->name, "autocreatepeer")) {
21114 autocreatepeer = ast_true(v->value);
21115 } else if (!strcasecmp(v->name, "match_auth_username")) {
21116 global_match_auth_username = ast_true(v->value);
21117 } else if (!strcasecmp(v->name, "srvlookup")) {
21118 global_srvlookup = ast_true(v->value);
21119 } else if (!strcasecmp(v->name, "pedantic")) {
21120 pedanticsipchecking = ast_true(v->value);
21121 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
21122 max_expiry = atoi(v->value);
21123 if (max_expiry < 1)
21124 max_expiry = DEFAULT_MAX_EXPIRY;
21125 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
21126 min_expiry = atoi(v->value);
21127 if (min_expiry < 1)
21128 min_expiry = DEFAULT_MIN_EXPIRY;
21129 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
21130 default_expiry = atoi(v->value);
21131 if (default_expiry < 1)
21132 default_expiry = DEFAULT_DEFAULT_EXPIRY;
21133 } else if (!strcasecmp(v->name, "sipdebug")) {
21134 if (ast_true(v->value))
21135 sipdebug |= sip_debug_config;
21136 } else if (!strcasecmp(v->name, "dumphistory")) {
21137 dumphistory = ast_true(v->value);
21138 } else if (!strcasecmp(v->name, "recordhistory")) {
21139 recordhistory = ast_true(v->value);
21140 } else if (!strcasecmp(v->name, "registertimeout")) {
21141 global_reg_timeout = atoi(v->value);
21142 if (global_reg_timeout < 1)
21143 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
21144 } else if (!strcasecmp(v->name, "registerattempts")) {
21145 global_regattempts_max = atoi(v->value);
21146 } else if (!strcasecmp(v->name, "stunaddr")) {
21147 stunaddr.sin_port = htons(3478);
21148 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
21149 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
21150 externexpire = time(NULL);
21151 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
21152 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
21153 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
21154 } else if (!strcasecmp(v->name, "localnet")) {
21155 struct ast_ha *na;
21156 int ha_error = 0;
21158 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
21159 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
21160 else
21161 localaddr = na;
21162 if (ha_error)
21163 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
21164 } else if (!strcasecmp(v->name, "externip")) {
21165 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
21166 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
21167 externexpire = 0;
21168 /* If no port was specified use the value of bindport */
21169 if (!externip.sin_port)
21170 externip.sin_port = bindaddr.sin_port;
21171 } else if (!strcasecmp(v->name, "externhost")) {
21172 ast_copy_string(externhost, v->value, sizeof(externhost));
21173 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
21174 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
21175 externexpire = time(NULL);
21176 } else if (!strcasecmp(v->name, "externrefresh")) {
21177 if (sscanf(v->value, "%d", &externrefresh) != 1) {
21178 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
21179 externrefresh = 10;
21181 } else if (!strcasecmp(v->name, "allow")) {
21182 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
21183 if (error)
21184 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
21185 } else if (!strcasecmp(v->name, "disallow")) {
21186 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
21187 if (error)
21188 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
21189 } else if (!strcasecmp(v->name, "autoframing")) {
21190 global_autoframing = ast_true(v->value);
21191 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
21192 allow_external_domains = ast_true(v->value);
21193 } else if (!strcasecmp(v->name, "autodomain")) {
21194 auto_sip_domains = ast_true(v->value);
21195 } else if (!strcasecmp(v->name, "domain")) {
21196 char *domain = ast_strdupa(v->value);
21197 char *context = strchr(domain, ',');
21199 if (context)
21200 *context++ = '\0';
21202 if (ast_strlen_zero(context))
21203 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
21204 if (ast_strlen_zero(domain))
21205 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
21206 else
21207 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
21208 } else if (!strcasecmp(v->name, "register")) {
21209 if (sip_register(v->value, v->lineno) == 0)
21210 registry_count++;
21211 } else if (!strcasecmp(v->name, "tos_sip")) {
21212 if (ast_str2tos(v->value, &global_tos_sip))
21213 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
21214 } else if (!strcasecmp(v->name, "tos_audio")) {
21215 if (ast_str2tos(v->value, &global_tos_audio))
21216 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
21217 } else if (!strcasecmp(v->name, "tos_video")) {
21218 if (ast_str2tos(v->value, &global_tos_video))
21219 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
21220 } else if (!strcasecmp(v->name, "tos_text")) {
21221 if (ast_str2tos(v->value, &global_tos_text))
21222 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
21223 } else if (!strcasecmp(v->name, "cos_sip")) {
21224 if (ast_str2cos(v->value, &global_cos_sip))
21225 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
21226 } else if (!strcasecmp(v->name, "cos_audio")) {
21227 if (ast_str2cos(v->value, &global_cos_audio))
21228 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
21229 } else if (!strcasecmp(v->name, "cos_video")) {
21230 if (ast_str2cos(v->value, &global_cos_video))
21231 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
21232 } else if (!strcasecmp(v->name, "cos_text")) {
21233 if (ast_str2cos(v->value, &global_cos_text))
21234 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
21235 } else if (!strcasecmp(v->name, "bindport")) {
21236 int i;
21237 if (sscanf(v->value, "%d", &i) == 1) {
21238 bindaddr.sin_port = htons(i);
21239 } else {
21240 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
21242 } else if (!strcasecmp(v->name, "hash_user")) {
21243 int i;
21244 if (sscanf(v->value, "%d", &i) == 1 && i > 2) {
21245 hash_user_size = i;
21246 } else {
21247 ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
21249 } else if (!strcasecmp(v->name, "hash_peer")) {
21250 int i;
21251 if (sscanf(v->value, "%d", &i) == 1 && i > 2) {
21252 hash_peer_size = i;
21253 } else {
21254 ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
21256 } else if (!strcasecmp(v->name, "hash_dialog")) {
21257 int i;
21258 if (sscanf(v->value, "%d", &i) == 1 && i > 2) {
21259 hash_dialog_size = i;
21260 } else {
21261 ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
21263 } else if (!strcasecmp(v->name, "qualify")) {
21264 if (!strcasecmp(v->value, "no")) {
21265 default_qualify = 0;
21266 } else if (!strcasecmp(v->value, "yes")) {
21267 default_qualify = DEFAULT_MAXMS;
21268 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
21269 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
21270 default_qualify = 0;
21272 } else if (!strcasecmp(v->name, "qualifyfreq")) {
21273 int i;
21274 if (sscanf(v->value, "%d", &i) == 1)
21275 global_qualifyfreq = i * 1000;
21276 else {
21277 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
21278 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
21280 } else if (!strcasecmp(v->name, "callevents")) {
21281 global_callevents = ast_true(v->value);
21282 } else if (!strcasecmp(v->name, "authfailureevents")) {
21283 global_authfailureevents = ast_true(v->value);
21284 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
21285 default_maxcallbitrate = atoi(v->value);
21286 if (default_maxcallbitrate < 0)
21287 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
21288 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
21289 global_matchexterniplocally = ast_true(v->value);
21290 } else if (!strcasecmp(v->name, "session-timers")) {
21291 int i = (int) str2stmode(v->value);
21292 if (i < 0) {
21293 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
21294 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
21295 } else {
21296 global_st_mode = i;
21298 } else if (!strcasecmp(v->name, "session-expires")) {
21299 if (sscanf(v->value, "%d", &global_max_se) != 1) {
21300 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
21301 global_max_se = DEFAULT_MAX_SE;
21303 } else if (!strcasecmp(v->name, "session-minse")) {
21304 if (sscanf(v->value, "%d", &global_min_se) != 1) {
21305 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
21306 global_min_se = DEFAULT_MIN_SE;
21308 if (global_min_se < 90) {
21309 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
21310 global_min_se = DEFAULT_MIN_SE;
21312 } else if (!strcasecmp(v->name, "session-refresher")) {
21313 int i = (int) str2strefresher(v->value);
21314 if (i < 0) {
21315 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
21316 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
21317 } else {
21318 global_st_refresher = i;
21323 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
21324 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
21325 allow_external_domains = 1;
21328 /* Build list of authentication to various SIP realms, i.e. service providers */
21329 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
21330 /* Format for authentication is auth = username:password@realm */
21331 if (!strcasecmp(v->name, "auth"))
21332 authl = add_realm_authentication(authl, v->value, v->lineno);
21335 if (ucfg) {
21336 struct ast_variable *gen;
21337 int genhassip, genregistersip;
21338 const char *hassip, *registersip;
21340 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
21341 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
21342 gen = ast_variable_browse(ucfg, "general");
21343 cat = ast_category_browse(ucfg, NULL);
21344 while (cat) {
21345 if (strcasecmp(cat, "general")) {
21346 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
21347 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
21348 if (ast_true(hassip) || (!hassip && genhassip)) {
21349 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, FALSE);
21350 if (peer) {
21351 ao2_t_link(peers, peer, "link peer into peer table");
21352 if (peer->addr.sin_addr.s_addr) {
21353 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
21356 unref_peer(peer, "unref_peer: from reload_config");
21357 peer_count++;
21360 if (ast_true(registersip) || (!registersip && genregistersip)) {
21361 char tmp[256];
21362 const char *host = ast_variable_retrieve(ucfg, cat, "host");
21363 const char *username = ast_variable_retrieve(ucfg, cat, "username");
21364 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
21365 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
21366 if (!host)
21367 host = ast_variable_retrieve(ucfg, "general", "host");
21368 if (!username)
21369 username = ast_variable_retrieve(ucfg, "general", "username");
21370 if (!secret)
21371 secret = ast_variable_retrieve(ucfg, "general", "secret");
21372 if (!contact)
21373 contact = "s";
21374 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
21375 if (!ast_strlen_zero(secret))
21376 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
21377 else
21378 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
21379 if (sip_register(tmp, 0) == 0)
21380 registry_count++;
21384 cat = ast_category_browse(ucfg, cat);
21386 ast_config_destroy(ucfg);
21390 /* Load peers, users and friends */
21391 cat = NULL;
21392 while ( (cat = ast_category_browse(cfg, cat)) ) {
21393 const char *utype;
21394 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
21395 continue;
21396 utype = ast_variable_retrieve(cfg, cat, "type");
21397 if (!utype) {
21398 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
21399 continue;
21400 } else {
21401 int is_peer = 0;
21402 if (!strcasecmp(utype, "user")) {
21403 is_peer = 1;
21404 } else if (!strcasecmp(utype, "friend")) {
21405 is_peer = 1;
21406 } else if (!strcasecmp(utype, "peer"))
21407 is_peer = 2;
21408 else {
21409 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
21410 continue;
21412 if (is_peer) {
21413 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, is_peer == 2);
21414 if (peer) {
21415 ao2_t_link(peers, peer, "link peer into peers table");
21416 if (peer->addr.sin_addr.s_addr) {
21417 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
21419 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
21420 peer_count++;
21426 /* Set UDP address and open socket */
21427 bindaddr.sin_family = AF_INET;
21428 internip = bindaddr;
21429 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
21430 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
21431 ast_config_destroy(cfg);
21432 return 0;
21434 ast_mutex_lock(&netlock);
21435 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
21436 close(sipsock);
21437 sipsock = -1;
21439 if (sipsock < 0) {
21440 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
21441 if (sipsock < 0) {
21442 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
21443 ast_config_destroy(cfg);
21444 return -1;
21445 } else {
21446 /* Allow SIP clients on the same host to access us: */
21447 const int reuseFlag = 1;
21449 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
21450 (const char*)&reuseFlag,
21451 sizeof reuseFlag);
21453 ast_enable_packet_fragmentation(sipsock);
21455 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
21456 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
21457 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
21458 strerror(errno));
21459 close(sipsock);
21460 sipsock = -1;
21461 } else {
21462 ast_verb(2, "SIP Listening on %s:%d\n",
21463 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
21464 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
21468 if (stunaddr.sin_addr.s_addr != 0) {
21469 ast_debug(1, "stun to %s:%d\n",
21470 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
21471 ast_stun_request(sipsock, &stunaddr,
21472 NULL, &externip);
21473 ast_debug(1, "STUN sees us at %s:%d\n",
21474 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
21476 ast_mutex_unlock(&netlock);
21478 /* Start TCP server */
21479 ast_tcptls_server_start(&sip_tcp_desc);
21481 /* Start TLS server if needed */
21482 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
21484 if (ast_ssl_setup(sip_tls_desc.tls_cfg))
21485 ast_tcptls_server_start(&sip_tls_desc);
21486 else if (sip_tls_desc.tls_cfg->enabled) {
21487 sip_tls_desc.tls_cfg = NULL;
21488 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
21492 /* Add default domains - host name, IP address and IP:port
21493 * Only do this if user added any sip domain with "localdomains"
21494 * In order to *not* break backwards compatibility
21495 * Some phones address us at IP only, some with additional port number
21497 if (auto_sip_domains) {
21498 char temp[MAXHOSTNAMELEN];
21500 /* First our default IP address */
21501 if (bindaddr.sin_addr.s_addr)
21502 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
21503 else
21504 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
21506 /* If TCP is running on a different IP than UDP, then add it too */
21507 if (sip_tcp_desc.sin.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.sin))
21508 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.sin.sin_addr), SIP_DOMAIN_AUTO, NULL);
21510 /* If TLS is running on a differen IP than UDP and TCP, then add that too */
21511 if (sip_tls_desc.sin.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.sin) && inaddrcmp(&sip_tcp_desc.sin, &sip_tls_desc.sin))
21512 add_sip_domain(ast_inet_ntoa(sip_tls_desc.sin.sin_addr), SIP_DOMAIN_AUTO, NULL);
21514 /* Our extern IP address, if configured */
21515 if (externip.sin_addr.s_addr)
21516 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
21518 /* Extern host name (NAT traversal support) */
21519 if (!ast_strlen_zero(externhost))
21520 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
21522 /* Our host name */
21523 if (!gethostname(temp, sizeof(temp)))
21524 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
21527 /* Release configuration from memory */
21528 ast_config_destroy(cfg);
21530 /* Load the list of manual NOTIFY types to support */
21531 if (notify_types)
21532 ast_config_destroy(notify_types);
21533 notify_types = ast_config_load(notify_config, config_flags);
21535 /* Done, tell the manager */
21536 manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
21537 run_end = time(0);
21538 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
21540 return 0;
21543 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
21545 struct sip_pvt *p;
21546 struct ast_udptl *udptl = NULL;
21548 p = chan->tech_pvt;
21549 if (!p)
21550 return NULL;
21552 sip_pvt_lock(p);
21553 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
21554 udptl = p->udptl;
21555 sip_pvt_unlock(p);
21556 return udptl;
21559 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
21561 struct sip_pvt *p;
21563 p = chan->tech_pvt;
21564 if (!p)
21565 return -1;
21566 sip_pvt_lock(p);
21567 if (udptl)
21568 ast_udptl_get_peer(udptl, &p->udptlredirip);
21569 else
21570 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
21571 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21572 if (!p->pendinginvite) {
21573 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
21574 transmit_reinvite_with_sdp(p, TRUE, FALSE);
21575 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
21576 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
21577 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
21580 /* Reset lastrtprx timer */
21581 p->lastrtprx = p->lastrtptx = time(NULL);
21582 sip_pvt_unlock(p);
21583 return 0;
21586 /*! \brief Handle T38 reinvite
21587 \todo Make sure we don't destroy the call if we can't handle the re-invite.
21588 Nothing should be changed until we have processed the SDP and know that we
21589 can handle it.
21591 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
21593 struct sip_pvt *p;
21594 int flag = 0;
21596 p = chan->tech_pvt;
21597 if (!p || !pvt->udptl)
21598 return -1;
21600 /* Setup everything on the other side like offered/responded from first side */
21601 sip_pvt_lock(p);
21603 /*! \todo check if this is not set earlier when setting up the PVT. If not
21604 maybe it should move there. */
21605 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
21607 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
21608 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
21609 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
21611 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
21612 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
21613 not really T38 re-invites which are different. In this
21614 case it's used properly, to see if we can reinvite over
21615 NAT
21617 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
21618 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
21619 flag =1;
21620 } else {
21621 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
21623 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
21624 if (!p->pendinginvite) {
21625 if (flag)
21626 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
21627 else
21628 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip.sin_addr));
21629 change_t38_state(p, T38_LOCAL_REINVITE);
21630 transmit_reinvite_with_sdp(p, TRUE, FALSE);
21631 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
21632 if (flag)
21633 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
21634 else
21635 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip.sin_addr));
21636 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
21639 /* Reset lastrtprx timer */
21640 p->lastrtprx = p->lastrtptx = time(NULL);
21641 sip_pvt_unlock(p);
21642 return 0;
21643 } else { /* If we are handling sending 200 OK to the other side of the bridge */
21644 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
21645 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
21646 flag = 1;
21647 } else {
21648 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
21650 if (flag)
21651 ast_debug(3, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
21652 else
21653 ast_debug(3, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip.sin_addr));
21654 change_t38_state(pvt, T38_ENABLED);
21655 change_t38_state(p, T38_ENABLED);
21656 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
21657 p->lastrtprx = p->lastrtptx = time(NULL);
21658 sip_pvt_unlock(p);
21659 return 0;
21664 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
21665 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
21667 struct sip_pvt *p = NULL;
21668 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
21670 if (!(p = chan->tech_pvt))
21671 return AST_RTP_GET_FAILED;
21673 sip_pvt_lock(p);
21674 if (!(p->rtp)) {
21675 sip_pvt_unlock(p);
21676 return AST_RTP_GET_FAILED;
21679 *rtp = p->rtp;
21681 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
21682 res = AST_RTP_TRY_PARTIAL;
21683 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
21684 res = AST_RTP_TRY_NATIVE;
21685 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
21686 res = AST_RTP_GET_FAILED;
21688 sip_pvt_unlock(p);
21690 return res;
21693 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
21694 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
21696 struct sip_pvt *p = NULL;
21697 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
21699 if (!(p = chan->tech_pvt))
21700 return AST_RTP_GET_FAILED;
21702 sip_pvt_lock(p);
21703 if (!(p->vrtp)) {
21704 sip_pvt_unlock(p);
21705 return AST_RTP_GET_FAILED;
21708 *rtp = p->vrtp;
21710 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
21711 res = AST_RTP_TRY_NATIVE;
21713 sip_pvt_unlock(p);
21715 return res;
21718 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
21719 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
21721 struct sip_pvt *p = NULL;
21722 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
21724 if (!(p = chan->tech_pvt))
21725 return AST_RTP_GET_FAILED;
21727 sip_pvt_lock(p);
21728 if (!(p->trtp)) {
21729 sip_pvt_unlock(p);
21730 return AST_RTP_GET_FAILED;
21733 *rtp = p->trtp;
21735 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
21736 res = AST_RTP_TRY_NATIVE;
21738 sip_pvt_unlock(p);
21740 return res;
21743 /*! \brief Set the RTP peer for this call */
21744 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
21746 struct sip_pvt *p;
21747 int changed = 0;
21749 p = chan->tech_pvt;
21750 if (!p)
21751 return -1;
21753 /* Disable early RTP bridge */
21754 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
21755 return 0;
21757 sip_pvt_lock(p);
21758 if (p->alreadygone) {
21759 /* If we're destroyed, don't bother */
21760 sip_pvt_unlock(p);
21761 return 0;
21764 /* if this peer cannot handle reinvites of the media stream to devices
21765 that are known to be behind a NAT, then stop the process now
21767 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
21768 sip_pvt_unlock(p);
21769 return 0;
21772 if (rtp) {
21773 changed |= ast_rtp_get_peer(rtp, &p->redirip);
21774 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
21775 memset(&p->redirip, 0, sizeof(p->redirip));
21776 changed = 1;
21778 if (vrtp) {
21779 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
21780 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
21781 memset(&p->vredirip, 0, sizeof(p->vredirip));
21782 changed = 1;
21784 if (trtp) {
21785 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
21786 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
21787 memset(&p->tredirip, 0, sizeof(p->tredirip));
21788 changed = 1;
21790 if (codecs && (p->redircodecs != codecs)) {
21791 p->redircodecs = codecs;
21792 changed = 1;
21794 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
21795 if (chan->_state != AST_STATE_UP) { /* We are in early state */
21796 if (p->do_history)
21797 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
21798 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
21799 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
21800 ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
21801 transmit_reinvite_with_sdp(p, FALSE, FALSE);
21802 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
21803 ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
21804 /* We have a pending Invite. Send re-invite when we're done with the invite */
21805 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
21808 /* Reset lastrtprx timer */
21809 p->lastrtprx = p->lastrtptx = time(NULL);
21810 sip_pvt_unlock(p);
21811 return 0;
21814 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
21815 static char *descrip_dtmfmode = " SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
21816 static char *app_dtmfmode = "SIPDtmfMode";
21818 static char *app_sipaddheader = "SIPAddHeader";
21819 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
21821 static char *descrip_sipaddheader = ""
21822 " SIPAddHeader(Header: Content):\n"
21823 "Adds a header to a SIP call placed with DIAL.\n"
21824 "Remember to user the X-header if you are adding non-standard SIP\n"
21825 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
21826 "Adding the wrong headers may jeopardize the SIP dialog.\n"
21827 "Always returns 0\n";
21830 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
21831 static int sip_dtmfmode(struct ast_channel *chan, void *data)
21833 struct sip_pvt *p;
21834 char *mode = data;
21836 if (!data) {
21837 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
21838 return 0;
21840 ast_channel_lock(chan);
21841 if (!IS_SIP_TECH(chan->tech)) {
21842 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
21843 ast_channel_unlock(chan);
21844 return 0;
21846 p = chan->tech_pvt;
21847 if (!p) {
21848 ast_channel_unlock(chan);
21849 return 0;
21851 sip_pvt_lock(p);
21852 if (!strcasecmp(mode, "info")) {
21853 ast_clear_flag(&p->flags[0], SIP_DTMF);
21854 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
21855 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
21856 } else if (!strcasecmp(mode, "shortinfo")) {
21857 ast_clear_flag(&p->flags[0], SIP_DTMF);
21858 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
21859 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
21860 } else if (!strcasecmp(mode, "rfc2833")) {
21861 ast_clear_flag(&p->flags[0], SIP_DTMF);
21862 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
21863 p->jointnoncodeccapability |= AST_RTP_DTMF;
21864 } else if (!strcasecmp(mode, "inband")) {
21865 ast_clear_flag(&p->flags[0], SIP_DTMF);
21866 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
21867 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
21868 } else
21869 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
21870 if (p->rtp)
21871 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
21872 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
21873 if (!p->vad) {
21874 p->vad = ast_dsp_new();
21875 ast_dsp_set_features(p->vad, DSP_FEATURE_DIGIT_DETECT);
21877 } else {
21878 if (p->vad) {
21879 ast_dsp_free(p->vad);
21880 p->vad = NULL;
21883 sip_pvt_unlock(p);
21884 ast_channel_unlock(chan);
21885 return 0;
21888 /*! \brief Add a SIP header to an outbound INVITE */
21889 static int sip_addheader(struct ast_channel *chan, void *data)
21891 int no = 0;
21892 int ok = FALSE;
21893 char varbuf[30];
21894 char *inbuf = data;
21896 if (ast_strlen_zero(inbuf)) {
21897 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
21898 return 0;
21900 ast_channel_lock(chan);
21902 /* Check for headers */
21903 while (!ok && no <= 50) {
21904 no++;
21905 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
21907 /* Compare without the leading underscore */
21908 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
21909 ok = TRUE;
21911 if (ok) {
21912 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
21913 if (sipdebug)
21914 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
21915 } else {
21916 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
21918 ast_channel_unlock(chan);
21919 return 0;
21922 /*! \brief Transfer call before connect with a 302 redirect
21923 \note Called by the transfer() dialplan application through the sip_transfer()
21924 pbx interface function if the call is in ringing state
21925 \todo Fix this function so that we wait for reply to the REFER and
21926 react to errors, denials or other issues the other end might have.
21928 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
21930 char *cdest;
21931 char *extension, *host, *port;
21932 char tmp[80];
21934 cdest = ast_strdupa(dest);
21936 extension = strsep(&cdest, "@");
21937 host = strsep(&cdest, ":");
21938 port = strsep(&cdest, ":");
21939 if (ast_strlen_zero(extension)) {
21940 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
21941 return 0;
21944 /* we'll issue the redirect message here */
21945 if (!host) {
21946 char *localtmp;
21948 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
21949 if (ast_strlen_zero(tmp)) {
21950 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
21951 return 0;
21953 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
21954 && (localtmp = strchr(localtmp, '@'))) {
21955 char lhost[80], lport[80];
21957 memset(lhost, 0, sizeof(lhost));
21958 memset(lport, 0, sizeof(lport));
21959 localtmp++;
21960 /* This is okey because lhost and lport are as big as tmp */
21961 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
21962 if (ast_strlen_zero(lhost)) {
21963 ast_log(LOG_ERROR, "Can't find the host address\n");
21964 return 0;
21966 host = ast_strdupa(lhost);
21967 if (!ast_strlen_zero(lport)) {
21968 port = ast_strdupa(lport);
21973 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
21974 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
21976 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
21977 sip_alreadygone(p);
21978 /* hangup here */
21979 return 0;
21982 /*! \brief Return SIP UA's codec (part of the RTP interface) */
21983 static int sip_get_codec(struct ast_channel *chan)
21985 struct sip_pvt *p = chan->tech_pvt;
21986 return p->peercapability ? p->peercapability : p->capability;
21989 /*! \brief Send a poke to all known peers
21990 Space them out 100 ms apart
21991 XXX We might have a cool algorithm for this or use random - any suggestions?
21993 static void sip_poke_all_peers(void)
21995 int ms = 0;
21996 struct ao2_iterator i;
21997 struct sip_peer *peer;
21999 i = ao2_iterator_init(peers, 0);
22001 if (!speerobjs) /* No peers, just give up */
22002 return;
22004 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
22005 ao2_lock(peer);
22006 ms += 100;
22007 AST_SCHED_REPLACE(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer);
22008 ao2_unlock(peer);
22009 unref_peer(peer, "toss iterator peer ptr");
22013 /*! \brief Send all known registrations */
22014 static void sip_send_all_registers(void)
22016 int ms;
22017 int regspacing;
22018 if (!regobjs)
22019 return;
22020 regspacing = default_expiry * 1000/regobjs;
22021 if (regspacing > 100)
22022 regspacing = 100;
22023 ms = regspacing;
22024 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
22025 ASTOBJ_WRLOCK(iterator);
22026 ms += regspacing;
22027 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
22028 registry_unref(_data, "REPLACE sched del decs the refcount"),
22029 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
22030 registry_addref(iterator, "REPLACE sched add incs the refcount"));
22031 ASTOBJ_UNLOCK(iterator);
22032 } while (0)
22036 /*! \brief Reload module */
22037 static int sip_do_reload(enum channelreloadreason reason)
22039 time_t start_poke, end_poke;
22041 reload_config(reason);
22042 ast_sched_dump(sched);
22044 start_poke = time(0);
22045 /* Prune peers who still are supposed to be deleted */
22046 ao2_t_callback(peers, OBJ_NODATA|OBJ_UNLINK, peer_is_marked, 0, "callback to remove marked peers");
22048 ast_debug(4, "--------------- Done destroying pruned peers\n");
22050 /* Send qualify (OPTIONS) to all peers */
22051 sip_poke_all_peers();
22053 /* Register with all services */
22054 sip_send_all_registers();
22055 end_poke = time(0);
22057 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
22059 ast_debug(4, "--------------- SIP reload done\n");
22061 return 0;
22064 /*! \brief Force reload of module from cli */
22065 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
22068 switch (cmd) {
22069 case CLI_INIT:
22070 e->command = "sip reload";
22071 e->usage =
22072 "Usage: sip reload\n"
22073 " Reloads SIP configuration from sip.conf\n";
22074 return NULL;
22075 case CLI_GENERATE:
22076 return NULL;
22079 ast_mutex_lock(&sip_reload_lock);
22080 if (sip_reloading)
22081 ast_verbose("Previous SIP reload not yet done\n");
22082 else {
22083 sip_reloading = TRUE;
22084 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
22086 ast_mutex_unlock(&sip_reload_lock);
22087 restart_monitor();
22089 return CLI_SUCCESS;
22092 /*! \brief Part of Asterisk module interface */
22093 static int reload(void)
22095 if (sip_reload(0, 0, NULL))
22096 return 0;
22097 return 1;
22100 static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
22101 /*! \brief SIP Cli commands definition */
22102 static struct ast_cli_entry cli_sip[] = {
22103 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
22104 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
22105 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains."),
22106 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
22107 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
22108 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
22109 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
22110 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registery\n"),
22111 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
22112 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
22113 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
22114 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
22115 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
22116 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
22117 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
22118 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
22119 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
22120 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
22121 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
22122 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
22125 /*! \brief PBX load module - initialization */
22126 static int load_module(void)
22128 ast_verbose("SIP channel loading...\n");
22129 /* the fact that ao2_containers can't resize automatically is a major worry! */
22130 /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
22131 peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
22132 peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
22133 dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
22135 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
22137 if (!(sched = sched_context_create())) {
22138 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
22139 return AST_MODULE_LOAD_FAILURE;
22142 if (!(io = io_context_create())) {
22143 ast_log(LOG_ERROR, "Unable to create I/O context\n");
22144 sched_context_destroy(sched);
22145 return AST_MODULE_LOAD_FAILURE;
22148 sip_reloadreason = CHANNEL_MODULE_LOAD;
22150 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
22151 return AST_MODULE_LOAD_DECLINE;
22153 /* Prepare the version that does not require DTMF BEGIN frames.
22154 * We need to use tricks such as memcpy and casts because the variable
22155 * has const fields.
22157 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
22158 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
22160 /* Make sure we can register our sip channel type */
22161 if (ast_channel_register(&sip_tech)) {
22162 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
22163 io_context_destroy(io);
22164 sched_context_destroy(sched);
22165 return AST_MODULE_LOAD_FAILURE;
22168 /* Register all CLI functions for SIP */
22169 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
22171 /* Tell the RTP subdriver that we're here */
22172 ast_rtp_proto_register(&sip_rtp);
22174 /* Tell the UDPTL subdriver that we're here */
22175 ast_udptl_proto_register(&sip_udptl);
22177 /* Register dialplan applications */
22178 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
22179 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
22181 /* Register dialplan functions */
22182 ast_custom_function_register(&sip_header_function);
22183 ast_custom_function_register(&sippeer_function);
22184 ast_custom_function_register(&sipchaninfo_function);
22185 ast_custom_function_register(&checksipdomain_function);
22187 /* Register manager commands */
22188 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
22189 "List SIP peers (text format)", mandescr_show_peers);
22190 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
22191 "Show SIP peer (text format)", mandescr_show_peer);
22192 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
22193 "Show SIP peer (text format)", mandescr_show_peer); /*! \todo Fix this XXX This must be all wrong XXXX */
22194 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
22195 "Show SIP registrations (text format)", mandescr_show_registry);
22196 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
22197 "Send a SIP notify", mandescr_sipnotify);
22198 sip_poke_all_peers();
22199 sip_send_all_registers();
22201 /* And start the monitor for the first time */
22202 restart_monitor();
22204 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
22205 "name", RQ_CHAR, 10,
22206 "ipaddr", RQ_CHAR, 15,
22207 "port", RQ_UINTEGER2, 5,
22208 "regseconds", RQ_UINTEGER2, 5, /* Max of 18 hours */
22209 "defaultuser", RQ_CHAR, 10,
22210 "fullcontact", RQ_CHAR, 35,
22211 "regserver", RQ_CHAR, 20,
22212 "useragent", RQ_CHAR, 20,
22213 SENTINEL);
22215 return AST_MODULE_LOAD_SUCCESS;
22218 /*! \brief PBX unload module API */
22219 static int unload_module(void)
22221 struct sip_pvt *p;
22222 struct sip_threadinfo *th;
22223 struct ast_context *con;
22224 struct ao2_iterator i;
22226 ast_sched_dump(sched);
22228 /* First, take us out of the channel type list */
22229 ast_channel_unregister(&sip_tech);
22231 /* Unregister dial plan functions */
22232 ast_custom_function_unregister(&sipchaninfo_function);
22233 ast_custom_function_unregister(&sippeer_function);
22234 ast_custom_function_unregister(&sip_header_function);
22235 ast_custom_function_unregister(&checksipdomain_function);
22237 /* Unregister dial plan applications */
22238 ast_unregister_application(app_dtmfmode);
22239 ast_unregister_application(app_sipaddheader);
22241 /* Unregister CLI commands */
22242 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
22244 /* Disconnect from the RTP subsystem */
22245 ast_rtp_proto_unregister(&sip_rtp);
22247 /* Disconnect from UDPTL */
22248 ast_udptl_proto_unregister(&sip_udptl);
22250 /* Unregister AMI actions */
22251 ast_manager_unregister("SIPpeers");
22252 ast_manager_unregister("SIPshowpeer");
22253 ast_manager_unregister("SIPqualifypeer");
22254 ast_manager_unregister("SIPshowregistry");
22255 ast_manager_unregister("SIPnotify");
22257 /* Kill TCP/TLS server threads */
22258 if (sip_tcp_desc.master)
22259 ast_tcptls_server_stop(&sip_tcp_desc);
22260 if (sip_tls_desc.master)
22261 ast_tcptls_server_stop(&sip_tls_desc);
22263 /* Kill all existing TCP/TLS threads */
22264 AST_LIST_LOCK(&threadl);
22265 AST_LIST_TRAVERSE_SAFE_BEGIN(&threadl, th, list) {
22266 pthread_t thread = th->threadid;
22267 th->stop = 1;
22268 AST_LIST_UNLOCK(&threadl);
22269 pthread_kill(thread, SIGURG);
22270 pthread_join(thread, NULL);
22271 AST_LIST_LOCK(&threadl);
22273 AST_LIST_TRAVERSE_SAFE_END;
22274 AST_LIST_UNLOCK(&threadl);
22276 /* Hangup all dialogs if they have an owner */
22277 i = ao2_iterator_init(dialogs, 0);
22278 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
22279 if (p->owner)
22280 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
22281 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
22284 ast_mutex_lock(&monlock);
22285 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
22286 pthread_cancel(monitor_thread);
22287 pthread_kill(monitor_thread, SIGURG);
22288 pthread_join(monitor_thread, NULL);
22290 monitor_thread = AST_PTHREADT_STOP;
22291 ast_mutex_unlock(&monlock);
22293 /* Destroy all the dialogs and free their memory */
22294 i = ao2_iterator_init(dialogs, 0);
22295 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
22296 dialog_unlink_all(p, TRUE, TRUE);
22297 ao2_t_ref(p, -1, "throw away iterator result");
22300 /* Free memory for local network address mask */
22301 ast_free_ha(localaddr);
22303 clear_realm_authentication(authl);
22306 if (default_tls_cfg.certfile)
22307 ast_free(default_tls_cfg.certfile);
22308 if (default_tls_cfg.cipher)
22309 ast_free(default_tls_cfg.cipher);
22310 if (default_tls_cfg.cafile)
22311 ast_free(default_tls_cfg.cafile);
22312 if (default_tls_cfg.capath)
22313 ast_free(default_tls_cfg.capath);
22315 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
22316 ASTOBJ_CONTAINER_DESTROY(&regl);
22318 ao2_t_ref(peers, -1, "unref the peers table");
22319 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
22320 ao2_t_ref(dialogs, -1, "unref the dialogs table");
22322 clear_sip_domains();
22323 close(sipsock);
22324 sched_context_destroy(sched);
22325 con = ast_context_find(used_context);
22326 if (con)
22327 ast_context_destroy(con, "SIP");
22328 ast_unload_realtime("sipregs");
22329 ast_unload_realtime("sippeers");
22331 return 0;
22334 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
22335 .load = load_module,
22336 .unload = unload_module,
22337 .reload = reload,