Detect if the installed gcc version supports the warn_unused_result attribute.
[asterisk-bristuff.git] / channels / chan_sip.c
blobd6a1ec9610c12690064bf3c7c158a4ae68201bd3
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
44 * \ingroup channel_drivers
46 * \par Overview of the handling of SIP sessions
47 * The SIP channel handles several types of SIP sessions, or dialogs,
48 * not all of them being "telephone calls".
49 * - Incoming calls that will be sent to the PBX core
50 * - Outgoing calls, generated by the PBX
51 * - SIP subscriptions and notifications of states and voicemail messages
52 * - SIP registrations, both inbound and outbound
53 * - SIP peer management (peerpoke, OPTIONS)
54 * - SIP text messages
56 * In the SIP channel, there's a list of active SIP dialogs, which includes
57 * all of these when they are active. "sip show channels" in the CLI will
58 * show most of these, excluding subscriptions which are shown by
59 * "sip show subscriptions"
61 * \par incoming packets
62 * Incoming packets are received in the monitoring thread, then handled by
63 * sipsock_read(). This function parses the packet and matches an existing
64 * dialog or starts a new SIP dialog.
66 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
67 * If it is a response to an outbound request, the packet is sent to handle_response().
68 * If it is a request, handle_incoming() sends it to one of a list of functions
69 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
70 * sipsock_read locks the ast_channel if it exists (an active call) and
71 * unlocks it after we have processed the SIP message.
73 * A new INVITE is sent to handle_request_invite(), that will end up
74 * starting a new channel in the PBX, the new channel after that executing
75 * in a separate channel thread. This is an incoming "call".
76 * When the call is answered, either by a bridged channel or the PBX itself
77 * the sip_answer() function is called.
79 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
80 * in rtp.c
82 * \par Outbound calls
83 * Outbound calls are set up by the PBX through the sip_request_call()
84 * function. After that, they are activated by sip_call().
86 * \par Hanging up
87 * The PBX issues a hangup on both incoming and outgoing calls through
88 * the sip_hangup() function
91 /*** MODULEINFO
92 <depend>chan_local</depend>
93 ***/
95 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
97 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
98 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
99 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
100 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
101 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
102 that do not support Session-Timers).
104 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
105 per-peer settings override the global settings. The following new parameters have been
106 added to the sip.conf file.
107 session-timers=["accept", "originate", "refuse"]
108 session-expires=[integer]
109 session-minse=[integer]
110 session-refresher=["uas", "uac"]
112 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
113 Asterisk. The Asterisk can be configured in one of the following three modes:
115 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
116 made by remote end-points. A remote end-point can request Asterisk to engage
117 session-timers by either sending it an INVITE request with a "Supported: timer"
118 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
119 Session-Expires: header in it. In this mode, the Asterisk server does not
120 request session-timers from remote end-points. This is the default mode.
121 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
122 end-points to activate session-timers in addition to honoring such requests
123 made by the remote end-pints. In order to get as much protection as possible
124 against hanging SIP channels due to network or end-point failures, Asterisk
125 resends periodic re-INVITEs even if a remote end-point does not support
126 the session-timers feature.
127 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
128 timers for inbound or outbound requests. If a remote end-point requests
129 session-timers in a dialog, then Asterisk ignores that request unless it's
130 noted as a requirement (Require: header), in which case the INVITE is
131 rejected with a 420 Bad Extension response.
135 #include "asterisk.h"
137 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
139 #include <ctype.h>
140 #include <sys/ioctl.h>
141 #include <fcntl.h>
142 #include <signal.h>
143 #include <sys/signal.h>
144 #include <regex.h>
145 #include <time.h>
147 #include "asterisk/network.h"
148 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
150 #include "asterisk/lock.h"
151 #include "asterisk/channel.h"
152 #include "asterisk/config.h"
153 #include "asterisk/module.h"
154 #include "asterisk/pbx.h"
155 #include "asterisk/sched.h"
156 #include "asterisk/io.h"
157 #include "asterisk/rtp.h"
158 #include "asterisk/udptl.h"
159 #include "asterisk/acl.h"
160 #include "asterisk/manager.h"
161 #include "asterisk/callerid.h"
162 #include "asterisk/cli.h"
163 #include "asterisk/app.h"
164 #include "asterisk/musiconhold.h"
165 #include "asterisk/dsp.h"
166 #include "asterisk/features.h"
167 #include "asterisk/srv.h"
168 #include "asterisk/astdb.h"
169 #include "asterisk/causes.h"
170 #include "asterisk/utils.h"
171 #include "asterisk/file.h"
172 #include "asterisk/astobj.h"
174 Uncomment the define below, if you are having refcount related memory leaks.
175 With this uncommented, this module will generate a file, /tmp/refs, which contains
176 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
177 be modified to ao2_t_* calls, and include a tag describing what is happening with
178 enough detail, to make pairing up a reference count increment with its corresponding decrement.
179 The refcounter program in utils/ can be invaluable in highlighting objects that are not
180 balanced, along with the complete history for that object.
181 In normal operation, the macros defined will throw away the tags, so they do not
182 affect the speed of the program at all. They can be considered to be documentation.
184 /* #define REF_DEBUG 1 */
185 #include "asterisk/astobj2.h"
186 #include "asterisk/dnsmgr.h"
187 #include "asterisk/devicestate.h"
188 #include "asterisk/linkedlists.h"
189 #include "asterisk/stringfields.h"
190 #include "asterisk/monitor.h"
191 #include "asterisk/netsock.h"
192 #include "asterisk/localtime.h"
193 #include "asterisk/abstract_jb.h"
194 #include "asterisk/threadstorage.h"
195 #include "asterisk/translate.h"
196 #include "asterisk/ast_version.h"
197 #include "asterisk/event.h"
198 #include "asterisk/tcptls.h"
200 #ifndef FALSE
201 #define FALSE 0
202 #endif
204 #ifndef TRUE
205 #define TRUE 1
206 #endif
208 #define SIPBUFSIZE 512
210 #define XMIT_ERROR -2
212 /* #define VOCAL_DATA_HACK */
214 #define DEFAULT_DEFAULT_EXPIRY 120
215 #define DEFAULT_MIN_EXPIRY 60
216 #define DEFAULT_MAX_EXPIRY 3600
217 #define DEFAULT_REGISTRATION_TIMEOUT 20
218 #define DEFAULT_MAX_FORWARDS "70"
220 /* guard limit must be larger than guard secs */
221 /* guard min must be < 1000, and should be >= 250 */
222 #define EXPIRY_GUARD_SECS 15 /*!< How long before expiry do we reregister */
223 #define EXPIRY_GUARD_LIMIT 30 /*!< Below here, we use EXPIRY_GUARD_PCT instead of
224 EXPIRY_GUARD_SECS */
225 #define EXPIRY_GUARD_MIN 500 /*!< This is the minimum guard time applied. If
226 GUARD_PCT turns out to be lower than this, it
227 will use this time instead.
228 This is in milliseconds. */
229 #define EXPIRY_GUARD_PCT 0.20 /*!< Percentage of expires timeout to use when
230 below EXPIRY_GUARD_LIMIT */
231 #define DEFAULT_EXPIRY 900 /*!< Expire slowly */
233 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
234 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
235 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
236 static int expiry = DEFAULT_EXPIRY;
238 #ifndef MAX
239 #define MAX(a,b) ((a) > (b) ? (a) : (b))
240 #endif
242 #define CALLERID_UNKNOWN "Unknown"
244 #define DEFAULT_MAXMS 2000 /*!< Qualification: Must be faster than 2 seconds by default */
245 #define DEFAULT_QUALIFYFREQ 60 * 1000 /*!< Qualification: How often to check for the host to be up */
246 #define DEFAULT_FREQ_NOTOK 10 * 1000 /*!< Qualification: How often to check, if the host is down... */
248 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
249 #define MAX_RETRANS 6 /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
250 #define SIP_TIMER_T1 500 /* SIP timer T1 (according to RFC 3261) */
251 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1
252 \todo Use known T1 for timeout (peerpoke)
254 #define DEFAULT_TRANS_TIMEOUT -1 /* Use default SIP transaction timeout */
255 #define MAX_AUTHTRIES 3 /*!< Try authentication three times, then fail */
257 #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */
258 #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */
259 #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */
260 #define SIP_MIN_PACKET 1024 /*!< Initialize size of memory to allocate for packets */
262 #define INITIAL_CSEQ 101 /*!< our initial sip sequence number */
264 #define DEFAULT_MAX_SE 1800 /*!< Session-Timer Default Session-Expires period (RFC 4028) */
265 #define DEFAULT_MIN_SE 90 /*!< Session-Timer Default Min-SE period (RFC 4028) */
267 #define SDP_MAX_RTPMAP_CODECS 32 /*!< Maximum number of codecs allowed in received SDP */
269 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
270 static struct ast_jb_conf default_jbconf =
272 .flags = 0,
273 .max_size = -1,
274 .resync_threshold = -1,
275 .impl = ""
277 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
279 static const char config[] = "sip.conf"; /*!< Main configuration file */
280 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
282 #define RTP 1
283 #define NO_RTP 0
285 /*! \brief Authorization scheme for call transfers
286 \note Not a bitfield flag, since there are plans for other modes,
287 like "only allow transfers for authenticated devices" */
288 enum transfermodes {
289 TRANSFER_OPENFORALL, /*!< Allow all SIP transfers */
290 TRANSFER_CLOSED, /*!< Allow no SIP transfers */
294 enum sip_result {
295 AST_SUCCESS = 0,
296 AST_FAILURE = -1,
299 /*! \brief States for the INVITE transaction, not the dialog
300 \note this is for the INVITE that sets up the dialog
302 enum invitestates {
303 INV_NONE = 0, /*!< No state at all, maybe not an INVITE dialog */
304 INV_CALLING = 1, /*!< Invite sent, no answer */
305 INV_PROCEEDING = 2, /*!< We got/sent 1xx message */
306 INV_EARLY_MEDIA = 3, /*!< We got 18x message with to-tag back */
307 INV_COMPLETED = 4, /*!< Got final response with error. Wait for ACK, then CONFIRMED */
308 INV_CONFIRMED = 5, /*!< Confirmed response - we've got an ack (Incoming calls only) */
309 INV_TERMINATED = 6, /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
310 The only way out of this is a BYE from one side */
311 INV_CANCELLED = 7, /*!< Transaction cancelled by client or server in non-terminated state */
314 enum xmittype {
315 XMIT_CRITICAL = 2, /*!< Transmit critical SIP message reliably, with re-transmits.
316 If it fails, it's critical and will cause a teardown of the session */
317 XMIT_RELIABLE = 1, /*!< Transmit SIP message reliably, with re-transmits */
318 XMIT_UNRELIABLE = 0, /*!< Transmit SIP message without bothering with re-transmits */
321 enum parse_register_result {
322 PARSE_REGISTER_FAILED,
323 PARSE_REGISTER_UPDATE,
324 PARSE_REGISTER_QUERY,
327 enum subscriptiontype {
328 NONE = 0,
329 XPIDF_XML,
330 DIALOG_INFO_XML,
331 CPIM_PIDF_XML,
332 PIDF_XML,
333 MWI_NOTIFICATION
336 /*! \brief Subscription types that we support. We support
337 - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
338 - SIMPLE presence used for device status
339 - Voicemail notification subscriptions
341 static const struct cfsubscription_types {
342 enum subscriptiontype type;
343 const char * const event;
344 const char * const mediatype;
345 const char * const text;
346 } subscription_types[] = {
347 { NONE, "-", "unknown", "unknown" },
348 /* RFC 4235: SIP Dialog event package */
349 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
350 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
351 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
352 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
353 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
357 /*! \brief Authentication types - proxy or www authentication
358 \note Endpoints, like Asterisk, should always use WWW authentication to
359 allow multiple authentications in the same call - to the proxy and
360 to the end point.
362 enum sip_auth_type {
363 PROXY_AUTH = 407,
364 WWW_AUTH = 401,
367 /*! \brief Authentication result from check_auth* functions */
368 enum check_auth_result {
369 AUTH_DONT_KNOW = -100, /*!< no result, need to check further */
370 /* XXX maybe this is the same as AUTH_NOT_FOUND */
372 AUTH_SUCCESSFUL = 0,
373 AUTH_CHALLENGE_SENT = 1,
374 AUTH_SECRET_FAILED = -1,
375 AUTH_USERNAME_MISMATCH = -2,
376 AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
377 AUTH_FAKE_AUTH = -4,
378 AUTH_UNKNOWN_DOMAIN = -5,
379 AUTH_PEER_NOT_DYNAMIC = -6,
380 AUTH_ACL_FAILED = -7,
383 /*! \brief States for outbound registrations (with register= lines in sip.conf */
384 enum sipregistrystate {
385 REG_STATE_UNREGISTERED = 0, /*!< We are not registred
386 * \note Initial state. We should have a timeout scheduled for the initial
387 * (or next) registration transmission, calling sip_reregister
390 REG_STATE_REGSENT, /*!< Registration request sent
391 * \note sent initial request, waiting for an ack or a timeout to
392 * retransmit the initial request.
395 REG_STATE_AUTHSENT, /*!< We have tried to authenticate
396 * \note entered after transmit_register with auth info,
397 * waiting for an ack.
400 REG_STATE_REGISTERED, /*!< Registered and done */
402 REG_STATE_REJECTED, /*!< Registration rejected *
403 * \note only used when the remote party has an expire larger than
404 * our max-expire. This is a final state from which we do not
405 * recover (not sure how correctly).
408 REG_STATE_TIMEOUT, /*!< Registration timed out *
409 * \note XXX unused */
411 REG_STATE_NOAUTH, /*!< We have no accepted credentials
412 * \note fatal - no chance to proceed */
414 REG_STATE_FAILED, /*!< Registration failed after several tries
415 * \note fatal - no chance to proceed */
418 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
419 enum st_mode {
420 SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */
421 SESSION_TIMER_MODE_ACCEPT, /*!< Honor inbound Session-Timer requests */
422 SESSION_TIMER_MODE_ORIGINATE, /*!< Originate outbound and honor inbound requests */
423 SESSION_TIMER_MODE_REFUSE /*!< Ignore inbound Session-Timers requests */
426 /*! \brief The entity playing the refresher role for Session-Timers */
427 enum st_refresher {
428 SESSION_TIMER_REFRESHER_AUTO, /*!< Negotiated */
429 SESSION_TIMER_REFRESHER_UAC, /*!< Session is refreshed by the UAC */
430 SESSION_TIMER_REFRESHER_UAS /*!< Session is refreshed by the UAS */
434 /*! \brief definition of a sip proxy server
436 * For outbound proxies, this is allocated in the SIP peer dynamically or
437 * statically as the global_outboundproxy. The pointer in a SIP message is just
438 * a pointer and should *not* be de-allocated.
440 struct sip_proxy {
441 char name[MAXHOSTNAMELEN]; /*!< DNS name of domain/host or IP */
442 struct sockaddr_in ip; /*!< Currently used IP address and port */
443 time_t last_dnsupdate; /*!< When this was resolved */
444 int force; /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
445 /* Room for a SRV record chain based on the name */
448 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
449 enum can_create_dialog {
450 CAN_NOT_CREATE_DIALOG,
451 CAN_CREATE_DIALOG,
452 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
455 /*! \brief SIP Request methods known by Asterisk
457 \note Do _NOT_ make any changes to this enum, or the array following it;
458 if you think you are doing the right thing, you are probably
459 not doing the right thing. If you think there are changes
460 needed, get someone else to review them first _before_
461 submitting a patch. If these two lists do not match properly
462 bad things will happen.
465 enum sipmethod {
466 SIP_UNKNOWN, /*!< Unknown response */
467 SIP_RESPONSE, /*!< Not request, response to outbound request */
468 SIP_REGISTER, /*!< Registration to the mothership, tell us where you are located */
469 SIP_OPTIONS, /*!< Check capabilities of a device, used for "ping" too */
470 SIP_NOTIFY, /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
471 SIP_INVITE, /*!< Set up a session */
472 SIP_ACK, /*!< End of a three-way handshake started with INVITE. */
473 SIP_PRACK, /*!< Reliable pre-call signalling. Not supported in Asterisk. */
474 SIP_BYE, /*!< End of a session */
475 SIP_REFER, /*!< Refer to another URI (transfer) */
476 SIP_SUBSCRIBE, /*!< Subscribe for updates (voicemail, session status, device status, presence) */
477 SIP_MESSAGE, /*!< Text messaging */
478 SIP_UPDATE, /*!< Update a dialog. We can send UPDATE; but not accept it */
479 SIP_INFO, /*!< Information updates during a session */
480 SIP_CANCEL, /*!< Cancel an INVITE */
481 SIP_PUBLISH, /*!< Not supported in Asterisk */
482 SIP_PING, /*!< Not supported at all, no standard but still implemented out there */
485 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
486 structure and then route the messages according to the type.
488 \note Note that sip_methods[i].id == i must hold or the code breaks */
489 static const struct cfsip_methods {
490 enum sipmethod id;
491 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
492 char * const text;
493 enum can_create_dialog can_create;
494 } sip_methods[] = {
495 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
496 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
497 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
498 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
499 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
500 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
501 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
502 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
503 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
504 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
505 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
506 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
507 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
508 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
509 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
510 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
511 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
514 /*! Define SIP option tags, used in Require: and Supported: headers
515 We need to be aware of these properties in the phones to use
516 the replace: header. We should not do that without knowing
517 that the other end supports it...
518 This is nothing we can configure, we learn by the dialog
519 Supported: header on the REGISTER (peer) or the INVITE
520 (other devices)
521 We are not using many of these today, but will in the future.
522 This is documented in RFC 3261
524 #define SUPPORTED 1
525 #define NOT_SUPPORTED 0
527 /* SIP options */
528 #define SIP_OPT_REPLACES (1 << 0)
529 #define SIP_OPT_100REL (1 << 1)
530 #define SIP_OPT_TIMER (1 << 2)
531 #define SIP_OPT_EARLY_SESSION (1 << 3)
532 #define SIP_OPT_JOIN (1 << 4)
533 #define SIP_OPT_PATH (1 << 5)
534 #define SIP_OPT_PREF (1 << 6)
535 #define SIP_OPT_PRECONDITION (1 << 7)
536 #define SIP_OPT_PRIVACY (1 << 8)
537 #define SIP_OPT_SDP_ANAT (1 << 9)
538 #define SIP_OPT_SEC_AGREE (1 << 10)
539 #define SIP_OPT_EVENTLIST (1 << 11)
540 #define SIP_OPT_GRUU (1 << 12)
541 #define SIP_OPT_TARGET_DIALOG (1 << 13)
542 #define SIP_OPT_NOREFERSUB (1 << 14)
543 #define SIP_OPT_HISTINFO (1 << 15)
544 #define SIP_OPT_RESPRIORITY (1 << 16)
545 #define SIP_OPT_UNKNOWN (1 << 17)
548 /*! \brief List of well-known SIP options. If we get this in a require,
549 we should check the list and answer accordingly. */
550 static const struct cfsip_options {
551 int id; /*!< Bitmap ID */
552 int supported; /*!< Supported by Asterisk ? */
553 char * const text; /*!< Text id, as in standard */
554 } sip_options[] = { /* XXX used in 3 places */
555 /* RFC3891: Replaces: header for transfer */
556 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
557 /* One version of Polycom firmware has the wrong label */
558 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
559 /* RFC3262: PRACK 100% reliability */
560 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
561 /* RFC4028: SIP Session-Timers */
562 { SIP_OPT_TIMER, SUPPORTED, "timer" },
563 /* RFC3959: SIP Early session support */
564 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
565 /* RFC3911: SIP Join header support */
566 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
567 /* RFC3327: Path support */
568 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
569 /* RFC3840: Callee preferences */
570 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
571 /* RFC3312: Precondition support */
572 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
573 /* RFC3323: Privacy with proxies*/
574 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
575 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
576 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
577 /* RFC3329: Security agreement mechanism */
578 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
579 /* SIMPLE events: RFC4662 */
580 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
581 /* GRUU: Globally Routable User Agent URI's */
582 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
583 /* RFC4538: Target-dialog */
584 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
585 /* Disable the REFER subscription, RFC 4488 */
586 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
587 /* ietf-sip-history-info-06.txt */
588 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
589 /* ietf-sip-resource-priority-10.txt */
590 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
594 /*! \brief SIP Methods we support
595 \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
596 allowsubscribe and allowrefer on in sip.conf.
598 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
600 /*! \brief SIP Extensions we support */
601 #define SUPPORTED_EXTENSIONS "replaces, timer"
603 /*! \brief Standard SIP and TLS port from RFC 3261. DO NOT CHANGE THIS */
604 #define STANDARD_SIP_PORT 5060
605 #define STANDARD_TLS_PORT 5061
606 /*! \note in many SIP headers, absence of a port number implies port 5060,
607 * and this is why we cannot change the above constant.
608 * There is a limited number of places in asterisk where we could,
609 * in principle, use a different "default" port number, but
610 * we do not support this feature at the moment.
611 * You can run Asterisk with SIP on a different port with a configuration
612 * option. If you change this value, the signalling will be incorrect.
615 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
617 These are default values in the source. There are other recommended values in the
618 sip.conf.sample for new installations. These may differ to keep backwards compatibility,
619 yet encouraging new behaviour on new installations
621 /*@{*/
622 #define DEFAULT_CONTEXT "default"
623 #define DEFAULT_MOHINTERPRET "default"
624 #define DEFAULT_MOHSUGGEST ""
625 #define DEFAULT_VMEXTEN "asterisk"
626 #define DEFAULT_CALLERID "asterisk"
627 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
628 #define DEFAULT_ALLOWGUEST TRUE
629 #define DEFAULT_CALLCOUNTER FALSE
630 #define DEFAULT_SRVLOOKUP TRUE /*!< Recommended setting is ON */
631 #define DEFAULT_COMPACTHEADERS FALSE
632 #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. */
633 #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. */
634 #define DEFAULT_TOS_VIDEO 0 /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
635 #define DEFAULT_TOS_TEXT 0 /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
636 #define DEFAULT_COS_SIP 4
637 #define DEFAULT_COS_AUDIO 5
638 #define DEFAULT_COS_VIDEO 6
639 #define DEFAULT_COS_TEXT 5
640 #define DEFAULT_ALLOW_EXT_DOM TRUE
641 #define DEFAULT_REALM "asterisk"
642 #define DEFAULT_NOTIFYRINGING TRUE
643 #define DEFAULT_PEDANTIC FALSE
644 #define DEFAULT_AUTOCREATEPEER FALSE
645 #define DEFAULT_QUALIFY FALSE
646 #define DEFAULT_REGEXTENONQUALIFY FALSE
647 #define DEFAULT_T1MIN 100 /*!< 100 MS for minimal roundtrip time */
648 #define DEFAULT_MAX_CALL_BITRATE (384) /*!< Max bitrate for video */
649 #ifndef DEFAULT_USERAGENT
650 #define DEFAULT_USERAGENT "Asterisk PBX" /*!< Default Useragent: header unless re-defined in sip.conf */
651 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
652 #define DEFAULT_SDPOWNER "root" /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
653 #endif
654 /*@}*/
656 /*! \name DefaultSettings
657 Default setttings are used as a channel setting and as a default when
658 configuring devices
660 /*@{*/
661 static char default_context[AST_MAX_CONTEXT];
662 static char default_subscribecontext[AST_MAX_CONTEXT];
663 static char default_language[MAX_LANGUAGE];
664 static char default_callerid[AST_MAX_EXTENSION];
665 static char default_fromdomain[AST_MAX_EXTENSION];
666 static char default_notifymime[AST_MAX_EXTENSION];
667 static int default_qualify; /*!< Default Qualify= setting */
668 static char default_vmexten[AST_MAX_EXTENSION];
669 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
670 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
671 * a bridged channel on hold */
672 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
673 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
674 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
676 /*! \brief a place to store all global settings for the sip channel driver */
677 struct sip_settings {
678 int peer_rtupdate; /*!< G: Update database with registration data for peer? */
679 int rtsave_sysname; /*!< G: Save system name at registration? */
680 int ignore_regexpire; /*!< G: Ignore expiration of peer */
683 static struct sip_settings sip_cfg;
684 /*@}*/
686 /*! \name GlobalSettings
687 Global settings apply to the channel (often settings you can change in the general section
688 of sip.conf
690 /*@{*/
691 static int global_directrtpsetup; /*!< Enable support for Direct RTP setup (no re-invites) */
692 static int global_limitonpeers; /*!< Match call limit on peers only */
693 static int global_rtautoclear; /*!< Realtime ?? */
694 static int global_notifyringing; /*!< Send notifications on ringing */
695 static int global_notifyhold; /*!< Send notifications on hold */
696 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
697 static int global_srvlookup; /*!< SRV Lookup on or off. Default is on */
698 static int pedanticsipchecking; /*!< Extra checking ? Default off */
699 static int autocreatepeer; /*!< Auto creation of peers at registration? Default off. */
700 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
701 static int global_relaxdtmf; /*!< Relax DTMF */
702 static int global_rtptimeout; /*!< Time out call if no RTP */
703 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
704 static int global_rtpkeepalive; /*!< Send RTP keepalives */
705 static int global_reg_timeout;
706 static int global_regattempts_max; /*!< Registration attempts before giving up */
707 static int global_allowguest; /*!< allow unauthenticated users/peers to connect? */
708 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
709 call-limit to 999. When we remove the call-limit from the code, we can make it
710 with just a boolean flag in the device structure */
711 static int global_allowsubscribe; /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
712 the global setting is in globals_flags[1] */
713 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
714 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
715 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
716 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
717 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
718 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
719 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
720 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
721 static int compactheaders; /*!< send compact sip headers */
722 static int recordhistory; /*!< Record SIP history. Off by default */
723 static int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
724 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
725 static char global_regcontext[AST_MAX_CONTEXT]; /*!< Context for auto-extensions */
726 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
727 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
728 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
729 static int allow_external_domains; /*!< Accept calls to external SIP domains? */
730 static int global_callevents; /*!< Whether we send manager events or not */
731 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
732 static int global_t1; /*!< T1 time */
733 static int global_t1min; /*!< T1 roundtrip time minimum */
734 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
735 static int global_regextenonqualify; /*!< Whether to add/remove regexten when qualifying peers */
736 static int global_autoframing; /*!< Turn autoframing on or off. */
737 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
738 static struct sip_proxy global_outboundproxy; /*!< Outbound proxy */
739 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
740 static int global_qualifyfreq; /*!< Qualify frequency */
743 /*! \brief Codecs that we support by default: */
744 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
745 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
746 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
747 static int global_min_se; /*!< Lowest threshold for session refresh interval */
748 static int global_max_se; /*!< Highest threshold for session refresh interval */
750 /*@}*/
752 /*! \name Object counters @{
753 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
754 * should be used to modify these values. */
755 static int suserobjs = 0; /*!< Static users */
756 static int ruserobjs = 0; /*!< Realtime users */
757 static int speerobjs = 0; /*!< Static peers */
758 static int rpeerobjs = 0; /*!< Realtime peers */
759 static int apeerobjs = 0; /*!< Autocreated peer objects */
760 static int regobjs = 0; /*!< Registry objects */
761 /* }@ */
763 static struct ast_flags global_flags[2] = {{0}}; /*!< global SIP_ flags */
764 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
767 AST_MUTEX_DEFINE_STATIC(netlock);
769 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
770 when it's doing something critical. */
772 AST_MUTEX_DEFINE_STATIC(monlock);
774 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
776 /*! \brief This is the thread for the monitor which checks for input on the channels
777 which are not currently in use. */
778 static pthread_t monitor_thread = AST_PTHREADT_NULL;
780 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
781 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
783 static struct sched_context *sched; /*!< The scheduling context */
784 static struct io_context *io; /*!< The IO context */
785 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
787 #define DEC_CALL_LIMIT 0
788 #define INC_CALL_LIMIT 1
789 #define DEC_CALL_RINGING 2
790 #define INC_CALL_RINGING 3
792 /*!< Define some SIP transports */
793 enum sip_transport {
794 SIP_TRANSPORT_UDP = 1,
795 SIP_TRANSPORT_TCP = 1 << 1,
796 SIP_TRANSPORT_TLS = 1 << 2,
799 /*!< The SIP socket definition */
800 struct sip_socket {
801 enum sip_transport type;
802 int fd;
803 uint16_t port;
804 struct ast_tcptls_session_instance *ser;
807 /*! \brief sip_request: The data grabbed from the UDP socket
809 * \verbatim
810 * Incoming messages: we first store the data from the socket in data[],
811 * adding a trailing \0 to make string parsing routines happy.
812 * Then call parse_request() and req.method = find_sip_method();
813 * to initialize the other fields. The \r\n at the end of each line is
814 * replaced by \0, so that data[] is not a conforming SIP message anymore.
815 * After this processing, rlPart1 is set to non-NULL to remember
816 * that we can run get_header() on this kind of packet.
818 * parse_request() splits the first line as follows:
819 * Requests have in the first line method uri SIP/2.0
820 * rlPart1 = method; rlPart2 = uri;
821 * Responses have in the first line SIP/2.0 NNN description
822 * rlPart1 = SIP/2.0; rlPart2 = NNN + description;
824 * For outgoing packets, we initialize the fields with init_req() or init_resp()
825 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
826 * and then fill the rest with add_header() and add_line().
827 * The \r\n at the end of the line are still there, so the get_header()
828 * and similar functions don't work on these packets.
829 * \endverbatim
831 struct sip_request {
832 char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */
833 char *rlPart2; /*!< The Request URI or Response Status */
834 int len; /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
835 int headers; /*!< # of SIP Headers */
836 int method; /*!< Method of this request */
837 int lines; /*!< Body Content */
838 unsigned int sdp_start; /*!< the line number where the SDP begins */
839 unsigned int sdp_end; /*!< the line number where the SDP ends */
840 char debug; /*!< print extra debugging if non zero */
841 char has_to_tag; /*!< non-zero if packet has To: tag */
842 char ignore; /*!< if non-zero This is a re-transmit, ignore it */
843 char *header[SIP_MAX_HEADERS];
844 char *line[SIP_MAX_LINES];
845 struct ast_str *data;
846 /* XXX Do we need to unref socket.ser when the request goes away? */
847 struct sip_socket socket; /*!< The socket used for this request */
850 /*! \brief structure used in transfers */
851 struct sip_dual {
852 struct ast_channel *chan1; /*!< First channel involved */
853 struct ast_channel *chan2; /*!< Second channel involved */
854 struct sip_request req; /*!< Request that caused the transfer (REFER) */
855 int seqno; /*!< Sequence number */
858 struct sip_pkt;
860 /*! \brief Parameters to the transmit_invite function */
861 struct sip_invite_param {
862 int addsipheaders; /*!< Add extra SIP headers */
863 const char *uri_options; /*!< URI options to add to the URI */
864 const char *vxml_url; /*!< VXML url for Cisco phones */
865 char *auth; /*!< Authentication */
866 char *authheader; /*!< Auth header */
867 enum sip_auth_type auth_type; /*!< Authentication type */
868 const char *replaces; /*!< Replaces header for call transfers */
869 int transfer; /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
872 /*! \brief Structure to save routing information for a SIP session */
873 struct sip_route {
874 struct sip_route *next;
875 char hop[0];
878 /*! \brief Modes for SIP domain handling in the PBX */
879 enum domain_mode {
880 SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */
881 SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */
884 /*! \brief Domain data structure.
885 \note In the future, we will connect this to a configuration tree specific
886 for this domain
888 struct domain {
889 char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */
890 char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
891 enum domain_mode mode; /*!< How did we find this domain? */
892 AST_LIST_ENTRY(domain) list; /*!< List mechanics */
895 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
898 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
899 struct sip_history {
900 AST_LIST_ENTRY(sip_history) list;
901 char event[0]; /* actually more, depending on needs */
904 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
906 /*! \brief sip_auth: Credentials for authentication to other SIP services */
907 struct sip_auth {
908 char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */
909 char username[256]; /*!< Username */
910 char secret[256]; /*!< Secret */
911 char md5secret[256]; /*!< MD5Secret */
912 struct sip_auth *next; /*!< Next auth structure in list */
915 /*! \name SIPflags
916 Various flags for the flags field in the pvt structure
917 Trying to sort these up (one or more of the following):
918 D: Dialog
919 P: Peer/user
920 G: Global flag
921 When flags are used by multiple structures, it is important that
922 they have a common layout so it is easy to copy them.
924 /*@{*/
925 #define SIP_OUTGOING (1 << 0) /*!< D: Direction of the last transaction in this dialog */
926 #define SIP_RINGING (1 << 2) /*!< D: Have sent 180 ringing */
927 #define SIP_PROGRESS_SENT (1 << 3) /*!< D: Have sent 183 message progress */
928 #define SIP_NEEDREINVITE (1 << 4) /*!< D: Do we need to send another reinvite? */
929 #define SIP_PENDINGBYE (1 << 5) /*!< D: Need to send bye after we ack? */
930 #define SIP_GOTREFER (1 << 6) /*!< D: Got a refer? */
931 #define SIP_CALL_LIMIT (1 << 7) /*!< D: Call limit enforced for this call */
932 #define SIP_INC_COUNT (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
933 #define SIP_INC_RINGING (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
934 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10) /*!< D: Do not hangup at first ast_hangup */
936 #define SIP_PROMISCREDIR (1 << 11) /*!< DP: Promiscuous redirection */
937 #define SIP_TRUSTRPID (1 << 12) /*!< DP: Trust RPID headers? */
938 #define SIP_USEREQPHONE (1 << 13) /*!< DP: Add user=phone to numeric URI. Default off */
939 #define SIP_USECLIENTCODE (1 << 14) /*!< DP: Trust X-ClientCode info message */
941 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
942 #define SIP_DTMF (7 << 15) /*!< DP: DTMF Support: five settings, uses three bits */
943 #define SIP_DTMF_RFC2833 (0 << 15) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
944 #define SIP_DTMF_INBAND (1 << 15) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
945 #define SIP_DTMF_INFO (2 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" */
946 #define SIP_DTMF_AUTO (3 << 15) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
947 #define SIP_DTMF_SHORTINFO (4 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
949 /* NAT settings - see nat2str() */
950 #define SIP_NAT (3 << 18) /*!< DP: four settings, uses two bits */
951 #define SIP_NAT_NEVER (0 << 18) /*!< DP: No nat support */
952 #define SIP_NAT_RFC3581 (1 << 18) /*!< DP: NAT RFC3581 */
953 #define SIP_NAT_ROUTE (2 << 18) /*!< DP: NAT Only ROUTE */
954 #define SIP_NAT_ALWAYS (3 << 18) /*!< DP: NAT Both ROUTE and RFC3581 */
956 /* re-INVITE related settings */
957 #define SIP_REINVITE (7 << 20) /*!< DP: four settings, uses three bits */
958 #define SIP_REINVITE_NONE (0 << 20) /*!< DP: no reinvite allowed */
959 #define SIP_CAN_REINVITE (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
960 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
961 #define SIP_REINVITE_UPDATE (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
963 /* "insecure" settings - see insecure2str() */
964 #define SIP_INSECURE (3 << 23) /*!< DP: three settings, uses two bits */
965 #define SIP_INSECURE_NONE (0 << 23) /*!< DP: secure mode */
966 #define SIP_INSECURE_PORT (1 << 23) /*!< DP: don't require matching port for incoming requests */
967 #define SIP_INSECURE_INVITE (1 << 24) /*!< DP: don't require authentication for incoming INVITEs */
969 /* Sending PROGRESS in-band settings */
970 #define SIP_PROG_INBAND (3 << 25) /*!< DP: three settings, uses two bits */
971 #define SIP_PROG_INBAND_NEVER (0 << 25)
972 #define SIP_PROG_INBAND_NO (1 << 25)
973 #define SIP_PROG_INBAND_YES (2 << 25)
975 #define SIP_SENDRPID (1 << 29) /*!< DP: Remote Party-ID Support */
976 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
978 /*! \brief Flags to copy from peer/user to dialog */
979 #define SIP_FLAGS_TO_COPY \
980 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
981 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
982 SIP_USEREQPHONE | SIP_INSECURE)
983 /*@}*/
985 /*! \name SIPflags2
986 a second page of flags (for flags[1] */
987 /*@{*/
988 /* realtime flags */
989 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
990 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
991 /* Space for addition of other realtime flags in the future */
992 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9) /*!< D: Unsent state pending change exists */
994 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14) /*!< DP: Video supported if offered? */
995 #define SIP_PAGE2_TEXTSUPPORT (1 << 15) /*!< GDP: Global text enable */
996 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< GP: Allow subscriptions from this peer? */
997 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< DP: Allow overlap dialing ? */
998 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< GP: Only issue MWI notification if subscribed to */
1000 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< GDP: T38 Fax Passthrough Support */
1001 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< GDP: T38 Fax Passthrough Support */
1002 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1003 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< GDP: T38 Fax Passthrough Support (not implemented) */
1005 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< D: Call hold states: */
1006 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23) /*!< D: Active hold */
1007 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23) /*!< D: One directional hold */
1008 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23) /*!< D: Inactive hold */
1010 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< DP: Compensate for buggy RFC2833 implementations */
1011 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< DP: Buggy CISCO MWI fix */
1012 #define SIP_PAGE2_REGISTERTRYING (1 << 29) /*!< DP: Send 100 Trying on REGISTER attempts */
1013 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30) /*!< DP: Use source IP of RTP as destination if NAT is enabled */
1015 #define SIP_PAGE2_FLAGS_TO_COPY \
1016 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
1017 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
1018 SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_UDPTL_DESTINATION)
1020 /*@}*/
1022 /*! \name SIPflagsT38
1023 T.38 set of flags */
1025 /*@{*/
1026 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/
1027 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/
1028 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/
1029 /* Rate management */
1030 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3)
1031 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
1032 /* UDP Error correction */
1033 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
1034 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */
1035 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */
1036 /* T38 Spec version */
1037 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */
1038 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */
1039 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */
1040 /* Maximum Fax Rate */
1041 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */
1042 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */
1043 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */
1044 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */
1045 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */
1046 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */
1048 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
1049 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
1050 /*@}*/
1052 /*! \brief debugging state
1053 * We store separately the debugging requests from the config file
1054 * and requests from the CLI. Debugging is enabled if either is set
1055 * (which means that if sipdebug is set in the config file, we can
1056 * only turn it off by reloading the config).
1058 enum sip_debug_e {
1059 sip_debug_none = 0,
1060 sip_debug_config = 1,
1061 sip_debug_console = 2,
1064 static enum sip_debug_e sipdebug;
1066 /*! \brief extra debugging for 'text' related events.
1067 * At thie moment this is set together with sip_debug_console.
1068 * It should either go away or be implemented properly.
1070 static int sipdebug_text;
1072 /*! \brief T38 States for a call */
1073 enum t38state {
1074 T38_DISABLED = 0, /*!< Not enabled */
1075 T38_LOCAL_DIRECT, /*!< Offered from local */
1076 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */
1077 T38_PEER_DIRECT, /*!< Offered from peer */
1078 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */
1079 T38_ENABLED /*!< Negotiated (enabled) */
1082 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
1083 struct t38properties {
1084 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */
1085 int capability; /*!< Our T38 capability */
1086 int peercapability; /*!< Peers T38 capability */
1087 int jointcapability; /*!< Supported T38 capability at both ends */
1088 enum t38state state; /*!< T.38 state */
1091 /*! \brief Parameters to know status of transfer */
1092 enum referstatus {
1093 REFER_IDLE, /*!< No REFER is in progress */
1094 REFER_SENT, /*!< Sent REFER to transferee */
1095 REFER_RECEIVED, /*!< Received REFER from transferrer */
1096 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING (unused) */
1097 REFER_ACCEPTED, /*!< Accepted by transferee */
1098 REFER_RINGING, /*!< Target Ringing */
1099 REFER_200OK, /*!< Answered by transfer target */
1100 REFER_FAILED, /*!< REFER declined - go on */
1101 REFER_NOAUTH /*!< We had no auth for REFER */
1104 /*! \brief generic struct to map between strings and integers.
1105 * Fill it with x-s pairs, terminate with an entry with s = NULL;
1106 * Then you can call map_x_s(...) to map an integer to a string,
1107 * and map_s_x() for the string -> integer mapping.
1109 struct _map_x_s {
1110 int x;
1111 const char *s;
1114 static const struct _map_x_s referstatusstrings[] = {
1115 { REFER_IDLE, "<none>" },
1116 { REFER_SENT, "Request sent" },
1117 { REFER_RECEIVED, "Request received" },
1118 { REFER_CONFIRMED, "Confirmed" },
1119 { REFER_ACCEPTED, "Accepted" },
1120 { REFER_RINGING, "Target ringing" },
1121 { REFER_200OK, "Done" },
1122 { REFER_FAILED, "Failed" },
1123 { REFER_NOAUTH, "Failed - auth failure" },
1124 { -1, NULL} /* terminator */
1127 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1128 \note OEJ: Should be moved to string fields */
1129 struct sip_refer {
1130 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */
1131 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */
1132 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */
1133 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
1134 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1135 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
1136 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */
1137 char replaces_callid[SIPBUFSIZE]; /*!< Replace info: callid */
1138 char replaces_callid_totag[SIPBUFSIZE/2]; /*!< Replace info: to-tag */
1139 char replaces_callid_fromtag[SIPBUFSIZE/2]; /*!< Replace info: from-tag */
1140 struct sip_pvt *refer_call; /*!< Call we are referring. This is just a reference to a
1141 * dialog owned by someone else, so we should not destroy
1142 * it when the sip_refer object goes.
1144 int attendedtransfer; /*!< Attended or blind transfer? */
1145 int localtransfer; /*!< Transfer to local domain? */
1146 enum referstatus status; /*!< REFER status */
1150 /*! \brief Structure that encapsulates all attributes related to running
1151 * SIP Session-Timers feature on a per dialog basis.
1153 struct sip_st_dlg {
1154 int st_active; /*!< Session-Timers on/off */
1155 int st_interval; /*!< Session-Timers negotiated session refresh interval */
1156 int st_schedid; /*!< Session-Timers ast_sched scheduler id */
1157 enum st_refresher st_ref; /*!< Session-Timers session refresher */
1158 int st_expirys; /*!< Session-Timers number of expirys */
1159 int st_active_peer_ua; /*!< Session-Timers on/off in peer UA */
1160 int st_cached_min_se; /*!< Session-Timers cached Min-SE */
1161 int st_cached_max_se; /*!< Session-Timers cached Session-Expires */
1162 enum st_mode st_cached_mode; /*!< Session-Timers cached M.O. */
1163 enum st_refresher st_cached_ref; /*!< Session-Timers cached refresher */
1167 /*! \brief Structure that encapsulates all attributes related to configuration
1168 * of SIP Session-Timers feature on a per user/peer basis.
1170 struct sip_st_cfg {
1171 enum st_mode st_mode_oper; /*!< Mode of operation for Session-Timers */
1172 enum st_refresher st_ref; /*!< Session-Timer refresher */
1173 int st_min_se; /*!< Lowest threshold for session refresh interval */
1174 int st_max_se; /*!< Highest threshold for session refresh interval */
1180 /*! \brief sip_pvt: structures used for each SIP dialog, ie. a call, a registration, a subscribe.
1181 * Created and initialized by sip_alloc(), the descriptor goes into the list of
1182 * descriptors (dialoglist).
1184 struct sip_pvt {
1185 struct sip_pvt *next; /*!< Next dialog in chain */
1186 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */
1187 int method; /*!< SIP method that opened this dialog */
1188 AST_DECLARE_STRING_FIELDS(
1189 AST_STRING_FIELD(callid); /*!< Global CallID */
1190 AST_STRING_FIELD(randdata); /*!< Random data */
1191 AST_STRING_FIELD(accountcode); /*!< Account code */
1192 AST_STRING_FIELD(realm); /*!< Authorization realm */
1193 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1194 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1195 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1196 AST_STRING_FIELD(domain); /*!< Authorization domain */
1197 AST_STRING_FIELD(from); /*!< The From: header */
1198 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */
1199 AST_STRING_FIELD(exten); /*!< Extension where to start */
1200 AST_STRING_FIELD(context); /*!< Context for this call */
1201 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1202 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1203 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
1204 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */
1205 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */
1206 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */
1207 AST_STRING_FIELD(todnid); /*!< DNID of this call (overrides host) */
1208 AST_STRING_FIELD(language); /*!< Default language for this call */
1209 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1210 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
1211 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */
1212 AST_STRING_FIELD(redircause); /*!< Referring cause */
1213 AST_STRING_FIELD(theirtag); /*!< Their tag */
1214 AST_STRING_FIELD(username); /*!< [user] name */
1215 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */
1216 AST_STRING_FIELD(authname); /*!< Who we use for authentication */
1217 AST_STRING_FIELD(uri); /*!< Original requested URI */
1218 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1219 AST_STRING_FIELD(peersecret); /*!< Password */
1220 AST_STRING_FIELD(peermd5secret);
1221 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
1222 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */
1223 AST_STRING_FIELD(via); /*!< Via: header */
1224 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */
1225 /* we only store the part in <brackets> in this field. */
1226 AST_STRING_FIELD(our_contact); /*!< Our contact header */
1227 AST_STRING_FIELD(rpid); /*!< Our RPID header */
1228 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */
1229 AST_STRING_FIELD(url); /*!< URL to be sent with next message to peer */
1230 AST_STRING_FIELD(parkinglot); /*!< Parkinglot */
1232 struct sip_socket socket; /*!< The socket used for this dialog */
1233 unsigned int ocseq; /*!< Current outgoing seqno */
1234 unsigned int icseq; /*!< Current incoming seqno */
1235 ast_group_t callgroup; /*!< Call group */
1236 ast_group_t pickupgroup; /*!< Pickup group */
1237 int lastinvite; /*!< Last Cseq of invite */
1238 int lastnoninvite; /*!< Last Cseq of non-invite */
1239 struct ast_flags flags[2]; /*!< SIP_ flags */
1241 /* boolean or small integers that don't belong in flags */
1242 char do_history; /*!< Set if we want to record history */
1243 char alreadygone; /*!< already destroyed by our peer */
1244 char needdestroy; /*!< need to be destroyed by the monitor thread */
1245 char outgoing_call; /*!< this is an outgoing call */
1246 char answered_elsewhere; /*!< This call is cancelled due to answer on another channel */
1247 char novideo; /*!< Didn't get video in invite, don't offer */
1248 char notext; /*!< Text not supported (?) */
1250 int timer_t1; /*!< SIP timer T1, ms rtt */
1251 int timer_b; /*!< SIP timer B, ms */
1252 unsigned int sipoptions; /*!< Supported SIP options on the other end */
1253 unsigned int reqsipoptions; /*!< Required SIP options on the other end */
1254 struct ast_codec_pref prefs; /*!< codec prefs */
1255 int capability; /*!< Special capability (codec) */
1256 int jointcapability; /*!< Supported capability at both ends (codecs) */
1257 int peercapability; /*!< Supported peer capability */
1258 int prefcodec; /*!< Preferred codec (outbound only) */
1259 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */
1260 int jointnoncodeccapability; /*!< Joint Non codec capability */
1261 int redircodecs; /*!< Redirect codecs */
1262 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */
1263 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog */
1264 struct t38properties t38; /*!< T38 settings */
1265 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
1266 struct ast_udptl *udptl; /*!< T.38 UDPTL session */
1267 int callingpres; /*!< Calling presentation */
1268 int authtries; /*!< Times we've tried to authenticate */
1269 int expiry; /*!< How long we take to expire */
1270 long branch; /*!< The branch identifier of this session */
1271 char tag[11]; /*!< Our tag for this session */
1272 int sessionid; /*!< SDP Session ID */
1273 int sessionversion; /*!< SDP Session Version */
1274 int sessionversion_remote; /*!< Remote UA's SDP Session Version */
1275 int session_modify; /*!< Session modification request true/false */
1276 struct sockaddr_in sa; /*!< Our peer */
1277 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */
1278 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */
1279 struct sockaddr_in tredirip; /*!< Where our Text RTP should be going if not to us */
1280 time_t lastrtprx; /*!< Last RTP received */
1281 time_t lastrtptx; /*!< Last RTP sent */
1282 int rtptimeout; /*!< RTP timeout time */
1283 struct sockaddr_in recv; /*!< Received as */
1284 struct sockaddr_in ourip; /*!< Our IP (as seen from the outside) */
1285 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */
1286 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */
1287 int route_persistant; /*!< Is this the "real" route? */
1288 struct ast_variable *notify_headers; /*!< Custom notify type */
1289 struct sip_auth *peerauth; /*!< Realm authentication */
1290 int noncecount; /*!< Nonce-count */
1291 char lastmsg[256]; /*!< Last Message sent/received */
1292 int amaflags; /*!< AMA Flags */
1293 int pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1294 struct sip_request initreq; /*!< Latest request that opened a new transaction
1295 within this dialog.
1296 NOT the request that opened the dialog
1299 int initid; /*!< Auto-congest ID if appropriate (scheduler) */
1300 int waitid; /*!< Wait ID for scheduler after 491 or other delays */
1301 int autokillid; /*!< Auto-kill ID (scheduler) */
1302 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */
1303 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */
1304 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */
1305 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */
1306 int laststate; /*!< SUBSCRIBE: Last known extension state */
1307 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */
1309 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */
1311 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one
1312 Used in peerpoke, mwi subscriptions */
1313 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */
1314 struct ast_rtp *rtp; /*!< RTP Session */
1315 struct ast_rtp *vrtp; /*!< Video RTP session */
1316 struct ast_rtp *trtp; /*!< Text RTP session */
1317 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */
1318 struct sip_history_head *history; /*!< History of this SIP dialog */
1319 size_t history_entries; /*!< Number of entires in the history */
1320 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1321 struct sip_invite_param *options; /*!< Options for INVITE */
1322 int autoframing; /*!< The number of Asters we group in a Pyroflax
1323 before strolling to the Grokyzpå
1324 (A bit unsure of this, please correct if
1325 you know more) */
1326 struct sip_st_dlg *stimer; /*!< SIP Session-Timers */
1328 int red;
1331 /*! Max entires in the history list for a sip_pvt */
1332 #define MAX_HISTORY_ENTRIES 50
1335 * Here we implement the container for dialogs (sip_pvt), defining
1336 * generic wrapper functions to ease the transition from the current
1337 * implementation (a single linked list) to a different container.
1338 * In addition to a reference to the container, we need functions to lock/unlock
1339 * the container and individual items, and functions to add/remove
1340 * references to the individual items.
1342 struct ao2_container *dialogs;
1345 * when we create or delete references, make sure to use these
1346 * functions so we keep track of the refcounts.
1347 * To simplify the code, we allow a NULL to be passed to dialog_unref().
1349 #ifdef REF_DEBUG
1350 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1351 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1352 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1354 if (p)
1355 _ao2_ref_debug(p, 1, tag, file, line, func);
1356 else
1357 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1358 return p;
1361 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
1363 if (p)
1364 _ao2_ref_debug(p, -1, tag, file, line, func);
1365 return NULL;
1367 #else
1368 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
1370 if (p)
1371 ao2_ref(p, 1);
1372 else
1373 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
1374 return p;
1377 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
1379 if (p)
1380 ao2_ref(p, -1);
1381 return NULL;
1383 #endif
1385 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1386 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1387 * Each packet holds a reference to the parent struct sip_pvt.
1388 * This structure is allocated in __sip_reliable_xmit() and only for packets that
1389 * require retransmissions.
1391 struct sip_pkt {
1392 struct sip_pkt *next; /*!< Next packet in linked list */
1393 int retrans; /*!< Retransmission number */
1394 int method; /*!< SIP method for this packet */
1395 int seqno; /*!< Sequence number */
1396 char is_resp; /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1397 char is_fatal; /*!< non-zero if there is a fatal error */
1398 struct sip_pvt *owner; /*!< Owner AST call */
1399 int retransid; /*!< Retransmission ID */
1400 int timer_a; /*!< SIP timer A, retransmission timer */
1401 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */
1402 int packetlen; /*!< Length of packet */
1403 struct ast_str *data;
1406 /*! \brief Structure for SIP user data. User's place calls to us */
1407 struct sip_user {
1408 /* Users who can access various contexts */
1409 char name[80];
1410 char secret[80]; /*!< Password */
1411 char md5secret[80]; /*!< Password in md5 */
1412 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1413 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1414 char cid_num[80]; /*!< Caller ID num */
1415 char cid_name[80]; /*!< Caller ID name */
1416 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1417 char language[MAX_LANGUAGE]; /*!< Default language for this user */
1418 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1419 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1420 char parkinglot[AST_MAX_CONTEXT];/*!< Parkinglot */
1421 char useragent[256]; /*!< User agent in SIP request */
1422 struct ast_codec_pref prefs; /*!< codec prefs */
1423 ast_group_t callgroup; /*!< Call group */
1424 ast_group_t pickupgroup; /*!< Pickup Group */
1425 unsigned int sipoptions; /*!< Supported SIP options */
1426 struct ast_flags flags[2]; /*!< SIP_ flags */
1428 /* things that don't belong in flags */
1429 char is_realtime; /*!< this is a 'realtime' user */
1430 unsigned int the_mark:1; /*!< moved out of the ASTOBJ fields; that which bears the_mark should be deleted! */
1432 int amaflags; /*!< AMA flags for billing */
1433 int callingpres; /*!< Calling id presentation */
1434 int capability; /*!< Codec capability */
1435 int inUse; /*!< Number of calls in use */
1436 int call_limit; /*!< Limit of concurrent calls */
1437 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1438 struct ast_ha *ha; /*!< ACL setting */
1439 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1440 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1441 int autoframing;
1442 struct sip_st_cfg stimer; /*!< SIP Session-Timers */
1446 * \brief A peer's mailbox
1448 * We could use STRINGFIELDS here, but for only two strings, it seems like
1449 * too much effort ...
1451 struct sip_mailbox {
1452 char *mailbox;
1453 char *context;
1454 /*! Associated MWI subscription */
1455 struct ast_event_sub *event_sub;
1456 AST_LIST_ENTRY(sip_mailbox) entry;
1459 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
1460 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1461 struct sip_peer {
1462 char name[80]; /*!< peer->name is the unique name of this object */
1463 struct sip_socket socket; /*!< Socket used for this peer */
1464 char secret[80]; /*!< Password */
1465 char md5secret[80]; /*!< Password in MD5 */
1466 struct sip_auth *auth; /*!< Realm authentication list */
1467 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */
1468 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1469 char username[80]; /*!< Temporary username until registration */
1470 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1471 int amaflags; /*!< AMA Flags (for billing) */
1472 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */
1473 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1474 char fromuser[80]; /*!< From: user when calling this peer */
1475 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
1476 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */
1477 char cid_num[80]; /*!< Caller ID num */
1478 char cid_name[80]; /*!< Caller ID name */
1479 int callingpres; /*!< Calling id presentation */
1480 int inUse; /*!< Number of calls in use */
1481 int inRinging; /*!< Number of calls ringing */
1482 int onHold; /*!< Peer has someone on hold */
1483 int call_limit; /*!< Limit of concurrent calls */
1484 int busy_level; /*!< Level of active channels where we signal busy */
1485 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */
1486 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1487 char language[MAX_LANGUAGE]; /*!< Default language for prompts */
1488 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1489 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1490 char parkinglot[AST_MAX_CONTEXT];/*!< Parkinglot */
1491 char useragent[256]; /*!< User agent in SIP request (saved from registration) */
1492 struct ast_codec_pref prefs; /*!< codec prefs */
1493 int lastmsgssent;
1494 unsigned int sipoptions; /*!< Supported SIP options */
1495 struct ast_flags flags[2]; /*!< SIP_ flags */
1497 /*! Mailboxes that this peer cares about */
1498 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1500 /* things that don't belong in flags */
1501 char is_realtime; /*!< this is a 'realtime' peer */
1502 char rt_fromcontact; /*!< P: copy fromcontact from realtime */
1503 char host_dynamic; /*!< P: Dynamic Peers register with Asterisk */
1504 char selfdestruct; /*!< P: Automatic peers need to destruct themselves */
1505 char the_mark; /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
1507 int expire; /*!< When to expire this peer registration */
1508 int capability; /*!< Codec capability */
1509 int rtptimeout; /*!< RTP timeout */
1510 int rtpholdtimeout; /*!< RTP Hold Timeout */
1511 int rtpkeepalive; /*!< Send RTP packets for keepalive */
1512 ast_group_t callgroup; /*!< Call group */
1513 ast_group_t pickupgroup; /*!< Pickup group */
1514 struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
1515 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */
1516 struct sockaddr_in addr; /*!< IP address of peer */
1517 int maxcallbitrate; /*!< Maximum Bitrate for a video call */
1519 /* Qualification */
1520 struct sip_pvt *call; /*!< Call pointer */
1521 int pokeexpire; /*!< When to expire poke (qualify= checking) */
1522 int lastms; /*!< How long last response took (in ms), or -1 for no response */
1523 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
1524 int qualifyfreq; /*!< Qualification: How often to check for the host to be up */
1525 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */
1526 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */
1527 struct ast_ha *ha; /*!< Access control list */
1528 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
1529 struct sip_pvt *mwipvt; /*!< Subscription for MWI */
1530 int autoframing;
1531 struct sip_st_cfg stimer; /*!< SIP Session-Timers */
1532 int timer_t1; /*!< The maximum T1 value for the peer */
1533 int timer_b; /*!< The maximum timer B (transaction timeouts) */
1534 int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1538 /*! \brief Registrations with other SIP proxies
1539 * Created by sip_register(), the entry is linked in the 'regl' list,
1540 * and never deleted (other than at 'sip reload' or module unload times).
1541 * The entry always has a pending timeout, either waiting for an ACK to
1542 * the REGISTER message (in which case we have to retransmit the request),
1543 * or waiting for the next REGISTER message to be sent (either the initial one,
1544 * or once the previously completed registration one expires).
1545 * The registration can be in one of many states, though at the moment
1546 * the handling is a bit mixed.
1547 * Note that the entire evolution of sip_registry (transmissions,
1548 * incoming packets and timeouts) is driven by one single thread,
1549 * do_monitor(), so there is almost no synchronization issue.
1550 * The only exception is the sip_pvt creation/lookup,
1551 * as the dialoglist is also manipulated by other threads.
1553 struct sip_registry {
1554 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1555 AST_DECLARE_STRING_FIELDS(
1556 AST_STRING_FIELD(callid); /*!< Global Call-ID */
1557 AST_STRING_FIELD(realm); /*!< Authorization realm */
1558 AST_STRING_FIELD(nonce); /*!< Authorization nonce */
1559 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */
1560 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1561 AST_STRING_FIELD(domain); /*!< Authorization domain */
1562 AST_STRING_FIELD(username); /*!< Who we are registering as */
1563 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */
1564 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */
1565 AST_STRING_FIELD(secret); /*!< Password in clear text */
1566 AST_STRING_FIELD(md5secret); /*!< Password in md5 */
1567 AST_STRING_FIELD(callback); /*!< Contact extension */
1568 AST_STRING_FIELD(random);
1570 enum sip_transport transport;
1571 int portno; /*!< Optional port override */
1572 int expire; /*!< Sched ID of expiration */
1573 int expiry; /*!< Value to use for the Expires header */
1574 int regattempts; /*!< Number of attempts (since the last success) */
1575 int timeout; /*!< sched id of sip_reg_timeout */
1576 int refresh; /*!< How often to refresh */
1577 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1578 enum sipregistrystate regstate; /*!< Registration state (see above) */
1579 struct timeval regtime; /*!< Last successful registration time */
1580 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */
1581 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */
1582 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for register */
1583 struct sockaddr_in us; /*!< Who the server thinks we are */
1584 int noncecount; /*!< Nonce-count */
1585 char lastmsg[256]; /*!< Last Message sent/received */
1588 struct sip_threadinfo {
1589 int stop;
1590 pthread_t threadid;
1591 struct ast_tcptls_session_instance *ser;
1592 enum sip_transport type; /* We keep a copy of the type here so we can display it in the connection list */
1593 AST_LIST_ENTRY(sip_threadinfo) list;
1596 /* --- Hash tables of various objects --------*/
1598 #ifdef LOW_MEMORY
1599 static int hash_peer_size = 17;
1600 static int hash_dialog_size = 17;
1601 static int hash_user_size = 17;
1602 #else
1603 static int hash_peer_size = 563;
1604 static int hash_dialog_size = 563;
1605 static int hash_user_size = 563;
1606 #endif
1608 /*! \brief The thread list of TCP threads */
1609 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
1611 /*! \brief The user list: Users and friends */
1612 static struct ao2_container *users;
1614 /*! \brief The peer list: Peers and Friends */
1615 struct ao2_container *peers;
1616 struct ao2_container *peers_by_ip;
1618 /*! \brief The register list: Other SIP proxies we register with and place calls to */
1619 static struct ast_register_list {
1620 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1621 int recheck;
1622 } regl;
1625 * \note The only member of the peer used here is the name field
1627 static int peer_hash_cb(const void *obj, const int flags)
1629 const struct sip_peer *peer = obj;
1631 return ast_str_hash(peer->name);
1635 * \note The only member of the peer used here is the name field
1637 static int peer_cmp_cb(void *obj, void *arg, int flags)
1639 struct sip_peer *peer = obj, *peer2 = arg;
1641 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1645 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1647 static int peer_iphash_cb(const void *obj, const int flags)
1649 const struct sip_peer *peer = obj;
1650 int ret1 = peer->addr.sin_addr.s_addr;
1651 if (ret1 < 0)
1652 ret1 = -ret1;
1654 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
1655 return ret1;
1656 } else {
1657 return ret1 + peer->addr.sin_port;
1662 * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
1664 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
1666 struct sip_peer *peer = obj, *peer2 = arg;
1668 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr)
1669 return 0;
1671 if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
1672 if (peer->addr.sin_port == peer2->addr.sin_port)
1673 return CMP_MATCH;
1674 else
1675 return 0;
1677 return CMP_MATCH;
1681 * \note The only member of the user used here is the name field
1683 static int user_hash_cb(const void *obj, const int flags)
1685 const struct sip_user *user = obj;
1687 return ast_str_hash(user->name);
1691 * \note The only member of the user used here is the name field
1693 static int user_cmp_cb(void *obj, void *arg, int flags)
1695 struct sip_user *user = obj, *user2 = arg;
1697 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1701 * \note The only member of the dialog used here callid string
1703 static int dialog_hash_cb(const void *obj, const int flags)
1705 const struct sip_pvt *pvt = obj;
1707 return ast_str_hash(pvt->callid);
1711 * \note The only member of the dialog used here callid string
1713 static int dialog_cmp_cb(void *obj, void *arg, int flags)
1715 struct sip_pvt *pvt = obj, *pvt2 = arg;
1717 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
1720 static int temp_pvt_init(void *);
1721 static void temp_pvt_cleanup(void *);
1723 /*! \brief A per-thread temporary pvt structure */
1724 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1726 #ifdef LOW_MEMORY
1727 static void ts_ast_rtp_destroy(void *);
1729 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
1730 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
1731 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
1732 #endif
1734 /*! \brief Authentication list for realm authentication
1735 * \todo Move the sip_auth list to AST_LIST */
1736 static struct sip_auth *authl = NULL;
1739 /* --- Sockets and networking --------------*/
1741 /*! \brief Main socket for SIP communication.
1743 * sipsock is shared between the SIP manager thread (which handles reload
1744 * requests), the io handler (sipsock_read()) and the user routines that
1745 * issue writes (using __sip_xmit()).
1746 * The socket is -1 only when opening fails (this is a permanent condition),
1747 * or when we are handling a reload() that changes its address (this is
1748 * a transient situation during which we might have a harmless race, see
1749 * below). Because the conditions for the race to be possible are extremely
1750 * rare, we don't want to pay the cost of locking on every I/O.
1751 * Rather, we remember that when the race may occur, communication is
1752 * bound to fail anyways, so we just live with this event and let
1753 * the protocol handle this above us.
1755 static int sipsock = -1;
1757 static struct sockaddr_in bindaddr; /*!< The address we bind to */
1759 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1760 * internip is initialized picking a suitable address from one of the
1761 * interfaces, and the same port number we bind to. It is used as the
1762 * default address/port in SIP messages, and as the default address
1763 * (but not port) in SDP messages.
1765 static struct sockaddr_in internip;
1767 /*! \brief our external IP address/port for SIP sessions.
1768 * externip.sin_addr is only set when we know we might be behind
1769 * a NAT, and this is done using a variety of (mutually exclusive)
1770 * ways from the config file:
1772 * + with "externip = host[:port]" we specify the address/port explicitly.
1773 * The address is looked up only once when (re)loading the config file;
1775 * + with "externhost = host[:port]" we do a similar thing, but the
1776 * hostname is stored in externhost, and the hostname->IP mapping
1777 * is refreshed every 'externrefresh' seconds;
1779 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1780 * to the specified server, and store the result in externip.
1782 * Other variables (externhost, externexpire, externrefresh) are used
1783 * to support the above functions.
1785 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */
1787 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1788 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1789 static int externrefresh = 10;
1790 static struct sockaddr_in stunaddr; /*!< stun server address */
1792 /*! \brief List of local networks
1793 * We store "localnet" addresses from the config file into an access list,
1794 * marked as 'DENY', so the call to ast_apply_ha() will return
1795 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1796 * (i.e. presumably public) addresses.
1798 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1800 static int ourport_tcp;
1801 static int ourport_tls;
1802 static struct sockaddr_in debugaddr;
1804 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */
1806 /*! some list management macros. */
1808 #define UNLINK(element, head, prev) do { \
1809 if (prev) \
1810 (prev)->next = (element)->next; \
1811 else \
1812 (head) = (element)->next; \
1813 } while (0)
1815 enum t38_action_flag {
1816 SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
1817 SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
1818 SDP_T38_ACCEPT, /*!< Remote side accepted our T38 request */
1821 /*---------------------------- Forward declarations of functions in chan_sip.c */
1822 /* Note: This is added to help splitting up chan_sip.c into several files
1823 in coming releases. */
1825 /*--- PBX interface functions */
1826 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1827 static int sip_devicestate(void *data);
1828 static int sip_sendtext(struct ast_channel *ast, const char *text);
1829 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1830 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1831 static int sip_hangup(struct ast_channel *ast);
1832 static int sip_answer(struct ast_channel *ast);
1833 static struct ast_frame *sip_read(struct ast_channel *ast);
1834 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1835 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1836 static int sip_transfer(struct ast_channel *ast, const char *dest);
1837 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1838 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1839 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1840 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1841 static const char *sip_get_callid(struct ast_channel *chan);
1843 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1844 static int sip_standard_port(struct sip_socket s);
1845 static int sip_prepare_socket(struct sip_pvt *p);
1847 /*--- Transmitting responses and requests */
1848 static int sipsock_read(int *id, int fd, short events, void *ignore);
1849 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1850 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1851 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1852 static int retrans_pkt(const void *data);
1853 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);
1854 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1855 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1856 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1857 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
1858 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1859 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);
1860 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1861 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1862 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1863 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1864 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1865 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1866 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1867 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1868 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1869 static int transmit_refer(struct sip_pvt *p, const char *dest);
1870 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1871 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1872 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
1873 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1874 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1875 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1876 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1877 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1878 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1879 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1881 /*--- Dialog management */
1882 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1883 int useglobal_nat, const int intended_method);
1884 static int __sip_autodestruct(const void *data);
1885 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1886 static int sip_cancel_destroy(struct sip_pvt *p);
1887 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1888 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
1889 static void *registry_unref(struct sip_registry *reg, char *tag);
1890 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1891 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1892 static void __sip_pretend_ack(struct sip_pvt *p);
1893 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1894 static int auto_congest(const void *arg);
1895 static int update_call_counter(struct sip_pvt *fup, int event);
1896 static int hangup_sip2cause(int cause);
1897 static const char *hangup_cause2sip(int cause);
1898 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1899 static void free_old_route(struct sip_route *route);
1900 static void list_route(struct sip_route *route);
1901 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1902 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1903 struct sip_request *req, char *uri);
1904 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1905 static void check_pendings(struct sip_pvt *p);
1906 static void *sip_park_thread(void *stuff);
1907 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1908 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1910 /*--- Codec handling / SDP */
1911 static void try_suggested_sip_codec(struct sip_pvt *p);
1912 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1913 static const char *get_sdp(struct sip_request *req, const char *name);
1914 static int find_sdp(struct sip_request *req);
1915 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1916 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1917 struct ast_str **m_buf, struct ast_str **a_buf,
1918 int debug, int *min_packet_size);
1919 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1920 struct ast_str **m_buf, struct ast_str **a_buf,
1921 int debug);
1922 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp);
1923 static void do_setnat(struct sip_pvt *p, int natflags);
1924 static void stop_media_flows(struct sip_pvt *p);
1926 /*--- Authentication stuff */
1927 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1928 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1929 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1930 const char *secret, const char *md5secret, int sipmethod,
1931 char *uri, enum xmittype reliable, int ignore);
1932 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1933 int sipmethod, char *uri, enum xmittype reliable,
1934 struct sockaddr_in *sin, struct sip_peer **authpeer);
1935 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1937 /*--- Domain handling */
1938 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1939 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1940 static void clear_sip_domains(void);
1942 /*--- SIP realm authentication */
1943 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1944 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
1945 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1947 /*--- Misc functions */
1948 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1949 static int sip_do_reload(enum channelreloadreason reason);
1950 static int reload_config(enum channelreloadreason reason);
1951 static int expire_register(const void *data);
1952 static void *do_monitor(void *data);
1953 static int restart_monitor(void);
1954 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1955 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1956 static int sip_refer_allocate(struct sip_pvt *p);
1957 static void ast_quiet_chan(struct ast_channel *chan);
1958 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1960 /*--- Device monitoring and Device/extension state/event handling */
1961 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1962 static int sip_devicestate(void *data);
1963 static int sip_poke_noanswer(const void *data);
1964 static int sip_poke_peer(struct sip_peer *peer, int force);
1965 static void sip_poke_all_peers(void);
1966 static void sip_peer_hold(struct sip_pvt *p, int hold);
1967 static void mwi_event_cb(const struct ast_event *, void *);
1969 /*--- Applications, functions, CLI and manager command helpers */
1970 static const char *sip_nat_mode(const struct sip_pvt *p);
1971 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1972 static char *transfermode2str(enum transfermodes mode) attribute_const;
1973 static const char *nat2str(int nat) attribute_const;
1974 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1975 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1976 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1977 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1978 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1979 static char *_sip_dbdump(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1980 static char *sip_dbdump(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1981 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1982 static void print_group(int fd, ast_group_t group, int crlf);
1983 static const char *dtmfmode2str(int mode) attribute_const;
1984 static int str2dtmfmode(const char *str) attribute_unused;
1985 static const char *insecure2str(int mode) attribute_const;
1986 static void cleanup_stale_contexts(char *new, char *old);
1987 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1988 static const char *domain_mode_to_text(const enum domain_mode mode);
1989 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1990 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1991 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1992 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1993 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1994 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1995 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1996 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1997 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1998 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1999 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2000 static char *complete_sip_peer(const char *word, int state, int flags2);
2001 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
2002 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
2003 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
2004 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
2005 static char *complete_sip_user(const char *word, int state, int flags2);
2006 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
2007 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
2008 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2009 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2010 static char *sip_do_debug_ip(int fd, char *arg);
2011 static char *sip_do_debug_peer(int fd, char *arg);
2012 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2013 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2014 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2015 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2016 static int sip_dtmfmode(struct ast_channel *chan, void *data);
2017 static int sip_addheader(struct ast_channel *chan, void *data);
2018 static int sip_do_reload(enum channelreloadreason reason);
2019 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2020 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
2022 /*--- Debugging
2023 Functions for enabling debug per IP or fully, or enabling history logging for
2024 a SIP dialog
2026 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
2027 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
2028 static inline int sip_debug_test_pvt(struct sip_pvt *p);
2031 /*! \brief Append to SIP dialog history
2032 \return Always returns 0 */
2033 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2034 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
2035 static void sip_dump_history(struct sip_pvt *dialog);
2037 /*--- Device object handling */
2038 static struct sip_peer *temp_peer(const char *name);
2039 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
2040 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
2041 static int update_call_counter(struct sip_pvt *fup, int event);
2042 static void sip_destroy_peer(struct sip_peer *peer);
2043 static void sip_destroy_peer_fn(void *peer);
2044 static void sip_destroy_user(struct sip_user *user);
2045 static void sip_destroy_user_fn(void *user);
2046 static void set_peer_defaults(struct sip_peer *peer);
2047 static struct sip_peer *temp_peer(const char *name);
2048 static void register_peer_exten(struct sip_peer *peer, int onoff);
2049 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
2050 static struct sip_user *find_user(const char *name, int realtime);
2051 static int sip_poke_peer_s(const void *data);
2052 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
2053 static void reg_source_db(struct sip_peer *peer);
2054 static void destroy_association(struct sip_peer *peer);
2055 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
2056 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
2058 /* Realtime device support */
2059 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);
2060 static struct sip_user *realtime_user(const char *username);
2061 static void update_peer(struct sip_peer *p, int expiry);
2062 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
2063 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
2064 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
2065 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2067 /*--- Internal UA client handling (outbound registrations) */
2068 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
2069 static void sip_registry_destroy(struct sip_registry *reg);
2070 static int sip_register(const char *value, int lineno);
2071 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
2072 static int sip_reregister(const void *data);
2073 static int __sip_do_register(struct sip_registry *r);
2074 static int sip_reg_timeout(const void *data);
2075 static void sip_send_all_registers(void);
2076 static int sip_reinvite_retry(const void *data);
2078 /*--- Parsing SIP requests and responses */
2079 static void append_date(struct sip_request *req); /* Append date to SIP packet */
2080 static int determine_firstline_parts(struct sip_request *req);
2081 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
2082 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
2083 static int find_sip_method(const char *msg);
2084 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
2085 static int parse_request(struct sip_request *req);
2086 static const char *get_header(const struct sip_request *req, const char *name);
2087 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
2088 static int method_match(enum sipmethod id, const char *name);
2089 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
2090 static char *get_in_brackets(char *tmp);
2091 static const char *find_alias(const char *name, const char *_default);
2092 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
2093 static int lws2sws(char *msgbuf, int len);
2094 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
2095 static char *remove_uri_parameters(char *uri);
2096 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
2097 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
2098 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
2099 static int set_address_from_contact(struct sip_pvt *pvt);
2100 static void check_via(struct sip_pvt *p, struct sip_request *req);
2101 static char *get_calleridname(const char *input, char *output, size_t outputsize);
2102 static int get_rpid_num(const char *input, char *output, int maxlen);
2103 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
2104 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
2105 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
2106 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
2108 /*--- Constructing requests and responses */
2109 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
2110 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
2111 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
2112 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
2113 static int init_resp(struct sip_request *resp, const char *msg);
2114 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
2115 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
2116 static void build_via(struct sip_pvt *p);
2117 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
2118 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin);
2119 static char *generate_random_string(char *buf, size_t size);
2120 static void build_callid_pvt(struct sip_pvt *pvt);
2121 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
2122 static void make_our_tag(char *tagbuf, size_t len);
2123 static int add_header(struct sip_request *req, const char *var, const char *value);
2124 static int add_header_contentLength(struct sip_request *req, int len);
2125 static int add_line(struct sip_request *req, const char *line);
2126 static int add_text(struct sip_request *req, const char *text);
2127 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
2128 static int add_vidupdate(struct sip_request *req);
2129 static void add_route(struct sip_request *req, struct sip_route *route);
2130 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2131 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
2132 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
2133 static void set_destination(struct sip_pvt *p, char *uri);
2134 static void append_date(struct sip_request *req);
2135 static void build_contact(struct sip_pvt *p);
2136 static void build_rpid(struct sip_pvt *p);
2138 /*------Request handling functions */
2139 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
2140 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);
2141 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
2142 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
2143 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
2144 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
2145 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
2146 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2147 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
2148 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
2149 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
2150 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
2151 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
2153 /*------Response handling functions */
2154 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2155 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2156 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2157 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2158 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2160 /*----- RTP interface functions */
2161 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);
2162 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2163 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2164 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2165 static int sip_get_codec(struct ast_channel *chan);
2166 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
2168 /*------ T38 Support --------- */
2169 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite);
2170 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
2171 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
2172 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
2173 static void change_t38_state(struct sip_pvt *p, int state);
2175 /*------ Session-Timers functions --------- */
2176 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
2177 static int proc_session_timer(const void *vp);
2178 static void stop_session_timer(struct sip_pvt *p);
2179 static void start_session_timer(struct sip_pvt *p);
2180 static void restart_session_timer(struct sip_pvt *p);
2181 static const char *strefresher2str(enum st_refresher r);
2182 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
2183 static int parse_minse(const char *p_hdrval, int *const p_interval);
2184 static int st_get_se(struct sip_pvt *, int max);
2185 static enum st_refresher st_get_refresher(struct sip_pvt *);
2186 static enum st_mode st_get_mode(struct sip_pvt *);
2187 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
2190 /*! \brief Definition of this channel for PBX channel registration */
2191 static const struct ast_channel_tech sip_tech = {
2192 .type = "SIP",
2193 .description = "Session Initiation Protocol (SIP)",
2194 .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
2195 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
2196 .requester = sip_request_call, /* called with chan unlocked */
2197 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
2198 .call = sip_call, /* called with chan locked */
2199 .send_html = sip_sendhtml,
2200 .hangup = sip_hangup, /* called with chan locked */
2201 .answer = sip_answer, /* called with chan locked */
2202 .read = sip_read, /* called with chan locked */
2203 .write = sip_write, /* called with chan locked */
2204 .write_video = sip_write, /* called with chan locked */
2205 .write_text = sip_write,
2206 .indicate = sip_indicate, /* called with chan locked */
2207 .transfer = sip_transfer, /* called with chan locked */
2208 .fixup = sip_fixup, /* called with chan locked */
2209 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
2210 .send_digit_end = sip_senddigit_end,
2211 .bridge = ast_rtp_bridge, /* XXX chan unlocked ? */
2212 .early_bridge = ast_rtp_early_bridge,
2213 .send_text = sip_sendtext, /* called with chan locked */
2214 .func_channel_read = acf_channel_read,
2215 .queryoption = sip_queryoption,
2216 .get_pvt_uniqueid = sip_get_callid,
2219 /*! \brief This version of the sip channel tech has no send_digit_begin
2220 * callback so that the core knows that the channel does not want
2221 * DTMF BEGIN frames.
2222 * The struct is initialized just before registering the channel driver,
2223 * and is for use with channels using SIP INFO DTMF.
2225 static struct ast_channel_tech sip_tech_info;
2227 static void *sip_tcp_worker_fn(void *);
2229 static struct ast_tls_config sip_tls_cfg;
2230 static struct ast_tls_config default_tls_cfg;
2232 static struct server_args sip_tcp_desc = {
2233 .accept_fd = -1,
2234 .master = AST_PTHREADT_NULL,
2235 .tls_cfg = NULL,
2236 .poll_timeout = -1,
2237 .name = "sip tcp server",
2238 .accept_fn = ast_tcptls_server_root,
2239 .worker_fn = sip_tcp_worker_fn,
2242 static struct server_args sip_tls_desc = {
2243 .accept_fd = -1,
2244 .master = AST_PTHREADT_NULL,
2245 .tls_cfg = &sip_tls_cfg,
2246 .poll_timeout = -1,
2247 .name = "sip tls server",
2248 .accept_fn = ast_tcptls_server_root,
2249 .worker_fn = sip_tcp_worker_fn,
2252 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
2253 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
2255 /*! \brief map from an integer value to a string.
2256 * If no match is found, return errorstring
2258 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2260 const struct _map_x_s *cur;
2262 for (cur = table; cur->s; cur++)
2263 if (cur->x == x)
2264 return cur->s;
2265 return errorstring;
2268 /*! \brief map from a string to an integer value, case insensitive.
2269 * If no match is found, return errorvalue.
2271 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2273 const struct _map_x_s *cur;
2275 for (cur = table; cur->s; cur++)
2276 if (!strcasecmp(cur->s, s))
2277 return cur->x;
2278 return errorvalue;
2282 /*! \brief Interface structure with callbacks used to connect to RTP module */
2283 static struct ast_rtp_protocol sip_rtp = {
2284 .type = "SIP",
2285 .get_rtp_info = sip_get_rtp_peer,
2286 .get_vrtp_info = sip_get_vrtp_peer,
2287 .get_trtp_info = sip_get_trtp_peer,
2288 .set_rtp_peer = sip_set_rtp_peer,
2289 .get_codec = sip_get_codec,
2292 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser);
2294 static void *sip_tcp_worker_fn(void *data)
2296 struct ast_tcptls_session_instance *ser = data;
2298 return _sip_tcp_helper_thread(NULL, ser);
2301 /*! \brief SIP TCP helper function */
2302 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser)
2304 int res, cl;
2305 struct sip_request req = { 0, } , reqcpy = { 0, };
2306 struct sip_threadinfo *me;
2307 char buf[1024] = "";
2309 me = ast_calloc(1, sizeof(*me));
2311 if (!me)
2312 goto cleanup2;
2314 me->threadid = pthread_self();
2315 me->ser = ser;
2316 if (ser->ssl)
2317 me->type = SIP_TRANSPORT_TLS;
2318 else
2319 me->type = SIP_TRANSPORT_TCP;
2321 AST_LIST_LOCK(&threadl);
2322 AST_LIST_INSERT_TAIL(&threadl, me, list);
2323 AST_LIST_UNLOCK(&threadl);
2325 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2326 goto cleanup;
2327 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2328 goto cleanup;
2330 for (;;) {
2331 ast_str_reset(req.data);
2332 ast_str_reset(reqcpy.data);
2333 req.len = 0;
2334 req.ignore = 0;
2335 req.debug = 0;
2337 req.socket.fd = ser->fd;
2338 if (ser->ssl) {
2339 req.socket.type = SIP_TRANSPORT_TLS;
2340 req.socket.port = htons(ourport_tls);
2341 } else {
2342 req.socket.type = SIP_TRANSPORT_TCP;
2343 req.socket.port = htons(ourport_tcp);
2345 res = ast_wait_for_input(ser->fd, -1);
2346 if (res < 0) {
2347 ast_debug(1, "ast_wait_for_input returned %d\n", res);
2348 goto cleanup;
2351 /* Read in headers one line at a time */
2352 while (req.len < 4 || strncmp((char *)&req.data->str + req.len - 4, "\r\n\r\n", 4)) {
2353 ast_mutex_lock(&ser->lock);
2354 if (!fgets(buf, sizeof(buf), ser->f)) {
2355 ast_mutex_unlock(&ser->lock);
2356 goto cleanup;
2358 ast_mutex_unlock(&ser->lock);
2359 if (me->stop)
2360 goto cleanup;
2361 ast_str_append(&req.data, 0, "%s", buf);
2362 req.len = req.data->used;
2364 copy_request(&reqcpy, &req);
2365 parse_request(&reqcpy);
2366 if (sscanf(get_header(&reqcpy, "Content-Length"), "%d", &cl)) {
2367 while (cl > 0) {
2368 ast_mutex_lock(&ser->lock);
2369 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, ser->f)) {
2370 ast_mutex_unlock(&ser->lock);
2371 goto cleanup;
2373 ast_mutex_unlock(&ser->lock);
2374 if (me->stop)
2375 goto cleanup;
2376 cl -= strlen(buf);
2377 ast_str_append(&req.data, 0, "%s", buf);
2378 req.len = req.data->used;
2381 req.socket.ser = ser;
2382 handle_request_do(&req, &ser->requestor);
2385 cleanup:
2386 AST_LIST_LOCK(&threadl);
2387 AST_LIST_REMOVE(&threadl, me, list);
2388 AST_LIST_UNLOCK(&threadl);
2389 ast_free(me);
2390 cleanup2:
2391 fclose(ser->f);
2392 ser->f = NULL;
2393 ser->fd = -1;
2394 if (reqcpy.data)
2395 ast_free(reqcpy.data);
2396 if (req.data) {
2397 ast_free(req.data);
2398 req.data = NULL;
2402 ao2_ref(ser, -1);
2403 ser = NULL;
2405 return NULL;
2408 #define sip_pvt_lock(x) ao2_lock(x)
2409 #define sip_pvt_trylock(x) ao2_trylock(x)
2410 #define sip_pvt_unlock(x) ao2_unlock(x)
2413 * helper functions to unreference various types of objects.
2414 * By handling them this way, we don't have to declare the
2415 * destructor on each call, which removes the chance of errors.
2417 static void *unref_peer(struct sip_peer *peer, char *tag)
2419 ao2_t_ref(peer, -1, tag);
2420 return NULL;
2423 static void *unref_user(struct sip_user *user, char *tag)
2425 ao2_t_ref(user, -1, tag);
2426 return NULL;
2429 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2431 ao2_t_ref(peer, 1,tag);
2432 return peer;
2436 * \brief Unlink a dialog from the dialogs container, as well as any other places
2437 * that it may be currently stored.
2439 * \note A reference to the dialog must be held before calling this function, and this
2440 * function does not release that reference.
2442 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2444 struct sip_pkt *cp;
2446 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
2448 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2450 /* Unlink us from the owner (channel) if we have one */
2451 if (dialog->owner) {
2452 if (lockowner)
2453 ast_channel_lock(dialog->owner);
2454 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2455 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2456 if (lockowner)
2457 ast_channel_unlock(dialog->owner);
2459 if (dialog->registry) {
2460 if (dialog->registry->call == dialog)
2461 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2462 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2464 if (dialog->stateid > -1) {
2465 ast_extension_state_del(dialog->stateid, NULL);
2466 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2467 dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2469 /* Remove link from peer to subscription of MWI */
2470 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2471 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2472 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2473 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2475 /* remove all current packets in this dialog */
2476 while((cp = dialog->packets)) {
2477 dialog->packets = dialog->packets->next;
2478 AST_SCHED_DEL(sched, cp->retransid);
2479 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2480 ast_free(cp);
2483 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"));
2485 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"));
2487 if (dialog->autokillid > -1)
2488 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"));
2490 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2491 return NULL;
2494 static void *registry_unref(struct sip_registry *reg, char *tag)
2496 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2497 ASTOBJ_UNREF(reg, sip_registry_destroy);
2498 return NULL;
2501 /*! \brief Add object reference to SIP registry */
2502 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2504 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2505 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2508 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2509 static struct ast_udptl_protocol sip_udptl = {
2510 type: "SIP",
2511 get_udptl_info: sip_get_udptl_peer,
2512 set_udptl_peer: sip_set_udptl_peer,
2515 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2516 __attribute__ ((format (printf, 2, 3)));
2519 /*! \brief Convert transfer status to string */
2520 static const char *referstatus2str(enum referstatus rstatus)
2522 return map_x_s(referstatusstrings, rstatus, "");
2525 /*! \brief Initialize the initital request packet in the pvt structure.
2526 This packet is used for creating replies and future requests in
2527 a dialog */
2528 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2530 if (p->initreq.headers)
2531 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2532 else
2533 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2534 /* Use this as the basis */
2535 copy_request(&p->initreq, req);
2536 parse_request(&p->initreq);
2537 if (req->debug)
2538 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2541 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2542 static void sip_alreadygone(struct sip_pvt *dialog)
2544 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2545 dialog->alreadygone = 1;
2548 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2549 static int proxy_update(struct sip_proxy *proxy)
2551 /* if it's actually an IP address and not a name,
2552 there's no need for a managed lookup */
2553 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2554 /* Ok, not an IP address, then let's check if it's a domain or host */
2555 /* XXX Todo - if we have proxy port, don't do SRV */
2556 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
2557 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2558 return FALSE;
2561 proxy->last_dnsupdate = time(NULL);
2562 return TRUE;
2565 /*! \brief Allocate and initialize sip proxy */
2566 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2568 struct sip_proxy *proxy;
2569 proxy = ast_calloc(1, sizeof(*proxy));
2570 if (!proxy)
2571 return NULL;
2572 proxy->force = force;
2573 ast_copy_string(proxy->name, name, sizeof(proxy->name));
2574 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2575 proxy_update(proxy);
2576 return proxy;
2579 /*! \brief Get default outbound proxy or global proxy */
2580 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2582 if (peer && peer->outboundproxy) {
2583 if (sipdebug)
2584 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2585 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2586 return peer->outboundproxy;
2588 if (global_outboundproxy.name[0]) {
2589 if (sipdebug)
2590 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2591 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2592 return &global_outboundproxy;
2594 if (sipdebug)
2595 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2596 return NULL;
2599 /*! \brief returns true if 'name' (with optional trailing whitespace)
2600 * matches the sip method 'id'.
2601 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2602 * a case-insensitive comparison to be more tolerant.
2603 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2605 static int method_match(enum sipmethod id, const char *name)
2607 int len = strlen(sip_methods[id].text);
2608 int l_name = name ? strlen(name) : 0;
2609 /* true if the string is long enough, and ends with whitespace, and matches */
2610 return (l_name >= len && name[len] < 33 &&
2611 !strncasecmp(sip_methods[id].text, name, len));
2614 /*! \brief find_sip_method: Find SIP method from header */
2615 static int find_sip_method(const char *msg)
2617 int i, res = 0;
2619 if (ast_strlen_zero(msg))
2620 return 0;
2621 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
2622 if (method_match(i, msg))
2623 res = sip_methods[i].id;
2625 return res;
2628 /*! \brief Parse supported header in incoming packet */
2629 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2631 char *next, *sep;
2632 char *temp;
2633 unsigned int profile = 0;
2634 int i, found;
2636 if (ast_strlen_zero(supported) )
2637 return 0;
2638 temp = ast_strdupa(supported);
2640 if (sipdebug)
2641 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2643 for (next = temp; next; next = sep) {
2644 found = FALSE;
2645 if ( (sep = strchr(next, ',')) != NULL)
2646 *sep++ = '\0';
2647 next = ast_skip_blanks(next);
2648 if (sipdebug)
2649 ast_debug(3, "Found SIP option: -%s-\n", next);
2650 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
2651 if (!strcasecmp(next, sip_options[i].text)) {
2652 profile |= sip_options[i].id;
2653 found = TRUE;
2654 if (sipdebug)
2655 ast_debug(3, "Matched SIP option: %s\n", next);
2656 break;
2660 /* This function is used to parse both Suported: and Require: headers.
2661 Let the caller of this function know that an unknown option tag was
2662 encountered, so that if the UAC requires it then the request can be
2663 rejected with a 420 response. */
2664 if (!found)
2665 profile |= SIP_OPT_UNKNOWN;
2667 if (!found && sipdebug) {
2668 if (!strncasecmp(next, "x-", 2))
2669 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2670 else
2671 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2675 if (pvt)
2676 pvt->sipoptions = profile;
2677 return profile;
2680 /*! \brief See if we pass debug IP filter */
2681 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2683 if (!sipdebug)
2684 return 0;
2685 if (debugaddr.sin_addr.s_addr) {
2686 if (((ntohs(debugaddr.sin_port) != 0)
2687 && (debugaddr.sin_port != addr->sin_port))
2688 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2689 return 0;
2691 return 1;
2694 /*! \brief The real destination address for a write */
2695 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2697 if (p->outboundproxy)
2698 return &p->outboundproxy->ip;
2700 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2703 /*! \brief Display SIP nat mode */
2704 static const char *sip_nat_mode(const struct sip_pvt *p)
2706 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2709 /*! \brief Test PVT for debugging output */
2710 static inline int sip_debug_test_pvt(struct sip_pvt *p)
2712 if (!sipdebug)
2713 return 0;
2714 return sip_debug_test_addr(sip_real_dst(p));
2717 static inline const char *get_transport(enum sip_transport t)
2719 switch (t) {
2720 case SIP_TRANSPORT_UDP:
2721 return "UDP";
2722 case SIP_TRANSPORT_TCP:
2723 return "TCP";
2724 case SIP_TRANSPORT_TLS:
2725 return "TLS";
2728 return "UNKNOWN";
2731 /*! \brief Transmit SIP message
2732 Sends a SIP request or response on a given socket (in the pvt)
2733 Called by retrans_pkt, send_request, send_response and
2734 __sip_reliable_xmit
2736 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2738 int res = 0;
2739 const struct sockaddr_in *dst = sip_real_dst(p);
2741 ast_debug(1, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport(p->socket.type), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
2743 if (sip_prepare_socket(p) < 0)
2744 return XMIT_ERROR;
2746 if (p->socket.ser)
2747 ast_mutex_lock(&p->socket.ser->lock);
2749 if (p->socket.type & SIP_TRANSPORT_UDP)
2750 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2751 else {
2752 if (p->socket.ser->f)
2753 res = ast_tcptls_server_write(p->socket.ser, data->str, len);
2754 else
2755 ast_debug(1, "No p->socket.ser->f len=%d\n", len);
2758 if (p->socket.ser)
2759 ast_mutex_unlock(&p->socket.ser->lock);
2761 if (res == -1) {
2762 switch (errno) {
2763 case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2764 case EHOSTUNREACH: /* Host can't be reached */
2765 case ENETDOWN: /* Inteface down */
2766 case ENETUNREACH: /* Network failure */
2767 case ECONNREFUSED: /* ICMP port unreachable */
2768 res = XMIT_ERROR; /* Don't bother with trying to transmit again */
2771 if (res != len)
2772 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));
2774 return res;
2777 /*! \brief Build a Via header for a request */
2778 static void build_via(struct sip_pvt *p)
2780 /* Work around buggy UNIDEN UIP200 firmware */
2781 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2783 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2784 ast_string_field_build(p, via, "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
2785 get_transport(p->socket.type),
2786 ast_inet_ntoa(p->ourip.sin_addr),
2787 ntohs(p->ourip.sin_port), p->branch, rport);
2790 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2792 * Using the localaddr structure built up with localnet statements in sip.conf
2793 * apply it to their address to see if we need to substitute our
2794 * externip or can get away with our internal bindaddr
2795 * 'us' is always overwritten.
2797 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2799 struct sockaddr_in theirs;
2800 /* Set want_remap to non-zero if we want to remap 'us' to an externally
2801 * reachable IP address and port. This is done if:
2802 * 1. we have a localaddr list (containing 'internal' addresses marked
2803 * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2804 * and AST_SENSE_ALLOW on 'external' ones);
2805 * 2. either stunaddr or externip is set, so we know what to use as the
2806 * externally visible address;
2807 * 3. the remote address, 'them', is external;
2808 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2809 * when passed to ast_apply_ha() so it does need to be remapped.
2810 * This fourth condition is checked later.
2812 int want_remap;
2814 *us = internip; /* starting guess for the internal address */
2815 /* now ask the system what would it use to talk to 'them' */
2816 ast_ouraddrfor(them, &us->sin_addr);
2817 theirs.sin_addr = *them;
2819 want_remap = localaddr &&
2820 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2821 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2823 if (want_remap &&
2824 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2825 /* if we used externhost or stun, see if it is time to refresh the info */
2826 if (externexpire && time(NULL) >= externexpire) {
2827 if (stunaddr.sin_addr.s_addr) {
2828 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2829 } else {
2830 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2831 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2833 externexpire = time(NULL) + externrefresh;
2835 if (externip.sin_addr.s_addr)
2836 *us = externip;
2837 else
2838 ast_log(LOG_WARNING, "stun failed\n");
2839 ast_debug(1, "Target address %s is not local, substituting externip\n",
2840 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2841 } else if (bindaddr.sin_addr.s_addr) {
2842 /* no remapping, but we bind to a specific address, so use it. */
2843 *us = bindaddr;
2847 /*! \brief Append to SIP dialog history with arg list */
2848 static __attribute__((format (printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2850 char buf[80], *c = buf; /* max history length */
2851 struct sip_history *hist;
2852 int l;
2854 vsnprintf(buf, sizeof(buf), fmt, ap);
2855 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2856 l = strlen(buf) + 1;
2857 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2858 return;
2859 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2860 ast_free(hist);
2861 return;
2863 memcpy(hist->event, buf, l);
2864 if (p->history_entries == MAX_HISTORY_ENTRIES) {
2865 struct sip_history *oldest;
2866 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2867 p->history_entries--;
2868 ast_free(oldest);
2870 AST_LIST_INSERT_TAIL(p->history, hist, list);
2871 p->history_entries++;
2874 /*! \brief Append to SIP dialog history with arg list */
2875 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2877 va_list ap;
2879 if (!p)
2880 return;
2882 if (!p->do_history && !recordhistory && !dumphistory)
2883 return;
2885 va_start(ap, fmt);
2886 append_history_va(p, fmt, ap);
2887 va_end(ap);
2889 return;
2892 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2893 static int retrans_pkt(const void *data)
2895 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2896 int reschedule = DEFAULT_RETRANS;
2897 int xmitres = 0;
2899 /* Lock channel PVT */
2900 sip_pvt_lock(pkt->owner);
2902 if (pkt->retrans < MAX_RETRANS) {
2903 pkt->retrans++;
2904 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
2905 if (sipdebug)
2906 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);
2907 } else {
2908 int siptimer_a;
2910 if (sipdebug)
2911 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2912 if (!pkt->timer_a)
2913 pkt->timer_a = 2 ;
2914 else
2915 pkt->timer_a = 2 * pkt->timer_a;
2917 /* For non-invites, a maximum of 4 secs */
2918 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
2919 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2920 siptimer_a = 4000;
2922 /* Reschedule re-transmit */
2923 reschedule = siptimer_a;
2924 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);
2927 if (sip_debug_test_pvt(pkt->owner)) {
2928 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2929 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2930 pkt->retrans, sip_nat_mode(pkt->owner),
2931 ast_inet_ntoa(dst->sin_addr),
2932 ntohs(dst->sin_port), pkt->data->str);
2935 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
2936 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2937 sip_pvt_unlock(pkt->owner);
2938 if (xmitres == XMIT_ERROR)
2939 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2940 else
2941 return reschedule;
2943 /* Too many retries */
2944 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2945 if (pkt->is_fatal || sipdebug) /* Tell us if it's critical or if we're debugging */
2946 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n",
2947 pkt->owner->callid, pkt->seqno,
2948 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2949 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2950 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2953 if (xmitres == XMIT_ERROR) {
2954 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2955 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2956 } else
2957 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2959 pkt->retransid = -1;
2961 if (pkt->is_fatal) {
2962 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2963 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
2964 usleep(1);
2965 sip_pvt_lock(pkt->owner);
2968 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
2969 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2971 if (pkt->owner->owner) {
2972 sip_alreadygone(pkt->owner);
2973 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2974 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
2975 ast_channel_unlock(pkt->owner->owner);
2976 } else {
2977 /* If no channel owner, destroy now */
2979 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2980 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2981 pkt->owner->needdestroy = 1;
2982 sip_alreadygone(pkt->owner);
2983 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2988 if (pkt->method == SIP_BYE) {
2989 /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
2990 if (pkt->owner->owner)
2991 ast_channel_unlock(pkt->owner->owner);
2992 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2993 pkt->owner->needdestroy = 1;
2996 /* Remove the packet */
2997 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2998 if (cur == pkt) {
2999 UNLINK(cur, pkt->owner->packets, prev);
3000 sip_pvt_unlock(pkt->owner);
3001 if (pkt->owner)
3002 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3003 if (pkt->data)
3004 ast_free(pkt->data);
3005 pkt->data = NULL;
3006 ast_free(pkt);
3007 return 0;
3010 /* error case */
3011 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3012 sip_pvt_unlock(pkt->owner);
3013 return 0;
3016 /*! \brief Transmit packet with retransmits
3017 \return 0 on success, -1 on failure to allocate packet
3019 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)
3021 struct sip_pkt *pkt = NULL;
3022 int siptimer_a = DEFAULT_RETRANS;
3023 int xmitres = 0;
3025 if (sipmethod == SIP_INVITE) {
3026 /* Note this is a pending invite */
3027 p->pendinginvite = seqno;
3030 /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3031 /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3032 /* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3033 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3034 xmitres = __sip_xmit(dialog_ref(p, "pasing dialog ptr into callback..."), data, len); /* Send packet */
3035 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3036 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3037 return AST_FAILURE;
3038 } else
3039 return AST_SUCCESS;
3042 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3043 return AST_FAILURE;
3044 /* copy data, add a terminator and save length */
3045 if (!(pkt->data = ast_str_create(len))) {
3046 ast_free(pkt);
3047 return AST_FAILURE;
3049 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3050 pkt->packetlen = len;
3051 /* copy other parameters from the caller */
3052 pkt->method = sipmethod;
3053 pkt->seqno = seqno;
3054 pkt->is_resp = resp;
3055 pkt->is_fatal = fatal;
3056 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3057 pkt->next = p->packets;
3058 p->packets = pkt; /* Add it to the queue */
3059 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
3060 pkt->retransid = -1;
3061 if (pkt->timer_t1)
3062 siptimer_a = pkt->timer_t1 * 2;
3064 /* Schedule retransmission */
3065 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3066 if (sipdebug)
3067 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
3069 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
3071 if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
3072 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3073 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3074 if (pkt->data)
3075 ast_free(pkt->data);
3076 return AST_FAILURE;
3077 } else {
3078 return AST_SUCCESS;
3082 /*! \brief Kill a SIP dialog (called only by the scheduler)
3083 * The scheduler has a reference to this dialog when p->autokillid != -1,
3084 * and we are called using that reference. So if the event is not
3085 * rescheduled, we need to call dialog_unref().
3087 static int __sip_autodestruct(const void *data)
3089 struct sip_pvt *p = (struct sip_pvt *)data;
3091 /* If this is a subscription, tell the phone that we got a timeout */
3092 if (p->subscribed) {
3093 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */
3094 p->subscribed = NONE;
3095 append_history(p, "Subscribestatus", "timeout");
3096 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3097 return 10000; /* Reschedule this destruction so that we know that it's gone */
3100 /* If there are packets still waiting for delivery, delay the destruction */
3101 if (p->packets) {
3102 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3103 append_history(p, "ReliableXmit", "timeout");
3104 return 10000;
3107 if (p->subscribed == MWI_NOTIFICATION)
3108 if (p->relatedpeer)
3109 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) */
3111 /* Reset schedule ID */
3112 p->autokillid = -1;
3114 if (p->owner) {
3115 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3116 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3117 } else if (p->refer && !p->alreadygone) {
3118 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3119 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3120 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3121 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3122 } else {
3123 append_history(p, "AutoDestroy", "%s", p->callid);
3124 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3125 dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3126 /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3127 /* sip_destroy(p); */ /* Go ahead and destroy dialog. All attempts to recover is done */
3128 /* sip_destroy also absorbs the reference */
3130 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3131 return 0;
3134 /*! \brief Schedule destruction of SIP dialog */
3135 static void sip_scheddestroy(struct sip_pvt *p, int ms)
3137 if (ms < 0) {
3138 if (p->timer_t1 == 0) {
3139 p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
3140 p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
3142 ms = p->timer_t1 * 64;
3144 if (sip_debug_test_pvt(p))
3145 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3146 if (sip_cancel_destroy(p))
3147 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
3149 if (p->do_history)
3150 append_history(p, "SchedDestroy", "%d ms", ms);
3151 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3153 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
3154 stop_session_timer(p);
3157 /*! \brief Cancel destruction of SIP dialog.
3158 * Be careful as this also absorbs the reference - if you call it
3159 * from within the scheduler, this might be the last reference.
3161 static int sip_cancel_destroy(struct sip_pvt *p)
3163 int res = 0;
3164 if (p->autokillid > -1) {
3165 int res3;
3167 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3168 append_history(p, "CancelDestroy", "");
3169 p->autokillid = -1;
3170 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3173 return res;
3176 /*! \brief Acknowledges receipt of a packet and stops retransmission
3177 * called with p locked*/
3178 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3180 struct sip_pkt *cur, *prev = NULL;
3181 const char *msg = "Not Found"; /* used only for debugging */
3183 /* If we have an outbound proxy for this dialog, then delete it now since
3184 the rest of the requests in this dialog needs to follow the routing.
3185 If obforcing is set, we will keep the outbound proxy during the whole
3186 dialog, regardless of what the SIP rfc says
3188 if (p->outboundproxy && !p->outboundproxy->force)
3189 p->outboundproxy = NULL;
3191 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3192 if (cur->seqno != seqno || cur->is_resp != resp)
3193 continue;
3194 if (cur->is_resp || cur->method == sipmethod) {
3195 msg = "Found";
3196 if (!resp && (seqno == p->pendinginvite)) {
3197 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3198 p->pendinginvite = 0;
3200 if (cur->retransid > -1) {
3201 if (sipdebug)
3202 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3204 /* This odd section is designed to thwart a
3205 * race condition in the packet scheduler. There are
3206 * two conditions under which deleting the packet from the
3207 * scheduler can fail.
3209 * 1. The packet has been removed from the scheduler because retransmission
3210 * is being attempted. The problem is that if the packet is currently attempting
3211 * retransmission and we are at this point in the code, then that MUST mean
3212 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3213 * lock temporarily to allow retransmission.
3215 * 2. The packet has reached its maximum number of retransmissions and has
3216 * been permanently removed from the packet scheduler. If this is the case, then
3217 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3218 * of the retransid to -1 is ensured since in both cases p's lock is held.
3220 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3221 sip_pvt_unlock(p);
3222 usleep(1);
3223 sip_pvt_lock(p);
3225 UNLINK(cur, p->packets, prev);
3226 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3227 if (cur->data)
3228 ast_free(cur->data);
3229 ast_free(cur);
3230 break;
3233 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3234 p->callid, resp ? "Response" : "Request", seqno, msg);
3237 /*! \brief Pretend to ack all packets
3238 * called with p locked */
3239 static void __sip_pretend_ack(struct sip_pvt *p)
3241 struct sip_pkt *cur = NULL;
3243 while (p->packets) {
3244 int method;
3245 if (cur == p->packets) {
3246 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
3247 return;
3249 cur = p->packets;
3250 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
3251 __sip_ack(p, cur->seqno, cur->is_resp, method);
3255 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
3256 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3258 struct sip_pkt *cur;
3259 int res = -1;
3261 for (cur = p->packets; cur; cur = cur->next) {
3262 if (cur->seqno == seqno && cur->is_resp == resp &&
3263 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
3264 /* this is our baby */
3265 if (cur->retransid > -1) {
3266 if (sipdebug)
3267 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
3269 AST_SCHED_DEL(sched, cur->retransid);
3270 res = 0;
3271 break;
3274 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");
3275 return res;
3279 /*! \brief Copy SIP request, parse it */
3280 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3282 copy_request(dst, src);
3283 parse_request(dst);
3286 /*! \brief add a blank line if no body */
3287 static void add_blank(struct sip_request *req)
3289 if (!req->lines) {
3290 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3291 ast_str_append(&req->data, 0, "\r\n");
3292 req->len = req->data->used;
3296 /*! \brief Transmit response on SIP request*/
3297 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3299 int res;
3301 add_blank(req);
3302 if (sip_debug_test_pvt(p)) {
3303 const struct sockaddr_in *dst = sip_real_dst(p);
3305 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
3306 reliable ? "Reliably " : "", sip_nat_mode(p),
3307 ast_inet_ntoa(dst->sin_addr),
3308 ntohs(dst->sin_port), req->data->str);
3310 if (p->do_history) {
3311 struct sip_request tmp = { .rlPart1 = NULL, };
3312 parse_copy(&tmp, req);
3313 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
3314 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
3315 ast_free(tmp.data);
3317 res = (reliable) ?
3318 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3319 __sip_xmit(p, req->data, req->len);
3320 ast_free(req->data);
3321 req->data = NULL;
3322 if (res > 0)
3323 return 0;
3324 return res;
3327 /*! \brief Send SIP Request to the other part of the dialogue */
3328 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3330 int res;
3332 /* If we have an outbound proxy, reset peer address
3333 Only do this once.
3335 if (p->outboundproxy) {
3336 p->sa = p->outboundproxy->ip;
3339 add_blank(req);
3340 if (sip_debug_test_pvt(p)) {
3341 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
3342 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);
3343 else
3344 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);
3346 if (p->do_history) {
3347 struct sip_request tmp = { .rlPart1 = NULL, };
3348 parse_copy(&tmp, req);
3349 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3350 ast_free(tmp.data);
3352 res = (reliable) ?
3353 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3354 __sip_xmit(p, req->data, req->len);
3355 if (req->data) {
3356 ast_free(req->data);
3357 req->data = NULL;
3359 return res;
3362 /*! \brief Query an option on a SIP dialog */
3363 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3365 int res = -1;
3366 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
3367 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
3369 switch (option) {
3370 case AST_OPTION_T38_STATE:
3371 /* Make sure we got an ast_t38_state enum passed in */
3372 if (*datalen != sizeof(enum ast_t38_state)) {
3373 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
3374 return -1;
3377 sip_pvt_lock(p);
3379 /* 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 */
3380 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT)) {
3381 switch (p->t38.state) {
3382 case T38_LOCAL_DIRECT:
3383 case T38_LOCAL_REINVITE:
3384 case T38_PEER_DIRECT:
3385 case T38_PEER_REINVITE:
3386 state = T38_STATE_NEGOTIATING;
3387 break;
3388 case T38_ENABLED:
3389 state = T38_STATE_NEGOTIATED;
3390 break;
3391 default:
3392 state = T38_STATE_UNKNOWN;
3396 sip_pvt_unlock(p);
3398 *((enum ast_t38_state *) data) = state;
3399 res = 0;
3401 break;
3402 default:
3403 break;
3406 return res;
3409 /*! \brief Locate closing quote in a string, skipping escaped quotes.
3410 * optionally with a limit on the search.
3411 * start must be past the first quote.
3413 static const char *find_closing_quote(const char *start, const char *lim)
3415 char last_char = '\0';
3416 const char *s;
3417 for (s = start; *s && s != lim; last_char = *s++) {
3418 if (*s == '"' && last_char != '\\')
3419 break;
3421 return s;
3424 /*! \brief Pick out text in brackets from character string
3425 \return pointer to terminated stripped string
3426 \param tmp input string that will be modified
3427 Examples:
3428 \verbatim
3429 "foo" <bar> valid input, returns bar
3430 foo returns the whole string
3431 < "foo ... > returns the string between brackets
3432 < "foo... bogus (missing closing bracket), returns the whole string
3433 XXX maybe should still skip the opening bracket
3434 \endverbatim
3436 static char *get_in_brackets(char *tmp)
3438 const char *parse = tmp;
3439 char *first_bracket;
3442 * Skip any quoted text until we find the part in brackets.
3443 * On any error give up and return the full string.
3445 while ( (first_bracket = strchr(parse, '<')) ) {
3446 char *first_quote = strchr(parse, '"');
3448 if (!first_quote || first_quote > first_bracket)
3449 break; /* no need to look at quoted part */
3450 /* the bracket is within quotes, so ignore it */
3451 parse = find_closing_quote(first_quote + 1, NULL);
3452 if (!*parse) { /* not found, return full string ? */
3453 /* XXX or be robust and return in-bracket part ? */
3454 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
3455 break;
3457 parse++;
3459 if (first_bracket) {
3460 char *second_bracket = strchr(first_bracket + 1, '>');
3461 if (second_bracket) {
3462 *second_bracket = '\0';
3463 tmp = first_bracket + 1;
3464 } else {
3465 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
3469 return tmp;
3472 /*! \brief * parses a URI in its components.
3474 * \note
3475 * - If scheme is specified, drop it from the top.
3476 * - If a component is not requested, do not split around it.
3478 * This means that if we don't have domain, we cannot split
3479 * name:pass and domain:port.
3480 * It is safe to call with ret_name, pass, domain, port
3481 * pointing all to the same place.
3482 * Init pointers to empty string so we never get NULL dereferencing.
3483 * Overwrites the string.
3484 * return 0 on success, other values on error.
3485 * \verbatim
3486 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
3487 * \endverbatim
3489 static int parse_uri(char *uri, char *scheme,
3490 char **ret_name, char **pass, char **domain, char **port, char **options)
3492 char *name = NULL;
3493 int error = 0;
3495 /* init field as required */
3496 if (pass)
3497 *pass = "";
3498 if (port)
3499 *port = "";
3500 if (scheme) {
3501 int l = strlen(scheme);
3502 if (!strncasecmp(uri, scheme, l))
3503 uri += l;
3504 else {
3505 ast_debug(1, "Missing scheme '%s' in '%s'\n", scheme, uri);
3506 error = -1;
3509 if (!domain) {
3510 /* if we don't want to split around domain, keep everything as a name,
3511 * so we need to do nothing here, except remember why.
3513 } else {
3514 /* store the result in a temp. variable to avoid it being
3515 * overwritten if arguments point to the same place.
3517 char *c, *dom = "";
3519 if ((c = strchr(uri, '@')) == NULL) {
3520 /* domain-only URI, according to the SIP RFC. */
3521 dom = uri;
3522 name = "";
3523 } else {
3524 *c++ = '\0';
3525 dom = c;
3526 name = uri;
3529 /* Remove options in domain and name */
3530 dom = strsep(&dom, ";");
3531 name = strsep(&name, ";");
3533 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
3534 *c++ = '\0';
3535 *port = c;
3537 if (pass && (c = strchr(name, ':'))) { /* user:password */
3538 *c++ = '\0';
3539 *pass = c;
3541 *domain = dom;
3543 if (ret_name) /* same as for domain, store the result only at the end */
3544 *ret_name = name;
3545 if (options)
3546 *options = uri ? uri : "";
3548 return error;
3551 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
3552 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3554 struct sip_pvt *p = chan->tech_pvt;
3556 if (subclass != AST_HTML_URL)
3557 return -1;
3559 ast_string_field_build(p, url, "<%s>;mode=active", data);
3561 if (sip_debug_test_pvt(p))
3562 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
3564 switch (chan->_state) {
3565 case AST_STATE_RING:
3566 transmit_response(p, "100 Trying", &p->initreq);
3567 break;
3568 case AST_STATE_RINGING:
3569 transmit_response(p, "180 Ringing", &p->initreq);
3570 break;
3571 case AST_STATE_UP:
3572 if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
3573 transmit_reinvite_with_sdp(p, FALSE, FALSE);
3574 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
3575 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
3577 break;
3578 default:
3579 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
3582 return 0;
3585 /*! \brief Deliver SIP call ID for the call */
3586 static const char *sip_get_callid(struct ast_channel *chan)
3588 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
3591 /*! \brief Send SIP MESSAGE text within a call
3592 Called from PBX core sendtext() application */
3593 static int sip_sendtext(struct ast_channel *ast, const char *text)
3595 struct sip_pvt *p = ast->tech_pvt;
3596 int debug = sip_debug_test_pvt(p);
3598 if (debug)
3599 ast_verbose("Sending text %s on %s\n", text, ast->name);
3600 if (!p)
3601 return -1;
3602 if (ast_strlen_zero(text))
3603 return 0;
3604 if (debug)
3605 ast_verbose("Really sending text %s on %s\n", text, ast->name);
3606 transmit_message_with_text(p, text);
3607 return 0;
3610 /*! \brief Update peer object in realtime storage
3611 If the Asterisk system name is set in asterisk.conf, we will use
3612 that name and store that in the "regserver" field in the sippeers
3613 table to facilitate multi-server setups.
3615 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)
3617 char port[10];
3618 char ipaddr[INET_ADDRSTRLEN];
3619 char regseconds[20];
3620 char *tablename = NULL;
3622 const char *sysname = ast_config_AST_SYSTEM_NAME;
3623 char *syslabel = NULL;
3625 time_t nowtime = time(NULL) + expirey;
3626 const char *fc = fullcontact ? "fullcontact" : NULL;
3628 int realtimeregs = ast_check_realtime("sipregs");
3630 tablename = realtimeregs ? "sipregs" : "sippeers";
3632 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
3633 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3634 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3636 if (ast_strlen_zero(sysname)) /* No system name, disable this */
3637 sysname = NULL;
3638 else if (sip_cfg.rtsave_sysname)
3639 syslabel = "regserver";
3641 if (fc) {
3642 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3643 "port", port, "regseconds", regseconds,
3644 deprecated_username ? "username" : "defaultuser", defaultuser,
3645 "useragent", useragent,
3646 fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
3647 } else {
3648 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3649 "port", port, "regseconds", regseconds,
3650 "useragent", useragent,
3651 deprecated_username ? "username" : "defaultuser", defaultuser,
3652 syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
3656 /*! \brief Automatically add peer extension to dial plan */
3657 static void register_peer_exten(struct sip_peer *peer, int onoff)
3659 char multi[256];
3660 char *stringp, *ext, *context;
3661 struct pbx_find_info q = { .stacklen = 0 };
3663 /* XXX note that global_regcontext is both a global 'enable' flag and
3664 * the name of the global regexten context, if not specified
3665 * individually.
3667 if (ast_strlen_zero(global_regcontext))
3668 return;
3670 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
3671 stringp = multi;
3672 while ((ext = strsep(&stringp, "&"))) {
3673 if ((context = strchr(ext, '@'))) {
3674 *context++ = '\0'; /* split ext@context */
3675 if (!ast_context_find(context)) {
3676 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
3677 continue;
3679 } else {
3680 context = global_regcontext;
3682 if (onoff) {
3683 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
3684 ast_strdup(peer->name), ast_free_ptr, "SIP");
3685 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
3686 ast_context_remove_extension(context, ext, 1, NULL);
3691 /*! Destroy mailbox subscriptions */
3692 static void destroy_mailbox(struct sip_mailbox *mailbox)
3694 if (mailbox->mailbox)
3695 ast_free(mailbox->mailbox);
3696 if (mailbox->context)
3697 ast_free(mailbox->context);
3698 if (mailbox->event_sub)
3699 ast_event_unsubscribe(mailbox->event_sub);
3700 ast_free(mailbox);
3703 /*! Destroy all peer-related mailbox subscriptions */
3704 static void clear_peer_mailboxes(struct sip_peer *peer)
3706 struct sip_mailbox *mailbox;
3708 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
3709 destroy_mailbox(mailbox);
3712 static void sip_destroy_peer_fn(void *peer)
3714 sip_destroy_peer(peer);
3717 /*! \brief Destroy peer object from memory */
3718 static void sip_destroy_peer(struct sip_peer *peer)
3720 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
3721 if (peer->outboundproxy)
3722 ast_free(peer->outboundproxy);
3723 peer->outboundproxy = NULL;
3725 /* Delete it, it needs to disappear */
3726 if (peer->call) {
3727 dialog_unlink_all(peer->call, TRUE, TRUE);
3728 peer->call = dialog_unref(peer->call, "peer->call is being unset");
3732 if (peer->mwipvt) { /* We have an active subscription, delete it */
3733 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
3734 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
3737 if (peer->chanvars) {
3738 ast_variables_destroy(peer->chanvars);
3739 peer->chanvars = NULL;
3742 /* If the schedule delete fails, that means the schedule is currently
3743 * running, which means we should wait for that thread to complete.
3744 * Otherwise, there's a crashable race condition.
3746 * NOTE: once peer is refcounted, this probably is no longer necessary.
3748 AST_SCHED_DEL(sched, peer->expire);
3749 AST_SCHED_DEL(sched, peer->pokeexpire);
3751 register_peer_exten(peer, FALSE);
3752 ast_free_ha(peer->ha);
3753 if (peer->selfdestruct)
3754 ast_atomic_fetchadd_int(&apeerobjs, -1);
3755 else if (peer->is_realtime) {
3756 ast_atomic_fetchadd_int(&rpeerobjs, -1);
3757 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
3758 } else
3759 ast_atomic_fetchadd_int(&speerobjs, -1);
3760 clear_realm_authentication(peer->auth);
3761 peer->auth = NULL;
3762 if (peer->dnsmgr)
3763 ast_dnsmgr_release(peer->dnsmgr);
3764 clear_peer_mailboxes(peer);
3766 if (peer->socket.ser) {
3767 ao2_ref(peer->socket.ser, -1);
3768 peer->socket.ser = NULL;
3772 /*! \brief Update peer data in database (if used) */
3773 static void update_peer(struct sip_peer *p, int expiry)
3775 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
3776 if (sip_cfg.peer_rtupdate &&
3777 (p->is_realtime || rtcachefriends)) {
3778 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expiry, p->deprecated_username);
3782 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config)
3784 struct ast_variable *var = NULL;
3785 struct ast_flags flags = {0};
3786 char *cat = NULL;
3787 const char *insecure;
3788 while ((cat = ast_category_browse(config, cat))) {
3789 insecure = ast_variable_retrieve(config, cat, "insecure");
3790 set_insecure_flags(&flags, insecure, -1);
3791 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
3792 var = ast_category_root(config, cat);
3793 break;
3796 return var;
3799 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
3801 struct ast_variable *tmp;
3802 for (tmp = var; tmp; tmp = tmp->next) {
3803 if (!newpeername && !strcasecmp(tmp->name, "name"))
3804 newpeername = tmp->value;
3806 return newpeername;
3809 /*! \brief realtime_peer: Get peer from realtime storage
3810 * Checks the "sippeers" realtime family from extconfig.conf
3811 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
3812 * This returns a pointer to a peer and because we use build_peer, we can rest
3813 * assured that the refcount is bumped.
3815 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
3817 struct sip_peer *peer;
3818 struct ast_variable *var = NULL;
3819 struct ast_variable *varregs = NULL;
3820 struct ast_variable *tmp;
3821 struct ast_config *peerlist = NULL;
3822 char ipaddr[INET_ADDRSTRLEN];
3823 char portstring[6]; /*up to 5 digits plus null terminator*/
3824 char *cat = NULL;
3825 unsigned short portnum;
3826 int realtimeregs = ast_check_realtime("sipregs");
3828 /* First check on peer name */
3829 if (newpeername) {
3830 if (realtimeregs)
3831 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3833 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
3834 if (!var && sin)
3835 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3836 if (!var) {
3837 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3838 /*!\note
3839 * If this one loaded something, then we need to ensure that the host
3840 * field matched. The only reason why we can't have this as a criteria
3841 * is because we only have the IP address and the host field might be
3842 * set as a name (and the reverse PTR might not match).
3844 if (var && sin) {
3845 for (tmp = var; tmp; tmp = tmp->next) {
3846 if (!strcasecmp(tmp->name, "host")) {
3847 struct hostent *hp;
3848 struct ast_hostent ahp;
3849 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3850 /* No match */
3851 ast_variables_destroy(var);
3852 var = NULL;
3854 break;
3861 if (!var && sin) { /* Then check on IP address for dynamic peers */
3862 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3863 portnum = ntohs(sin->sin_port);
3864 sprintf(portstring, "%u", portnum);
3865 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, NULL); /* First check for fixed IP hosts */
3866 if (var) {
3867 if (realtimeregs) {
3868 newpeername = get_name_from_variable(var, newpeername);
3869 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3871 } else {
3872 if (realtimeregs)
3873 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
3874 else
3875 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
3876 if (varregs) {
3877 newpeername = get_name_from_variable(varregs, newpeername);
3878 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3881 if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
3882 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, NULL);
3883 if (peerlist) {
3884 var = get_insecure_variable_from_config(peerlist);
3885 if(var) {
3886 if (realtimeregs) {
3887 newpeername = get_name_from_variable(var, newpeername);
3888 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3890 } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
3891 peerlist = NULL;
3892 cat = NULL;
3893 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
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, NULL);
3904 } else {
3905 if (realtimeregs) {
3906 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, NULL);
3907 if (peerlist) {
3908 varregs = get_insecure_variable_from_config(peerlist);
3909 if (varregs) {
3910 newpeername = get_name_from_variable(varregs, newpeername);
3911 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
3914 } else {
3915 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
3916 if (peerlist) {
3917 var = get_insecure_variable_from_config(peerlist);
3918 if (var) {
3919 newpeername = get_name_from_variable(var, newpeername);
3920 varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
3928 if (!var) {
3929 if (peerlist)
3930 ast_config_destroy(peerlist);
3931 return NULL;
3934 for (tmp = var; tmp; tmp = tmp->next) {
3935 /* If this is type=user, then skip this object. */
3936 if (!strcasecmp(tmp->name, "type") &&
3937 !strcasecmp(tmp->value, "user")) {
3938 if(peerlist)
3939 ast_config_destroy(peerlist);
3940 else {
3941 ast_variables_destroy(var);
3942 ast_variables_destroy(varregs);
3944 return NULL;
3945 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
3946 newpeername = tmp->value;
3950 if (!newpeername) { /* Did not find peer in realtime */
3951 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
3952 if(peerlist)
3953 ast_config_destroy(peerlist);
3954 else
3955 ast_variables_destroy(var);
3956 return NULL;
3960 /* Peer found in realtime, now build it in memory */
3961 peer = build_peer(newpeername, var, varregs, 1);
3962 if (!peer) {
3963 if(peerlist)
3964 ast_config_destroy(peerlist);
3965 else {
3966 ast_variables_destroy(var);
3967 ast_variables_destroy(varregs);
3969 return NULL;
3972 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
3974 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
3975 /* Cache peer */
3976 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
3977 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
3978 AST_SCHED_REPLACE(peer->expire, sched, global_rtautoclear * 1000, expire_register, (void *) peer);
3979 /* we could be incr. its refcount right here, but I guess, since
3980 peers hang around until module unload time anyway, it's not worth the trouble */
3982 ao2_t_link(peers, peer, "link peer into peers table");
3983 if (peer->addr.sin_addr.s_addr) {
3984 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
3987 } else {
3988 peer->is_realtime = 1;
3990 if (peerlist)
3991 ast_config_destroy(peerlist);
3992 else {
3993 ast_variables_destroy(var);
3994 ast_variables_destroy(varregs);
3997 return peer;
4000 /*! \brief Locate peer by name or ip address
4001 * This is used on incoming SIP message to find matching peer on ip
4002 or outgoing message to find matching peer on name
4003 \note Avoid using this function in new functions if there is a way to avoid it, i
4004 since it might cause a database lookup.
4006 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
4008 struct sip_peer *p = NULL;
4009 struct sip_peer tmp_peer;
4011 if (peer) {
4012 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
4013 p = ao2_t_find(peers, &tmp_peer, OBJ_POINTER, "ao2_find in peers table");
4014 } else if (sin) { /* search by addr? */
4015 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
4016 tmp_peer.addr.sin_port = sin->sin_port;
4017 tmp_peer.flags[0].flags = 0;
4018 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); */
4019 if (!p) {
4020 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
4021 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); */
4022 if (p) {
4023 return p;
4028 if (!p && realtime)
4029 p = realtime_peer(peer, sin);
4031 return p;
4034 static void sip_destroy_user_fn(void *user)
4036 sip_destroy_user(user);
4040 /*! \brief Remove user object from in-memory storage */
4041 static void sip_destroy_user(struct sip_user *user)
4043 ast_debug(3, "Destroying user object from memory: %s\n", user->name);
4045 ast_free_ha(user->ha);
4046 if (user->chanvars) {
4047 ast_variables_destroy(user->chanvars);
4048 user->chanvars = NULL;
4050 if (user->is_realtime)
4051 ast_atomic_fetchadd_int(&ruserobjs, -1);
4052 else
4053 ast_atomic_fetchadd_int(&suserobjs, -1);
4056 /*! \brief Load user from realtime storage
4057 * Loads user from "sipusers" category in realtime (extconfig.conf)
4058 * returns a refcounted pointer to a sip_user structure.
4059 * Users are matched on From: user name (the domain in skipped) */
4060 static struct sip_user *realtime_user(const char *username)
4062 struct ast_variable *var;
4063 struct ast_variable *tmp;
4064 struct sip_user *user = NULL;
4066 var = ast_load_realtime("sipusers", "name", username, NULL);
4068 if (!var)
4069 return NULL;
4071 for (tmp = var; tmp; tmp = tmp->next) {
4072 if (!strcasecmp(tmp->name, "type") &&
4073 !strcasecmp(tmp->value, "peer")) {
4074 ast_variables_destroy(var);
4075 return NULL;
4079 user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
4081 if (!user) { /* No user found */
4082 ast_variables_destroy(var);
4083 return NULL;
4086 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
4087 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
4088 ast_atomic_fetchadd_int(&suserobjs, 1);
4089 ao2_t_link(users, user, "link user into users table");
4090 } else {
4091 /* Move counter from s to r... */
4092 ast_atomic_fetchadd_int(&suserobjs, -1);
4093 ast_atomic_fetchadd_int(&ruserobjs, 1);
4094 user->is_realtime = 1;
4096 ast_variables_destroy(var);
4097 return user;
4100 /*! \brief Locate user by name
4101 * Locates user by name (From: sip uri user name part) first
4102 * from in-memory list (static configuration) then from
4103 * realtime storage (defined in extconfig.conf)
4104 * \return a refcounted pointer to a user. Make sure the
4105 * the ref count is decremented when this pointer is nulled, changed,
4106 * or goes out of scope!
4109 static struct sip_user *find_user(const char *name, int realtime)
4111 struct sip_user tmp;
4112 struct sip_user *u;
4114 ast_copy_string(tmp.name, name, sizeof(tmp.name));
4115 u = ao2_t_find(users, &tmp, OBJ_POINTER, "ao2_find in users table");
4117 if (!u && realtime)
4118 u = realtime_user(name);
4119 return u;
4122 /*! \brief Set nat mode on the various data sockets */
4123 static void do_setnat(struct sip_pvt *p, int natflags)
4125 const char *mode = natflags ? "On" : "Off";
4127 if (p->rtp) {
4128 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
4129 ast_rtp_setnat(p->rtp, natflags);
4131 if (p->vrtp) {
4132 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
4133 ast_rtp_setnat(p->vrtp, natflags);
4135 if (p->udptl) {
4136 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
4137 ast_udptl_setnat(p->udptl, natflags);
4139 if (p->trtp) {
4140 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
4141 ast_rtp_setnat(p->trtp, natflags);
4145 /*! \brief Change the T38 state on a SIP dialog */
4146 static void change_t38_state(struct sip_pvt *p, int state)
4148 int old = p->t38.state;
4149 struct ast_channel *chan = p->owner;
4150 enum ast_control_t38 message = 0;
4152 /* Don't bother changing if we are already in the state wanted */
4153 if (old == state)
4154 return;
4156 p->t38.state = state;
4157 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
4159 /* If no channel was provided we can't send off a control frame */
4160 if (!chan)
4161 return;
4163 /* Given the state requested and old state determine what control frame we want to queue up */
4164 if (state == T38_ENABLED)
4165 message = AST_T38_NEGOTIATED;
4166 else if (state == T38_DISABLED && old == T38_ENABLED)
4167 message = AST_T38_TERMINATED;
4168 else if (state == T38_DISABLED && old == T38_LOCAL_REINVITE)
4169 message = AST_T38_REFUSED;
4171 /* Woot we got a message, create a control frame and send it on! */
4172 if (message)
4173 ast_queue_control_data(chan, AST_CONTROL_T38, &message, sizeof(message));
4176 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
4177 static void set_t38_capabilities(struct sip_pvt *p)
4179 p->t38.capability = global_t38_capability;
4180 if (p->udptl) {
4181 if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC )
4182 p->t38.capability |= T38FAX_UDP_EC_FEC;
4183 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
4184 p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
4185 else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE )
4186 p->t38.capability |= T38FAX_UDP_EC_NONE;
4187 p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
4191 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
4193 if (to_sock->ser) {
4194 ao2_ref(to_sock->ser, -1);
4195 to_sock->ser = NULL;
4198 if (from_sock->ser) {
4199 ao2_ref(from_sock->ser, +1);
4202 *to_sock = *from_sock;
4205 /*! \brief Create address structure from peer reference.
4206 * This function copies data from peer to the dialog, so we don't have to look up the peer
4207 * again from memory or database during the life time of the dialog.
4209 * \return -1 on error, 0 on success.
4212 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
4214 copy_socket_data(&dialog->socket, &peer->socket);
4216 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
4217 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
4218 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
4219 dialog->recv = dialog->sa;
4220 } else
4221 return -1;
4223 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
4224 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4225 dialog->capability = peer->capability;
4226 if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
4227 ast_rtp_destroy(dialog->vrtp);
4228 dialog->vrtp = NULL;
4230 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
4231 ast_rtp_destroy(dialog->trtp);
4232 dialog->trtp = NULL;
4234 dialog->prefs = peer->prefs;
4235 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
4236 ast_copy_flags(&dialog->t38.t38support, &peer->flags[1], SIP_PAGE2_T38SUPPORT);
4237 set_t38_capabilities(dialog);
4238 dialog->t38.jointcapability = dialog->t38.capability;
4239 } else if (dialog->udptl) {
4240 ast_udptl_destroy(dialog->udptl);
4241 dialog->udptl = NULL;
4243 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
4245 if (dialog->rtp) { /* Audio */
4246 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
4247 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
4248 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
4249 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
4250 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
4251 /* Set Frame packetization */
4252 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
4253 dialog->autoframing = peer->autoframing;
4255 if (dialog->vrtp) { /* Video */
4256 ast_rtp_setdtmf(dialog->vrtp, 0);
4257 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
4258 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
4259 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
4260 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
4262 if (dialog->trtp) { /* Realtime text */
4263 ast_rtp_setdtmf(dialog->trtp, 0);
4264 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
4265 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
4266 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
4267 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
4270 ast_string_field_set(dialog, peername, peer->name);
4271 ast_string_field_set(dialog, authname, peer->username);
4272 ast_string_field_set(dialog, username, peer->username);
4273 ast_string_field_set(dialog, peersecret, peer->secret);
4274 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
4275 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
4276 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
4277 ast_string_field_set(dialog, tohost, peer->tohost);
4278 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
4279 ast_string_field_set(dialog, context, peer->context);
4280 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
4281 dialog->outboundproxy = obproxy_get(dialog, peer);
4282 dialog->callgroup = peer->callgroup;
4283 dialog->pickupgroup = peer->pickupgroup;
4284 dialog->allowtransfer = peer->allowtransfer;
4285 dialog->jointnoncodeccapability = dialog->noncodeccapability;
4286 dialog->rtptimeout = peer->rtptimeout;
4287 dialog->maxcallbitrate = peer->maxcallbitrate;
4288 if (ast_strlen_zero(dialog->tohost))
4289 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
4290 if (!ast_strlen_zero(peer->fromdomain)) {
4291 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
4292 if (!dialog->initreq.headers) {
4293 char *c;
4294 char *tmpcall = ast_strdupa(dialog->callid);
4295 /* this sure looks to me like we are going to change the callid on this dialog!! */
4296 c = strchr(tmpcall, '@');
4297 if (c) {
4298 *c = '\0';
4299 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
4300 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
4301 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
4305 if (!ast_strlen_zero(peer->fromuser))
4306 ast_string_field_set(dialog, fromuser, peer->fromuser);
4307 if (!ast_strlen_zero(peer->language))
4308 ast_string_field_set(dialog, language, peer->language);
4310 /* Set timer T1 to RTT for this peer (if known by qualify=) */
4311 /* Minimum is settable or default to 100 ms */
4312 /* If there is a maxms and lastms from a qualify use that over a manual T1
4313 value. Otherwise, use the peer's T1 value. */
4314 if (peer->maxms && peer->lastms)
4315 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
4316 else
4317 dialog->timer_t1 = peer->timer_t1;
4319 /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
4320 the known timer */
4321 if (peer->timer_b)
4322 dialog->timer_b = peer->timer_b;
4323 else
4324 dialog->timer_b = 64 * dialog->timer_t1;
4326 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4327 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4328 dialog->noncodeccapability |= AST_RTP_DTMF;
4329 else
4330 dialog->noncodeccapability &= ~AST_RTP_DTMF;
4331 if (peer->call_limit)
4332 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
4334 return 0;
4336 /*! \brief create address structure from peer name
4337 * Or, if peer not found, find it in the global DNS
4338 * returns TRUE (-1) on failure, FALSE on success */
4339 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin)
4341 struct hostent *hp;
4342 struct ast_hostent ahp;
4343 struct sip_peer *peer;
4344 char *port;
4345 int portno;
4346 char host[MAXHOSTNAMELEN], *hostn;
4347 char peername[256];
4348 int srv_ret = 0;
4350 ast_copy_string(peername, opeer, sizeof(peername));
4351 port = strchr(peername, ':');
4352 if (port)
4353 *port++ = '\0';
4354 dialog->sa.sin_family = AF_INET;
4355 dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
4356 dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
4357 peer = find_peer(peername, NULL, 1);
4359 if (peer) {
4360 int res = create_addr_from_peer(dialog, peer);
4361 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
4362 return res;
4363 } else {
4364 /* Setup default parameters for this dialog's socket. Currently we only support regular UDP SIP as the default */
4365 dialog->socket.type = SIP_TRANSPORT_UDP;
4366 dialog->socket.port = bindaddr.sin_port;
4369 ast_string_field_set(dialog, tohost, peername);
4371 /* Get the outbound proxy information */
4372 dialog->outboundproxy = obproxy_get(dialog, NULL);
4374 /* If we have an outbound proxy, don't bother with DNS resolution at all */
4375 if (dialog->outboundproxy)
4376 return 0;
4378 /* This address should be updated using dnsmgr */
4379 if (sin) {
4380 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
4381 if (!sin->sin_port) {
4382 portno = port ? atoi(port) : (dialog->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
4383 } else {
4384 portno = ntohs(sin->sin_port);
4386 } else {
4388 /* Let's see if we can find the host in DNS. First try DNS SRV records,
4389 then hostname lookup */
4390 hostn = peername;
4391 portno = port ? atoi(port) : (dialog->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
4392 if (global_srvlookup) {
4393 char service[MAXHOSTNAMELEN];
4394 int tportno;
4396 snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
4397 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
4398 if (srv_ret > 0) {
4399 hostn = host;
4400 portno = tportno;
4404 hp = ast_gethostbyname(hostn, &ahp);
4405 if (!hp) {
4406 ast_log(LOG_WARNING, "No such host: %s\n", peername);
4407 return -1;
4409 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
4412 dialog->sa.sin_port = htons(portno);
4413 dialog->recv = dialog->sa;
4414 return 0;
4417 /*! \brief Scheduled congestion on a call.
4418 * Only called by the scheduler, must return the reference when done.
4420 static int auto_congest(const void *arg)
4422 struct sip_pvt *p = (struct sip_pvt *)arg;
4424 sip_pvt_lock(p);
4425 p->initid = -1; /* event gone, will not be rescheduled */
4426 if (p->owner) {
4427 /* XXX fails on possible deadlock */
4428 if (!ast_channel_trylock(p->owner)) {
4429 append_history(p, "Cong", "Auto-congesting (timer)");
4430 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
4431 ast_channel_unlock(p->owner);
4434 sip_pvt_unlock(p);
4435 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
4436 return 0;
4440 /*! \brief Initiate SIP call from PBX
4441 * used from the dial() application */
4442 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
4444 int res;
4445 struct sip_pvt *p = ast->tech_pvt; /* chan is locked, so the reference cannot go away */
4446 struct varshead *headp;
4447 struct ast_var_t *current;
4448 const char *referer = NULL; /* SIP referrer */
4450 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
4451 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
4452 return -1;
4455 /* Check whether there is vxml_url, distinctive ring variables */
4456 headp=&ast->varshead;
4457 AST_LIST_TRAVERSE(headp, current, entries) {
4458 /* Check whether there is a VXML_URL variable */
4459 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
4460 p->options->vxml_url = ast_var_value(current);
4461 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
4462 p->options->uri_options = ast_var_value(current);
4463 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
4464 /* Check whether there is a variable with a name starting with SIPADDHEADER */
4465 p->options->addsipheaders = 1;
4466 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
4467 /* This is a transfered call */
4468 p->options->transfer = 1;
4469 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
4470 /* This is the referrer */
4471 referer = ast_var_value(current);
4472 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
4473 /* We're replacing a call. */
4474 p->options->replaces = ast_var_value(current);
4475 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
4476 p->t38.state = T38_LOCAL_DIRECT;
4477 ast_debug(1, "T38State change to %d on channel %s\n", p->t38.state, ast->name);
4482 res = 0;
4483 ast_set_flag(&p->flags[0], SIP_OUTGOING);
4485 if (p->options->transfer) {
4486 char buf[SIPBUFSIZE/2];
4488 if (referer) {
4489 if (sipdebug)
4490 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
4491 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
4492 } else
4493 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
4494 ast_string_field_set(p, cid_name, buf);
4496 ast_debug(1, "Outgoing Call for %s\n", p->username);
4498 res = update_call_counter(p, INC_CALL_RINGING);
4500 if (res == -1)
4501 return res;
4503 p->callingpres = ast->cid.cid_pres;
4504 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
4505 p->jointnoncodeccapability = p->noncodeccapability;
4507 /* If there are no audio formats left to offer, punt */
4508 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
4509 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
4510 res = -1;
4511 } else {
4512 int xmitres;
4514 p->t38.jointcapability = p->t38.capability;
4515 ast_debug(2, "Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
4517 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
4518 if (xmitres == XMIT_ERROR)
4519 return -1;
4520 p->invitestate = INV_CALLING;
4522 /* Initialize auto-congest time */
4523 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
4524 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
4525 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
4526 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
4528 return res;
4531 /*! \brief Destroy registry object
4532 Objects created with the register= statement in static configuration */
4533 static void sip_registry_destroy(struct sip_registry *reg)
4535 /* Really delete */
4536 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
4538 if (reg->call) {
4539 /* Clear registry before destroying to ensure
4540 we don't get reentered trying to grab the registry lock */
4541 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
4542 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
4543 dialog_unlink_all(reg->call, TRUE, TRUE);
4544 reg->call = dialog_unref(reg->call, "unref reg->call");
4545 /* reg->call = sip_destroy(reg->call); */
4547 AST_SCHED_DEL(sched, reg->expire);
4548 AST_SCHED_DEL(sched, reg->timeout);
4550 ast_string_field_free_memory(reg);
4551 ast_atomic_fetchadd_int(&regobjs, -1);
4552 ast_dnsmgr_release(reg->dnsmgr);
4553 ast_free(reg);
4557 /*! \brief Execute destruction of SIP dialog structure, release memory */
4558 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
4561 if (sip_debug_test_pvt(p))
4562 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
4564 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4565 update_call_counter(p, DEC_CALL_LIMIT);
4566 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
4569 /* Unlink us from the owner if we have one */
4570 if (p->owner) {
4571 if (lockowner)
4572 ast_channel_lock(p->owner);
4573 if (option_debug)
4574 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
4575 p->owner->tech_pvt = NULL;
4576 /* Make sure that the channel knows its backend is going away */
4577 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
4578 if (lockowner)
4579 ast_channel_unlock(p->owner);
4580 /* Give the channel a chance to react before deallocation */
4581 usleep(1);
4584 /* Remove link from peer to subscription of MWI */
4585 if (p->relatedpeer && p->relatedpeer->mwipvt)
4586 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
4587 if (p->relatedpeer && p->relatedpeer->call == p)
4588 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
4590 if (p->relatedpeer)
4591 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
4593 if (p->registry) {
4594 if (p->registry->call == p)
4595 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
4596 p->registry = registry_unref(p->registry, "delete p->registry");
4599 if (dumphistory)
4600 sip_dump_history(p);
4602 if (p->options)
4603 ast_free(p->options);
4605 if (p->notify_headers) {
4606 ast_variables_destroy(p->notify_headers);
4607 p->notify_headers = NULL;
4609 if (p->rtp) {
4610 ast_rtp_destroy(p->rtp);
4612 if (p->vrtp) {
4613 ast_rtp_destroy(p->vrtp);
4615 if (p->trtp) {
4616 while (ast_rtp_get_bridged(p->trtp))
4617 usleep(1);
4618 ast_rtp_destroy(p->trtp);
4620 if (p->udptl)
4621 ast_udptl_destroy(p->udptl);
4622 if (p->refer)
4623 ast_free(p->refer);
4624 if (p->route) {
4625 free_old_route(p->route);
4626 p->route = NULL;
4628 if (p->initreq.data)
4629 ast_free(p->initreq.data);
4631 /* Destroy Session-Timers if allocated */
4632 if (p->stimer) {
4633 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1)
4634 AST_SCHED_DEL(sched, p->stimer->st_schedid);
4635 ast_free(p->stimer);
4636 p->stimer = NULL;
4639 /* Clear history */
4640 if (p->history) {
4641 struct sip_history *hist;
4642 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
4643 ast_free(hist);
4644 p->history_entries--;
4646 ast_free(p->history);
4647 p->history = NULL;
4650 if (p->chanvars) {
4651 ast_variables_destroy(p->chanvars);
4652 p->chanvars = NULL;
4655 ast_string_field_free_memory(p);
4657 if (p->socket.ser) {
4658 ao2_ref(p->socket.ser, -1);
4659 p->socket.ser = NULL;
4663 /*! \brief update_call_counter: Handle call_limit for SIP users
4664 * Setting a call-limit will cause calls above the limit not to be accepted.
4666 * Remember that for a type=friend, there's one limit for the user and
4667 * another for the peer, not a combined call limit.
4668 * This will cause unexpected behaviour in subscriptions, since a "friend"
4669 * is *two* devices in Asterisk, not one.
4671 * Thought: For realtime, we should probably update storage with inuse counter...
4673 * \return 0 if call is ok (no call limit, below threshold)
4674 * -1 on rejection of call
4677 static int update_call_counter(struct sip_pvt *fup, int event)
4679 char name[256];
4680 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
4681 int outgoing = fup->outgoing_call;
4682 struct sip_user *u = NULL;
4683 struct sip_peer *p = NULL;
4685 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
4688 /* Test if we need to check call limits, in order to avoid
4689 realtime lookups if we do not need it */
4690 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
4691 return 0;
4693 ast_copy_string(name, fup->username, sizeof(name));
4695 /* Check the list of users only for incoming calls */
4696 if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1))) {
4697 inuse = &u->inUse;
4698 call_limit = &u->call_limit;
4699 inringing = NULL;
4700 } else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
4701 inuse = &p->inUse;
4702 call_limit = &p->call_limit;
4703 inringing = &p->inRinging;
4704 ast_copy_string(name, fup->peername, sizeof(name));
4706 if (!p && !u) {
4707 ast_debug(2, "%s is not a local device, no call limit\n", name);
4708 return 0;
4711 switch(event) {
4712 /* incoming and outgoing affects the inUse counter */
4713 case DEC_CALL_LIMIT:
4714 /* Decrement inuse count if applicable */
4715 if (inuse && ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
4716 ast_atomic_fetchadd_int(inuse, -1);
4717 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
4718 } else
4719 *inuse = 0;
4720 /* Decrement ringing count if applicable */
4721 if (inringing && ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
4722 ast_atomic_fetchadd_int(inringing, -1);
4723 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
4725 /* Decrement onhold count if applicable */
4726 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
4727 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
4728 sip_peer_hold(fup, FALSE);
4730 if (sipdebug)
4731 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
4732 break;
4734 case INC_CALL_RINGING:
4735 case INC_CALL_LIMIT:
4736 /* If call limit is active and we have reached the limit, reject the call */
4737 if (*call_limit > 0 ) {
4738 if (*inuse >= *call_limit) {
4739 ast_log(LOG_WARNING, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
4740 if (u)
4741 unref_user(u, "update_call_counter: unref user u call limit exceeded");
4742 else
4743 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
4744 return -1;
4747 if (inringing && (event == INC_CALL_RINGING)) {
4748 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
4749 ast_atomic_fetchadd_int(inringing, +1);
4750 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
4753 /* Continue */
4754 ast_atomic_fetchadd_int(inuse, +1);
4755 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
4756 if (sipdebug) {
4757 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
4759 break;
4761 case DEC_CALL_RINGING:
4762 if (inringing && ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
4763 ast_atomic_fetchadd_int(inringing, -1);
4764 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
4766 break;
4768 default:
4769 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
4771 if (p) {
4772 ast_device_state_changed("SIP/%s", p->name);
4773 unref_peer(p, "update_call_counter: unref_peer from call counter");
4774 } else /* u must be set */
4775 unref_user(u, "update_call_counter: unref_user from call counter");
4776 return 0;
4780 static void sip_destroy_fn(void *p)
4782 sip_destroy(p);
4785 /*! \brief Destroy SIP call structure.
4786 * Make it return NULL so the caller can do things like
4787 * foo = sip_destroy(foo);
4788 * and reduce the chance of bugs due to dangling pointers.
4790 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
4792 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
4793 __sip_destroy(p, TRUE, TRUE);
4794 return NULL;
4797 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
4798 static int hangup_sip2cause(int cause)
4800 /* Possible values taken from causes.h */
4802 switch(cause) {
4803 case 401: /* Unauthorized */
4804 return AST_CAUSE_CALL_REJECTED;
4805 case 403: /* Not found */
4806 return AST_CAUSE_CALL_REJECTED;
4807 case 404: /* Not found */
4808 return AST_CAUSE_UNALLOCATED;
4809 case 405: /* Method not allowed */
4810 return AST_CAUSE_INTERWORKING;
4811 case 407: /* Proxy authentication required */
4812 return AST_CAUSE_CALL_REJECTED;
4813 case 408: /* No reaction */
4814 return AST_CAUSE_NO_USER_RESPONSE;
4815 case 409: /* Conflict */
4816 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
4817 case 410: /* Gone */
4818 return AST_CAUSE_UNALLOCATED;
4819 case 411: /* Length required */
4820 return AST_CAUSE_INTERWORKING;
4821 case 413: /* Request entity too large */
4822 return AST_CAUSE_INTERWORKING;
4823 case 414: /* Request URI too large */
4824 return AST_CAUSE_INTERWORKING;
4825 case 415: /* Unsupported media type */
4826 return AST_CAUSE_INTERWORKING;
4827 case 420: /* Bad extension */
4828 return AST_CAUSE_NO_ROUTE_DESTINATION;
4829 case 480: /* No answer */
4830 return AST_CAUSE_NO_ANSWER;
4831 case 481: /* No answer */
4832 return AST_CAUSE_INTERWORKING;
4833 case 482: /* Loop detected */
4834 return AST_CAUSE_INTERWORKING;
4835 case 483: /* Too many hops */
4836 return AST_CAUSE_NO_ANSWER;
4837 case 484: /* Address incomplete */
4838 return AST_CAUSE_INVALID_NUMBER_FORMAT;
4839 case 485: /* Ambiguous */
4840 return AST_CAUSE_UNALLOCATED;
4841 case 486: /* Busy everywhere */
4842 return AST_CAUSE_BUSY;
4843 case 487: /* Request terminated */
4844 return AST_CAUSE_INTERWORKING;
4845 case 488: /* No codecs approved */
4846 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
4847 case 491: /* Request pending */
4848 return AST_CAUSE_INTERWORKING;
4849 case 493: /* Undecipherable */
4850 return AST_CAUSE_INTERWORKING;
4851 case 500: /* Server internal failure */
4852 return AST_CAUSE_FAILURE;
4853 case 501: /* Call rejected */
4854 return AST_CAUSE_FACILITY_REJECTED;
4855 case 502:
4856 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
4857 case 503: /* Service unavailable */
4858 return AST_CAUSE_CONGESTION;
4859 case 504: /* Gateway timeout */
4860 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
4861 case 505: /* SIP version not supported */
4862 return AST_CAUSE_INTERWORKING;
4863 case 600: /* Busy everywhere */
4864 return AST_CAUSE_USER_BUSY;
4865 case 603: /* Decline */
4866 return AST_CAUSE_CALL_REJECTED;
4867 case 604: /* Does not exist anywhere */
4868 return AST_CAUSE_UNALLOCATED;
4869 case 606: /* Not acceptable */
4870 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
4871 default:
4872 return AST_CAUSE_NORMAL;
4874 /* Never reached */
4875 return 0;
4878 /*! \brief Convert Asterisk hangup causes to SIP codes
4879 \verbatim
4880 Possible values from causes.h
4881 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
4882 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
4884 In addition to these, a lot of PRI codes is defined in causes.h
4885 ...should we take care of them too ?
4887 Quote RFC 3398
4889 ISUP Cause value SIP response
4890 ---------------- ------------
4891 1 unallocated number 404 Not Found
4892 2 no route to network 404 Not found
4893 3 no route to destination 404 Not found
4894 16 normal call clearing --- (*)
4895 17 user busy 486 Busy here
4896 18 no user responding 408 Request Timeout
4897 19 no answer from the user 480 Temporarily unavailable
4898 20 subscriber absent 480 Temporarily unavailable
4899 21 call rejected 403 Forbidden (+)
4900 22 number changed (w/o diagnostic) 410 Gone
4901 22 number changed (w/ diagnostic) 301 Moved Permanently
4902 23 redirection to new destination 410 Gone
4903 26 non-selected user clearing 404 Not Found (=)
4904 27 destination out of order 502 Bad Gateway
4905 28 address incomplete 484 Address incomplete
4906 29 facility rejected 501 Not implemented
4907 31 normal unspecified 480 Temporarily unavailable
4908 \endverbatim
4910 static const char *hangup_cause2sip(int cause)
4912 switch (cause) {
4913 case AST_CAUSE_UNALLOCATED: /* 1 */
4914 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
4915 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
4916 return "404 Not Found";
4917 case AST_CAUSE_CONGESTION: /* 34 */
4918 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
4919 return "503 Service Unavailable";
4920 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
4921 return "408 Request Timeout";
4922 case AST_CAUSE_NO_ANSWER: /* 19 */
4923 return "480 Temporarily unavailable";
4924 case AST_CAUSE_CALL_REJECTED: /* 21 */
4925 return "403 Forbidden";
4926 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
4927 return "410 Gone";
4928 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
4929 return "480 Temporarily unavailable";
4930 case AST_CAUSE_INVALID_NUMBER_FORMAT:
4931 return "484 Address incomplete";
4932 case AST_CAUSE_USER_BUSY:
4933 return "486 Busy here";
4934 case AST_CAUSE_FAILURE:
4935 return "500 Server internal failure";
4936 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
4937 return "501 Not Implemented";
4938 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
4939 return "503 Service Unavailable";
4940 /* Used in chan_iax2 */
4941 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
4942 return "502 Bad Gateway";
4943 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
4944 return "488 Not Acceptable Here";
4946 case AST_CAUSE_NOTDEFINED:
4947 default:
4948 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
4949 return NULL;
4952 /* Never reached */
4953 return 0;
4957 /*! \brief sip_hangup: Hangup SIP call
4958 * Part of PBX interface, called from ast_hangup */
4959 static int sip_hangup(struct ast_channel *ast)
4961 struct sip_pvt *p = ast->tech_pvt;
4962 int needcancel = FALSE;
4963 int needdestroy = 0;
4964 struct ast_channel *oldowner = ast;
4966 if (!p) {
4967 ast_debug(1, "Asked to hangup channel that was not connected\n");
4968 return 0;
4970 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
4971 ast_debug(1, "This call was answered elsewhere");
4972 append_history(p, "Cancel", "Call answered elsewhere");
4973 p->answered_elsewhere = TRUE;
4976 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
4977 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
4978 if (sipdebug)
4979 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
4980 update_call_counter(p, DEC_CALL_LIMIT);
4982 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
4983 if (p->autokillid > -1 && sip_cancel_destroy(p))
4984 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
4985 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4986 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
4987 p->needdestroy = 0;
4988 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
4989 sip_pvt_lock(p);
4990 p->owner = NULL; /* Owner will be gone after we return, so take it away */
4991 sip_pvt_unlock(p);
4992 return 0;
4995 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
4996 if (p->refer)
4997 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
4998 else
4999 ast_debug(1, "Hanging up zombie call. Be scared.\n");
5000 } else
5001 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
5003 sip_pvt_lock(p);
5004 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
5005 if (sipdebug)
5006 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
5007 update_call_counter(p, DEC_CALL_LIMIT);
5010 /* Determine how to disconnect */
5011 if (p->owner != ast) {
5012 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
5013 sip_pvt_unlock(p);
5014 return 0;
5016 /* If the call is not UP, we need to send CANCEL instead of BYE */
5017 /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
5018 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
5019 needcancel = TRUE;
5020 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
5023 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
5025 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->owner->hangupcause) : "Unknown");
5027 /* Disconnect */
5028 if (p->vad)
5029 ast_dsp_free(p->vad);
5031 p->owner = NULL;
5032 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
5034 ast_module_unref(ast_module_info->self);
5035 /* Do not destroy this pvt until we have timeout or
5036 get an answer to the BYE or INVITE/CANCEL
5037 If we get no answer during retransmit period, drop the call anyway.
5038 (Sorry, mother-in-law, you can't deny a hangup by sending
5039 603 declined to BYE...)
5041 if (p->alreadygone)
5042 needdestroy = 1; /* Set destroy flag at end of this function */
5043 else if (p->invitestate != INV_CALLING)
5044 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5046 /* Start the process if it's not already started */
5047 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
5048 if (needcancel) { /* Outgoing call, not up */
5049 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5050 /* stop retransmitting an INVITE that has not received a response */
5051 __sip_pretend_ack(p);
5052 p->invitestate = INV_CANCELLED;
5054 /* if we can't send right now, mark it pending */
5055 if (p->invitestate == INV_CALLING) {
5056 /* We can't send anything in CALLING state */
5057 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
5058 /* Do we need a timer here if we don't hear from them at all? */
5059 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5060 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
5061 } else {
5062 /* Send a new request: CANCEL */
5063 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
5064 /* Actually don't destroy us yet, wait for the 487 on our original
5065 INVITE, but do set an autodestruct just in case we never get it. */
5066 needdestroy = 0;
5067 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5069 if ( p->initid != -1 ) {
5070 /* channel still up - reverse dec of inUse counter
5071 only if the channel is not auto-congested */
5072 update_call_counter(p, INC_CALL_LIMIT);
5074 } else { /* Incoming call, not up */
5075 const char *res;
5076 if (ast->hangupcause && (res = hangup_cause2sip(ast->hangupcause)))
5077 transmit_response_reliable(p, res, &p->initreq);
5078 else
5079 transmit_response_reliable(p, "603 Declined", &p->initreq);
5080 p->invitestate = INV_TERMINATED;
5082 } else { /* Call is in UP state, send BYE */
5083 if (!p->pendinginvite) {
5084 struct ast_channel *bridge = ast_bridged_channel(oldowner);
5085 char *audioqos = "";
5086 char *videoqos = "";
5087 char *textqos = "";
5089 if (p->rtp)
5090 ast_rtp_set_vars(oldowner, p->rtp);
5092 if (bridge) {
5093 struct sip_pvt *q = bridge->tech_pvt;
5095 if (IS_SIP_TECH(bridge->tech) && q->rtp)
5096 ast_rtp_set_vars(bridge, q->rtp);
5099 if (p->vrtp)
5100 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
5101 if (p->trtp)
5102 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
5103 /* Send a hangup */
5104 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
5106 /* Get RTCP quality before end of call */
5107 if (p->do_history) {
5108 if (p->rtp)
5109 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
5110 if (p->vrtp)
5111 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
5112 if (p->trtp)
5113 append_history(p, "RTCPtext", "Quality:%s", textqos);
5115 if (p->rtp && oldowner)
5116 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
5117 if (p->vrtp && oldowner)
5118 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
5119 if (p->trtp && oldowner)
5120 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
5121 } else {
5122 /* Note we will need a BYE when this all settles out
5123 but we can't send one while we have "INVITE" outstanding. */
5124 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
5125 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
5126 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"));
5127 if (sip_cancel_destroy(p))
5128 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
5132 if (needdestroy)
5133 p->needdestroy = 1;
5134 sip_pvt_unlock(p);
5135 return 0;
5138 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
5139 static void try_suggested_sip_codec(struct sip_pvt *p)
5141 int fmt;
5142 const char *codec;
5144 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
5145 if (!codec)
5146 return;
5148 fmt = ast_getformatbyname(codec);
5149 if (fmt) {
5150 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
5151 if (p->jointcapability & fmt) {
5152 p->jointcapability &= fmt;
5153 p->capability &= fmt;
5154 } else
5155 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
5156 } else
5157 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
5158 return;
5161 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
5162 * Part of PBX interface */
5163 static int sip_answer(struct ast_channel *ast)
5165 int res = 0;
5166 struct sip_pvt *p = ast->tech_pvt;
5168 sip_pvt_lock(p);
5169 if (ast->_state != AST_STATE_UP) {
5170 try_suggested_sip_codec(p);
5172 ast_setstate(ast, AST_STATE_UP);
5173 ast_debug(1, "SIP answering channel: %s\n", ast->name);
5174 if (p->t38.state == T38_PEER_DIRECT) {
5175 change_t38_state(p, T38_ENABLED);
5176 res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
5177 } else {
5178 ast_rtp_new_source(p->rtp);
5179 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
5182 sip_pvt_unlock(p);
5183 return res;
5186 /*! \brief Send frame to media channel (rtp) */
5187 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
5189 struct sip_pvt *p = ast->tech_pvt;
5190 int res = 0;
5192 switch (frame->frametype) {
5193 case AST_FRAME_VOICE:
5194 if (!(frame->subclass & ast->nativeformats)) {
5195 char s1[512], s2[512], s3[512];
5196 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
5197 frame->subclass,
5198 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
5199 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
5200 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
5201 ast->readformat,
5202 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
5203 ast->writeformat);
5204 return 0;
5206 if (p) {
5207 sip_pvt_lock(p);
5208 if (p->rtp) {
5209 /* If channel is not up, activate early media session */
5210 if ((ast->_state != AST_STATE_UP) &&
5211 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5212 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5213 ast_rtp_new_source(p->rtp);
5214 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5215 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5217 p->lastrtptx = time(NULL);
5218 res = ast_rtp_write(p->rtp, frame);
5220 sip_pvt_unlock(p);
5222 break;
5223 case AST_FRAME_VIDEO:
5224 if (p) {
5225 sip_pvt_lock(p);
5226 if (p->vrtp) {
5227 /* Activate video early media */
5228 if ((ast->_state != AST_STATE_UP) &&
5229 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5230 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5231 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5232 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5234 p->lastrtptx = time(NULL);
5235 res = ast_rtp_write(p->vrtp, frame);
5237 sip_pvt_unlock(p);
5239 break;
5240 case AST_FRAME_TEXT:
5241 if (p) {
5242 sip_pvt_lock(p);
5243 if (p->red) {
5244 red_buffer_t140(p->trtp, frame);
5245 } else {
5246 if (p->trtp) {
5247 /* Activate text early media */
5248 if ((ast->_state != AST_STATE_UP) &&
5249 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5250 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5251 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5252 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5254 p->lastrtptx = time(NULL);
5255 res = ast_rtp_write(p->trtp, frame);
5258 sip_pvt_unlock(p);
5260 break;
5261 case AST_FRAME_IMAGE:
5262 return 0;
5263 break;
5264 case AST_FRAME_MODEM:
5265 if (p) {
5266 sip_pvt_lock(p);
5267 /* UDPTL requires two-way communication, so early media is not needed here.
5268 we simply forget the frames if we get modem frames before the bridge is up.
5269 Fax will re-transmit.
5271 if (p->udptl && ast->_state == AST_STATE_UP)
5272 res = ast_udptl_write(p->udptl, frame);
5273 sip_pvt_unlock(p);
5275 break;
5276 default:
5277 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
5278 return 0;
5281 return res;
5284 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
5285 Basically update any ->owner links */
5286 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
5288 int ret = -1;
5289 struct sip_pvt *p;
5291 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
5292 ast_debug(1, "New channel is zombie\n");
5293 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
5294 ast_debug(1, "Old channel is zombie\n");
5296 if (!newchan || !newchan->tech_pvt) {
5297 if (!newchan)
5298 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
5299 else
5300 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
5301 return -1;
5303 p = newchan->tech_pvt;
5305 sip_pvt_lock(p);
5306 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
5307 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
5308 if (p->owner != oldchan)
5309 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
5310 else {
5311 p->owner = newchan;
5312 /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
5313 RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
5314 able to do this if the masquerade happens before the bridge breaks (e.g., AMI
5315 redirect of both channels). Note that a channel can not be masqueraded *into*
5316 a native bridge. So there is no danger that this breaks a native bridge that
5317 should stay up. */
5318 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
5319 ret = 0;
5321 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
5323 sip_pvt_unlock(p);
5324 return ret;
5327 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
5329 struct sip_pvt *p = ast->tech_pvt;
5330 int res = 0;
5332 sip_pvt_lock(p);
5333 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
5334 case SIP_DTMF_INBAND:
5335 res = -1; /* Tell Asterisk to generate inband indications */
5336 break;
5337 case SIP_DTMF_RFC2833:
5338 if (p->rtp)
5339 ast_rtp_senddigit_begin(p->rtp, digit);
5340 break;
5341 default:
5342 break;
5344 sip_pvt_unlock(p);
5346 return res;
5349 /*! \brief Send DTMF character on SIP channel
5350 within one call, we're able to transmit in many methods simultaneously */
5351 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
5353 struct sip_pvt *p = ast->tech_pvt;
5354 int res = 0;
5356 sip_pvt_lock(p);
5357 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
5358 case SIP_DTMF_INFO:
5359 case SIP_DTMF_SHORTINFO:
5360 transmit_info_with_digit(p, digit, duration);
5361 break;
5362 case SIP_DTMF_RFC2833:
5363 if (p->rtp)
5364 ast_rtp_senddigit_end(p->rtp, digit);
5365 break;
5366 case SIP_DTMF_INBAND:
5367 res = -1; /* Tell Asterisk to stop inband indications */
5368 break;
5370 sip_pvt_unlock(p);
5372 return res;
5375 /*! \brief Transfer SIP call */
5376 static int sip_transfer(struct ast_channel *ast, const char *dest)
5378 struct sip_pvt *p = ast->tech_pvt;
5379 int res;
5381 if (dest == NULL) /* functions below do not take a NULL */
5382 dest = "";
5383 sip_pvt_lock(p);
5384 if (ast->_state == AST_STATE_RING)
5385 res = sip_sipredirect(p, dest);
5386 else
5387 res = transmit_refer(p, dest);
5388 sip_pvt_unlock(p);
5389 return res;
5392 /*! \brief Play indication to user
5393 * With SIP a lot of indications is sent as messages, letting the device play
5394 the indication - busy signal, congestion etc
5395 \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
5397 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
5399 struct sip_pvt *p = ast->tech_pvt;
5400 int res = 0;
5402 sip_pvt_lock(p);
5403 switch(condition) {
5404 case AST_CONTROL_RINGING:
5405 if (ast->_state == AST_STATE_RING) {
5406 p->invitestate = INV_EARLY_MEDIA;
5407 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
5408 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
5409 /* Send 180 ringing if out-of-band seems reasonable */
5410 transmit_response(p, "180 Ringing", &p->initreq);
5411 ast_set_flag(&p->flags[0], SIP_RINGING);
5412 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
5413 break;
5414 } else {
5415 /* Well, if it's not reasonable, just send in-band */
5418 res = -1;
5419 break;
5420 case AST_CONTROL_BUSY:
5421 if (ast->_state != AST_STATE_UP) {
5422 transmit_response(p, "486 Busy Here", &p->initreq);
5423 p->invitestate = INV_COMPLETED;
5424 sip_alreadygone(p);
5425 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
5426 break;
5428 res = -1;
5429 break;
5430 case AST_CONTROL_CONGESTION:
5431 if (ast->_state != AST_STATE_UP) {
5432 transmit_response(p, "503 Service Unavailable", &p->initreq);
5433 p->invitestate = INV_COMPLETED;
5434 sip_alreadygone(p);
5435 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
5436 break;
5438 res = -1;
5439 break;
5440 case AST_CONTROL_PROCEEDING:
5441 if ((ast->_state != AST_STATE_UP) &&
5442 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5443 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5444 transmit_response(p, "100 Trying", &p->initreq);
5445 p->invitestate = INV_PROCEEDING;
5446 break;
5448 res = -1;
5449 break;
5450 case AST_CONTROL_PROGRESS:
5451 if ((ast->_state != AST_STATE_UP) &&
5452 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
5453 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
5454 p->invitestate = INV_EARLY_MEDIA;
5455 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
5456 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
5457 break;
5459 res = -1;
5460 break;
5461 case AST_CONTROL_HOLD:
5462 ast_rtp_new_source(p->rtp);
5463 ast_moh_start(ast, data, p->mohinterpret);
5464 break;
5465 case AST_CONTROL_UNHOLD:
5466 ast_rtp_new_source(p->rtp);
5467 ast_moh_stop(ast);
5468 break;
5469 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
5470 if (p->vrtp && !p->novideo) {
5471 transmit_info_with_vidupdate(p);
5472 /* ast_rtcp_send_h261fur(p->vrtp); */
5473 } else
5474 res = -1;
5475 break;
5476 case AST_CONTROL_T38: /* T38 control frame */
5477 if (datalen != sizeof(enum ast_control_t38)) {
5478 ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38. Expected %d, got %d\n", (int)sizeof(enum ast_control_t38), (int)datalen);
5479 } else {
5480 switch (*((enum ast_control_t38 *) data)) {
5481 case AST_T38_REQUEST_NEGOTIATE: /* Request T38 */
5482 if (p->t38.state != T38_ENABLED) {
5483 change_t38_state(p, T38_LOCAL_REINVITE);
5484 transmit_reinvite_with_sdp(p, TRUE, FALSE);
5486 break;
5487 case AST_T38_TERMINATED:
5488 case AST_T38_REFUSED:
5489 case AST_T38_REQUEST_TERMINATE: /* Shutdown T38 */
5490 if (p->t38.state == T38_ENABLED)
5491 transmit_reinvite_with_sdp(p, FALSE, FALSE);
5492 break;
5493 default:
5494 break;
5497 break;
5498 case AST_CONTROL_SRCUPDATE:
5499 ast_rtp_new_source(p->rtp);
5500 break;
5501 case -1:
5502 res = -1;
5503 break;
5504 default:
5505 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
5506 res = -1;
5507 break;
5509 sip_pvt_unlock(p);
5510 return res;
5514 /*! \brief Initiate a call in the SIP channel
5515 called from sip_request_call (calls from the pbx ) for outbound channels
5516 and from handle_request_invite for inbound channels
5519 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
5521 struct ast_channel *tmp;
5522 struct ast_variable *v = NULL;
5523 int fmt;
5524 int what;
5525 int video;
5526 int text;
5527 int needvideo = 0;
5528 int needtext = 0;
5529 char buf[SIPBUFSIZE];
5530 char *decoded_exten;
5533 const char *my_name; /* pick a good name */
5535 if (title)
5536 my_name = title;
5537 else if ( (my_name = strchr(i->fromdomain, ':')) )
5538 my_name++; /* skip ':' */
5539 else
5540 my_name = i->fromdomain;
5542 sip_pvt_unlock(i);
5543 /* Don't hold a sip pvt lock while we allocate a channel */
5544 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);
5547 if (!tmp) {
5548 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
5549 sip_pvt_lock(i);
5550 return NULL;
5552 sip_pvt_lock(i);
5554 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;
5556 /* Select our native format based on codec preference until we receive
5557 something from another device to the contrary. */
5558 if (i->jointcapability) { /* The joint capabilities of us and peer */
5559 what = i->jointcapability;
5560 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
5561 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
5562 } else if (i->capability) { /* Our configured capability for this peer */
5563 what = i->capability;
5564 video = i->capability & AST_FORMAT_VIDEO_MASK;
5565 text = i->capability & AST_FORMAT_TEXT_MASK;
5566 } else {
5567 what = global_capability; /* Global codec support */
5568 video = global_capability & AST_FORMAT_VIDEO_MASK;
5569 text = global_capability & AST_FORMAT_TEXT_MASK;
5572 /* Set the native formats for audio and merge in video */
5573 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
5574 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
5575 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
5576 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
5577 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
5578 if (i->prefcodec)
5579 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
5581 /* XXX Why are we choosing a codec from the native formats?? */
5582 fmt = ast_best_codec(tmp->nativeformats);
5584 /* If we have a prefcodec setting, we have an inbound channel that set a
5585 preferred format for this call. Otherwise, we check the jointcapability
5586 We also check for vrtp. If it's not there, we are not allowed do any video anyway.
5588 if (i->vrtp) {
5589 if (i->prefcodec)
5590 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK; /* Outbound call */
5591 else
5592 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK; /* Inbound call */
5595 if (i->trtp) {
5596 if (i->prefcodec)
5597 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
5598 else
5599 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
5602 if (needvideo)
5603 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
5604 else
5605 ast_debug(3, "This channel will not be able to handle video.\n");
5609 if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
5610 i->vad = ast_dsp_new();
5611 ast_dsp_set_features(i->vad, DSP_FEATURE_DIGIT_DETECT);
5612 if (global_relaxdtmf)
5613 ast_dsp_set_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
5616 /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
5617 if (i->rtp) {
5618 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
5619 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
5621 if (needvideo && i->vrtp) {
5622 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
5623 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
5625 if (needtext && i->trtp)
5626 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
5627 if (i->udptl)
5628 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
5630 if (state == AST_STATE_RING)
5631 tmp->rings = 1;
5632 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
5633 tmp->writeformat = fmt;
5634 tmp->rawwriteformat = fmt;
5635 tmp->readformat = fmt;
5636 tmp->rawreadformat = fmt;
5637 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
5639 tmp->callgroup = i->callgroup;
5640 tmp->pickupgroup = i->pickupgroup;
5641 tmp->cid.cid_pres = i->callingpres;
5642 if (!ast_strlen_zero(i->accountcode))
5643 ast_string_field_set(tmp, accountcode, i->accountcode);
5644 if (i->amaflags)
5645 tmp->amaflags = i->amaflags;
5646 if (!ast_strlen_zero(i->language))
5647 ast_string_field_set(tmp, language, i->language);
5648 i->owner = tmp;
5649 ast_module_ref(ast_module_info->self);
5650 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5651 /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
5652 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
5653 * structure so that there aren't issues when forming URI's
5655 decoded_exten = ast_strdupa(i->exten);
5656 ast_uri_decode(decoded_exten);
5657 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
5659 /* Don't use ast_set_callerid() here because it will
5660 * generate an unnecessary NewCallerID event */
5661 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5662 if (!ast_strlen_zero(i->rdnis))
5663 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
5665 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
5666 tmp->cid.cid_dnid = ast_strdup(i->exten);
5668 tmp->priority = 1;
5669 if (!ast_strlen_zero(i->uri))
5670 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
5671 if (!ast_strlen_zero(i->domain))
5672 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
5673 if (!ast_strlen_zero(i->callid))
5674 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
5675 if (i->rtp)
5676 ast_jb_configure(tmp, &global_jbconf);
5678 /* If the INVITE contains T.38 SDP information set the proper channel variable so a created outgoing call will also have T.38 */
5679 if (i->udptl && i->t38.state == T38_PEER_DIRECT)
5680 pbx_builtin_setvar_helper(tmp, "_T38CALL", "1");
5682 /* Set channel variables for this call from configuration */
5683 for (v = i->chanvars ; v ; v = v->next)
5684 pbx_builtin_setvar_helper(tmp, v->name, v->value);
5686 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
5687 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
5688 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
5689 ast_hangup(tmp);
5690 tmp = NULL;
5693 if (i->do_history)
5694 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
5696 /* Inform manager user about new channel and their SIP call ID */
5697 if (global_callevents)
5698 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
5699 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
5700 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
5702 return tmp;
5705 /*! \brief Reads one line of SIP message body */
5706 static char *get_body_by_line(const char *line, const char *name, int nameLen)
5708 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=')
5709 return ast_skip_blanks(line + nameLen + 1);
5711 return "";
5714 /*! \brief Lookup 'name' in the SDP starting
5715 * at the 'start' line. Returns the matching line, and 'start'
5716 * is updated with the next line number.
5718 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
5720 int len = strlen(name);
5722 while (*start < req->sdp_end) {
5723 const char *r = get_body_by_line(req->line[(*start)++], name, len);
5724 if (r[0] != '\0')
5725 return r;
5728 return "";
5731 /*! \brief Get a line from an SDP message body */
5732 static const char *get_sdp(struct sip_request *req, const char *name)
5734 int dummy = 0;
5736 return get_sdp_iterate(&dummy, req, name);
5739 /*! \brief Get a specific line from the message body */
5740 static char *get_body(struct sip_request *req, char *name)
5742 int x;
5743 int len = strlen(name);
5744 char *r;
5746 for (x = 0; x < req->lines; x++) {
5747 r = get_body_by_line(req->line[x], name, len);
5748 if (r[0] != '\0')
5749 return r;
5752 return "";
5755 /*! \brief Find compressed SIP alias */
5756 static const char *find_alias(const char *name, const char *_default)
5758 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
5759 static const struct cfalias {
5760 char * const fullname;
5761 char * const shortname;
5762 } aliases[] = {
5763 { "Content-Type", "c" },
5764 { "Content-Encoding", "e" },
5765 { "From", "f" },
5766 { "Call-ID", "i" },
5767 { "Contact", "m" },
5768 { "Content-Length", "l" },
5769 { "Subject", "s" },
5770 { "To", "t" },
5771 { "Supported", "k" },
5772 { "Refer-To", "r" },
5773 { "Referred-By", "b" },
5774 { "Allow-Events", "u" },
5775 { "Event", "o" },
5776 { "Via", "v" },
5777 { "Accept-Contact", "a" },
5778 { "Reject-Contact", "j" },
5779 { "Request-Disposition", "d" },
5780 { "Session-Expires", "x" },
5781 { "Identity", "y" },
5782 { "Identity-Info", "n" },
5784 int x;
5786 for (x=0; x<sizeof(aliases) / sizeof(aliases[0]); x++)
5787 if (!strcasecmp(aliases[x].fullname, name))
5788 return aliases[x].shortname;
5790 return _default;
5793 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
5795 int pass;
5798 * Technically you can place arbitrary whitespace both before and after the ':' in
5799 * a header, although RFC3261 clearly says you shouldn't before, and place just
5800 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
5801 * a good idea to say you can do it, and if you can do it, why in the hell would.
5802 * you say you shouldn't.
5803 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
5804 * and we always allow spaces after that for compatibility.
5806 for (pass = 0; name && pass < 2;pass++) {
5807 int x, len = strlen(name);
5808 for (x=*start; x<req->headers; x++) {
5809 if (!strncasecmp(req->header[x], name, len)) {
5810 char *r = req->header[x] + len; /* skip name */
5811 if (pedanticsipchecking)
5812 r = ast_skip_blanks(r);
5814 if (*r == ':') {
5815 *start = x+1;
5816 return ast_skip_blanks(r+1);
5820 if (pass == 0) /* Try aliases */
5821 name = find_alias(name, NULL);
5824 /* Don't return NULL, so get_header is always a valid pointer */
5825 return "";
5828 /*! \brief Get header from SIP request
5829 \return Always return something, so don't check for NULL because it won't happen :-)
5831 static const char *get_header(const struct sip_request *req, const char *name)
5833 int start = 0;
5834 return __get_header(req, name, &start);
5837 /*! \brief Read RTP from network */
5838 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
5840 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
5841 struct ast_frame *f;
5843 if (!p->rtp) {
5844 /* We have no RTP allocated for this channel */
5845 return &ast_null_frame;
5848 switch(ast->fdno) {
5849 case 0:
5850 f = ast_rtp_read(p->rtp); /* RTP Audio */
5851 break;
5852 case 1:
5853 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
5854 break;
5855 case 2:
5856 f = ast_rtp_read(p->vrtp); /* RTP Video */
5857 break;
5858 case 3:
5859 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
5860 break;
5861 case 4:
5862 f = ast_rtp_read(p->trtp); /* RTP Text */
5863 if (sipdebug_text) {
5864 int i;
5865 unsigned char* arr = f->data.ptr;
5866 for (i=0; i < f->datalen; i++)
5867 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
5868 ast_verbose(" -> ");
5869 for (i=0; i < f->datalen; i++)
5870 ast_verbose("%02X ", arr[i]);
5871 ast_verbose("\n");
5873 break;
5874 case 5:
5875 f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
5876 break;
5877 default:
5878 f = &ast_null_frame;
5880 /* Don't forward RFC2833 if we're not supposed to */
5881 if (f && (f->frametype == AST_FRAME_DTMF) &&
5882 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
5883 return &ast_null_frame;
5885 /* We already hold the channel lock */
5886 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
5887 return f;
5889 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
5890 if (!(f->subclass & p->jointcapability)) {
5891 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
5892 ast_getformatname(f->subclass), p->owner->name);
5893 return &ast_null_frame;
5895 ast_debug(1, "Oooh, format changed to %d %s\n",
5896 f->subclass, ast_getformatname(f->subclass));
5897 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
5898 ast_set_read_format(p->owner, p->owner->readformat);
5899 ast_set_write_format(p->owner, p->owner->writeformat);
5902 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
5903 f = ast_dsp_process(p->owner, p->vad, f);
5904 if (f && f->frametype == AST_FRAME_DTMF) {
5905 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
5906 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
5907 *faxdetect = 1;
5908 } else {
5909 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
5914 return f;
5917 /*! \brief Read SIP RTP from channel */
5918 static struct ast_frame *sip_read(struct ast_channel *ast)
5920 struct ast_frame *fr;
5921 struct sip_pvt *p = ast->tech_pvt;
5922 int faxdetected = FALSE;
5924 sip_pvt_lock(p);
5925 fr = sip_rtp_read(ast, p, &faxdetected);
5926 p->lastrtprx = time(NULL);
5928 /* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
5929 /* 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 */
5930 if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
5931 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
5932 if (!p->pendinginvite) {
5933 ast_debug(3, "Sending reinvite on SIP (%s) for T.38 negotiation.\n", ast->name);
5934 change_t38_state(p, T38_LOCAL_REINVITE);
5935 transmit_reinvite_with_sdp(p, TRUE, FALSE);
5937 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
5938 ast_debug(3, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
5939 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
5943 /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
5944 if (fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
5945 fr = &ast_null_frame;
5948 sip_pvt_unlock(p);
5950 return fr;
5954 /*! \brief Generate 32 byte random string for callid's etc */
5955 static char *generate_random_string(char *buf, size_t size)
5957 long val[4];
5958 int x;
5960 for (x=0; x<4; x++)
5961 val[x] = ast_random();
5962 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
5964 return buf;
5967 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
5968 static void build_callid_pvt(struct sip_pvt *pvt)
5970 char buf[33];
5972 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
5974 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
5978 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
5979 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
5981 char buf[33];
5983 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
5985 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
5988 /*! \brief Make our SIP dialog tag */
5989 static void make_our_tag(char *tagbuf, size_t len)
5991 snprintf(tagbuf, len, "as%08lx", ast_random());
5994 /*! \brief Allocate Session-Timers struct w/in dialog */
5995 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
5997 struct sip_st_dlg *stp;
5999 if (p->stimer) {
6000 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
6001 return p->stimer;
6004 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
6005 return NULL;
6007 p->stimer = stp;
6009 stp->st_schedid = -1; /* Session-Timers ast_sched scheduler id */
6011 return p->stimer;
6014 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
6015 * Returns a reference to the object so whoever uses it later must
6016 * remember to release the reference.
6018 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
6019 int useglobal_nat, const int intended_method)
6021 struct sip_pvt *p;
6023 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
6024 return NULL;
6026 if (ast_string_field_init(p, 512)) {
6027 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
6028 ast_free(p);
6029 return NULL;
6032 p->socket.fd = -1;
6033 p->socket.type = SIP_TRANSPORT_UDP;
6034 p->method = intended_method;
6035 p->initid = -1;
6036 p->waitid = -1;
6037 p->autokillid = -1;
6038 p->subscribed = NONE;
6039 p->stateid = -1;
6040 p->sessionversion_remote = -1;
6041 p->session_modify = TRUE;
6042 p->stimer = NULL;
6043 p->prefs = default_prefs; /* Set default codecs for this call */
6045 if (intended_method != SIP_OPTIONS) { /* Peerpoke has it's own system */
6046 p->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
6047 p->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
6050 if (!sin)
6051 p->ourip = internip;
6052 else {
6053 p->sa = *sin;
6054 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
6057 /* Copy global flags to this PVT at setup. */
6058 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
6059 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
6061 p->do_history = recordhistory;
6063 p->branch = ast_random();
6064 make_our_tag(p->tag, sizeof(p->tag));
6065 p->ocseq = INITIAL_CSEQ;
6067 if (sip_methods[intended_method].need_rtp) {
6068 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
6069 /* If the global videosupport flag is on, we always create a RTP interface for video */
6070 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
6071 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
6072 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
6073 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
6074 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
6075 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
6076 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
6077 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
6078 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
6079 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
6080 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
6081 if (p->chanvars) {
6082 ast_variables_destroy(p->chanvars);
6083 p->chanvars = NULL;
6085 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
6086 return NULL;
6088 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
6089 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
6090 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
6091 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
6092 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
6093 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
6094 if (p->vrtp) {
6095 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
6096 ast_rtp_setdtmf(p->vrtp, 0);
6097 ast_rtp_setdtmfcompensate(p->vrtp, 0);
6098 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
6099 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
6100 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
6102 if (p->trtp) {
6103 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
6104 ast_rtp_setdtmf(p->trtp, 0);
6105 ast_rtp_setdtmfcompensate(p->trtp, 0);
6107 if (p->udptl)
6108 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
6109 p->maxcallbitrate = default_maxcallbitrate;
6110 p->autoframing = global_autoframing;
6111 ast_rtp_codec_setpref(p->rtp, &p->prefs);
6114 if (useglobal_nat && sin) {
6115 /* Setup NAT structure according to global settings if we have an address */
6116 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
6117 p->recv = *sin;
6118 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
6121 if (p->method != SIP_REGISTER)
6122 ast_string_field_set(p, fromdomain, default_fromdomain);
6123 build_via(p);
6124 if (!callid)
6125 build_callid_pvt(p);
6126 else
6127 ast_string_field_set(p, callid, callid);
6128 /* Assign default music on hold class */
6129 ast_string_field_set(p, mohinterpret, default_mohinterpret);
6130 ast_string_field_set(p, mohsuggest, default_mohsuggest);
6131 p->capability = global_capability;
6132 p->allowtransfer = global_allowtransfer;
6133 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
6134 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
6135 p->noncodeccapability |= AST_RTP_DTMF;
6136 if (p->udptl) {
6137 ast_copy_flags(&p->t38.t38support, &p->flags[1], SIP_PAGE2_T38SUPPORT);
6138 set_t38_capabilities(p);
6139 p->t38.jointcapability = p->t38.capability;
6141 ast_string_field_set(p, context, default_context);
6142 ast_string_field_set(p, parkinglot, default_parkinglot);
6145 /* Add to active dialog list */
6147 ao2_t_link(dialogs, p, "link pvt into dialogs table");
6149 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");
6150 return p;
6153 /*! \brief argument to the helper function to identify a call */
6154 struct find_call_cb_arg {
6155 enum sipmethod method;
6156 const char *callid;
6157 const char *fromtag;
6158 const char *totag;
6159 const char *tag;
6163 * code to determine whether this is the pvt that we are looking for.
6164 * Return FALSE if not found, true otherwise. p is unlocked.
6166 static int find_call_cb(void *__p, void *__arg, int flags)
6168 struct sip_pvt *p = __p;
6169 struct find_call_cb_arg *arg = __arg;
6170 /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
6171 int found = FALSE;
6173 if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
6174 if (arg->method == SIP_REGISTER)
6175 found = (!strcmp(p->callid, arg->callid));
6176 else
6177 found = (!strcmp(p->callid, arg->callid) &&
6178 (!pedanticsipchecking || ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, arg->tag))) ;
6181 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);
6183 /* If we get a new request within an existing to-tag - check the to tag as well */
6184 if (pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
6185 if (p->tag[0] == '\0' && arg->totag[0]) {
6186 /* We have no to tag, but they have. Wrong dialog */
6187 found = FALSE;
6188 } else if (arg->totag[0]) { /* Both have tags, compare them */
6189 if (strcmp(arg->totag, p->tag)) {
6190 found = FALSE; /* This is not our packet */
6193 if (!found)
6194 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);
6197 return found;
6200 /*! \brief find or create a dialog structure for an incoming SIP message.
6201 * Connect incoming SIP message to current dialog or create new dialog structure
6202 * Returns a reference to the sip_pvt object, remember to give it back once done.
6203 * Called by handle_incoming(), sipsock_read
6205 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
6207 struct sip_pvt *p = NULL;
6208 char *tag = ""; /* note, tag is never NULL */
6209 char totag[128];
6210 char fromtag[128];
6211 struct find_call_cb_arg arg;
6212 const char *callid = get_header(req, "Call-ID");
6213 const char *from = get_header(req, "From");
6214 const char *to = get_header(req, "To");
6215 const char *cseq = get_header(req, "Cseq");
6216 struct sip_pvt *sip_pvt_ptr;
6218 /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
6219 /* get_header always returns non-NULL so we must use ast_strlen_zero() */
6220 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
6221 ast_strlen_zero(from) || ast_strlen_zero(cseq))
6222 return NULL; /* Invalid packet */
6224 arg.method = req->method;
6225 arg.callid = callid;
6226 arg.fromtag = fromtag;
6227 arg.totag = totag;
6228 arg.tag = ""; /* make sure tag is never NULL */
6230 if (pedanticsipchecking) {
6231 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
6232 we need more to identify a branch - so we have to check branch, from
6233 and to tags to identify a call leg.
6234 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
6235 in sip.conf
6237 if (gettag(req, "To", totag, sizeof(totag)))
6238 req->has_to_tag = 1; /* Used in handle_request/response */
6239 gettag(req, "From", fromtag, sizeof(fromtag));
6241 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
6243 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);
6245 /* All messages must always have From: tag */
6246 if (ast_strlen_zero(fromtag)) {
6247 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
6248 return NULL;
6250 /* reject requests that must always have a To: tag */
6251 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
6252 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
6253 return NULL;
6257 restartsearch:
6258 if (!pedanticsipchecking) {
6259 struct sip_pvt tmp_dialog = {
6260 .callid = callid,
6262 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
6263 if (sip_pvt_ptr) { /* well, if we don't find it-- what IS in there? */
6264 /* Found the call */
6265 sip_pvt_lock(sip_pvt_ptr);
6266 return sip_pvt_ptr;
6268 } else { /* in pedantic mode! -- do the fancy linear search */
6269 ao2_lock(dialogs);
6270 p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
6271 if (p) {
6272 if (sip_pvt_trylock(p)) {
6273 ao2_unlock(dialogs);
6274 usleep(1);
6275 goto restartsearch;
6277 ao2_unlock(dialogs);
6278 return p;
6280 ao2_unlock(dialogs);
6283 /* See if the method is capable of creating a dialog */
6284 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
6285 if (intended_method == SIP_REFER) {
6286 /* We do support REFER, but not outside of a dialog yet */
6287 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
6288 } else if (intended_method == SIP_NOTIFY) {
6289 /* We do not support out-of-dialog NOTIFY either,
6290 like voicemail notification, so cancel that early */
6291 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
6292 } else {
6293 /* Ok, time to create a new SIP dialog object, a pvt */
6294 if ((p = sip_alloc(callid, sin, 1, intended_method))) {
6295 /* Ok, we've created a dialog, let's go and process it */
6296 sip_pvt_lock(p);
6297 } else {
6298 /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
6299 getting a dialog from sip_alloc.
6301 Without a dialog we can't retransmit and handle ACKs and all that, but at least
6302 send an error message.
6304 Sorry, we apologize for the inconvienience
6306 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
6307 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
6310 return p; /* can be NULL */
6311 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
6312 /* A method we do not support, let's take it on the volley */
6313 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
6314 ast_debug(2, "Got a request with unsupported SIP method.\n");
6315 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
6316 /* This is a request outside of a dialog that we don't know about */
6317 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
6318 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
6320 /* We do not respond to responses for dialogs that we don't know about, we just drop
6321 the session quickly */
6322 if (intended_method == SIP_RESPONSE)
6323 ast_debug(2, "That's odd... Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
6325 return NULL;
6328 /*! \brief Parse register=> line in sip.conf and add to registry */
6329 static int sip_register(const char *value, int lineno)
6331 struct sip_registry *reg;
6332 int portnum = 0;
6333 enum sip_transport transport = SIP_TRANSPORT_UDP;
6334 char buf[256] = "";
6335 char *username = NULL;
6336 char *hostname=NULL, *secret=NULL, *authuser=NULL, *expiry=NULL;
6337 char *porta=NULL;
6338 char *callback=NULL;
6339 char *trans=NULL;
6341 if (!value)
6342 return -1;
6344 ast_copy_string(buf, value, sizeof(buf));
6346 username = strstr(buf, "://");
6348 if (username) {
6349 *username = '\0';
6350 username += 3;
6352 trans = buf;
6354 if (!strcasecmp(trans, "udp"))
6355 transport = SIP_TRANSPORT_UDP;
6356 else if (!strcasecmp(trans, "tcp"))
6357 transport = SIP_TRANSPORT_TCP;
6358 else if (!strcasecmp(trans, "tls"))
6359 transport = SIP_TRANSPORT_TLS;
6360 else
6361 ast_log(LOG_WARNING, "'%s' is not a valid transport value for registration '%s' at line '%d'\n", trans, value, lineno);
6362 } else {
6363 username = buf;
6364 ast_debug(1, "no trans\n");
6367 /* First split around the last '@' then parse the two components. */
6368 hostname = strrchr(username, '@'); /* allow @ in the first part */
6369 if (hostname)
6370 *hostname++ = '\0';
6371 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
6372 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact][~expiry] at line %d\n", lineno);
6373 return -1;
6375 /* split user[:secret[:authuser]] */
6376 secret = strchr(username, ':');
6377 if (secret) {
6378 *secret++ = '\0';
6379 authuser = strchr(secret, ':');
6380 if (authuser)
6381 *authuser++ = '\0';
6383 /* split host[:port][/contact] */
6384 expiry = strchr(hostname, '~');
6385 if (expiry)
6386 *expiry++ = '\0';
6387 callback = strchr(hostname, '/');
6388 if (callback)
6389 *callback++ = '\0';
6390 if (ast_strlen_zero(callback))
6391 callback = "s";
6392 porta = strchr(hostname, ':');
6393 if (porta) {
6394 *porta++ = '\0';
6395 portnum = atoi(porta);
6396 if (portnum == 0) {
6397 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
6398 return -1;
6401 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
6402 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
6403 return -1;
6406 if (ast_string_field_init(reg, 256)) {
6407 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
6408 ast_free(reg);
6409 return -1;
6412 ast_atomic_fetchadd_int(&regobjs, 1);
6413 ASTOBJ_INIT(reg);
6414 ast_string_field_set(reg, callback, callback);
6415 if (!ast_strlen_zero(username))
6416 ast_string_field_set(reg, username, username);
6417 if (hostname)
6418 ast_string_field_set(reg, hostname, hostname);
6419 if (authuser)
6420 ast_string_field_set(reg, authuser, authuser);
6421 if (secret)
6422 ast_string_field_set(reg, secret, secret);
6423 reg->transport = transport;
6424 reg->expire = -1;
6425 reg->expiry = (expiry ? atoi(expiry) : default_expiry);
6426 reg->timeout = -1;
6427 reg->refresh = reg->expiry;
6428 reg->portno = portnum;
6429 reg->callid_valid = FALSE;
6430 reg->ocseq = INITIAL_CSEQ;
6431 ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
6432 registry_unref(reg, "unref the reg pointer"); /* release the reference given by ASTOBJ_INIT. The container has another reference */
6433 return 0;
6436 /*! \brief Parse multiline SIP headers into one header
6437 This is enabled if pedanticsipchecking is enabled */
6438 static int lws2sws(char *msgbuf, int len)
6440 int h = 0, t = 0;
6441 int lws = 0;
6443 for (; h < len;) {
6444 /* Eliminate all CRs */
6445 if (msgbuf[h] == '\r') {
6446 h++;
6447 continue;
6449 /* Check for end-of-line */
6450 if (msgbuf[h] == '\n') {
6451 /* Check for end-of-message */
6452 if (h + 1 == len)
6453 break;
6454 /* Check for a continuation line */
6455 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
6456 /* Merge continuation line */
6457 h++;
6458 continue;
6460 /* Propagate LF and start new line */
6461 msgbuf[t++] = msgbuf[h++];
6462 lws = 0;
6463 continue;
6465 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
6466 if (lws) {
6467 h++;
6468 continue;
6470 msgbuf[t++] = msgbuf[h++];
6471 lws = 1;
6472 continue;
6474 msgbuf[t++] = msgbuf[h++];
6475 if (lws)
6476 lws = 0;
6478 msgbuf[t] = '\0';
6479 return t;
6482 /*! \brief Parse a SIP message
6483 \note this function is used both on incoming and outgoing packets
6485 static int parse_request(struct sip_request *req)
6487 char *c = req->data->str, **dst = req->header;
6488 int i = 0, lim = SIP_MAX_HEADERS - 1;
6490 req->header[0] = c;
6491 req->headers = -1; /* mark that we are working on the header */
6492 for (; *c; c++) {
6493 if (*c == '\r') /* remove \r */
6494 *c = '\0';
6495 else if (*c == '\n') { /* end of this line */
6496 *c = '\0';
6497 if (sipdebug)
6498 ast_debug(4, "%7s %2d [%3d]: %s\n",
6499 req->headers < 0 ? "Header" : "Body",
6500 i, (int)strlen(dst[i]), dst[i]);
6501 if (ast_strlen_zero(dst[i]) && req->headers < 0) {
6502 req->headers = i; /* record number of header lines */
6503 dst = req->line; /* start working on the body */
6504 i = 0;
6505 lim = SIP_MAX_LINES - 1;
6506 } else { /* move to next line, check for overflows */
6507 if (i++ >= lim)
6508 break;
6510 dst[i] = c + 1; /* record start of next line */
6513 /* Check for last header without CRLF. The RFC for SDP requires CRLF,
6514 but since some devices send without, we'll be generous in what we accept.
6516 if (!ast_strlen_zero(dst[i])) {
6517 if (sipdebug)
6518 ast_debug(4, "%7s %2d [%3d]: %s\n",
6519 req->headers < 0 ? "Header" : "Body",
6520 i, (int)strlen(dst[i]), dst[i]);
6521 i++;
6523 /* update count of header or body lines */
6524 if (req->headers >= 0) /* we are in the body */
6525 req->lines = i;
6526 else { /* no body */
6527 req->headers = i;
6528 req->lines = 0;
6529 req->line[0] = "";
6532 if (*c)
6533 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
6534 /* Split up the first line parts */
6535 return determine_firstline_parts(req);
6539 \brief Determine whether a SIP message contains an SDP in its body
6540 \param req the SIP request to process
6541 \return 1 if SDP found, 0 if not found
6543 Also updates req->sdp_start and req->sdp_end to indicate where the SDP
6544 lives in the message body.
6546 static int find_sdp(struct sip_request *req)
6548 const char *content_type;
6549 const char *content_length;
6550 const char *search;
6551 char *boundary;
6552 unsigned int x;
6553 int boundaryisquoted = FALSE;
6554 int found_application_sdp = FALSE;
6555 int found_end_of_headers = FALSE;
6557 content_length = get_header(req, "Content-Length");
6559 if (!ast_strlen_zero(content_length)) {
6560 if (sscanf(content_length, "%ud", &x) != 1) {
6561 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
6562 return 0;
6565 /* Content-Length of zero means there can't possibly be an
6566 SDP here, even if the Content-Type says there is */
6567 if (x == 0)
6568 return 0;
6571 content_type = get_header(req, "Content-Type");
6573 /* if the body contains only SDP, this is easy */
6574 if (!strncasecmp(content_type, "application/sdp", 15)) {
6575 req->sdp_start = 0;
6576 req->sdp_end = req->lines;
6577 return req->lines ? 1 : 0;
6580 /* if it's not multipart/mixed, there cannot be an SDP */
6581 if (strncasecmp(content_type, "multipart/mixed", 15))
6582 return 0;
6584 /* if there is no boundary marker, it's invalid */
6585 if ((search = strcasestr(content_type, ";boundary=")))
6586 search += 10;
6587 else if ((search = strcasestr(content_type, "; boundary=")))
6588 search += 11;
6589 else
6590 return 0;
6592 if (ast_strlen_zero(search))
6593 return 0;
6595 /* If the boundary is quoted with ", remove quote */
6596 if (*search == '\"') {
6597 search++;
6598 boundaryisquoted = TRUE;
6601 /* make a duplicate of the string, with two extra characters
6602 at the beginning */
6603 boundary = ast_strdupa(search - 2);
6604 boundary[0] = boundary[1] = '-';
6605 /* Remove final quote */
6606 if (boundaryisquoted)
6607 boundary[strlen(boundary) - 1] = '\0';
6609 /* search for the boundary marker, the empty line delimiting headers from
6610 sdp part and the end boundry if it exists */
6612 for (x = 0; x < (req->lines ); x++) {
6613 if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
6614 if(found_application_sdp && found_end_of_headers){
6615 req->sdp_end = x-1;
6616 return 1;
6618 found_application_sdp = FALSE;
6620 if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
6621 found_application_sdp = TRUE;
6623 if(strlen(req->line[x]) == 0 ){
6624 if(found_application_sdp && !found_end_of_headers){
6625 req->sdp_start = x;
6626 found_end_of_headers = TRUE;
6630 if(found_application_sdp && found_end_of_headers) {
6631 req->sdp_end = x;
6632 return TRUE;
6634 return FALSE;
6637 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
6638 If offer is rejected, we will not change any properties of the call
6639 Return 0 on success, a negative value on errors.
6640 Must be called after find_sdp().
6642 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
6644 const char *m; /* SDP media offer */
6645 const char *c;
6646 const char *a;
6647 const char *o; /* Pointer to o= line */
6648 char *o_copy; /* Copy of o= line */
6649 char *token;
6650 char host[258];
6651 int len = -1;
6652 int portno = -1; /*!< RTP Audio port number */
6653 int vportno = -1; /*!< RTP Video port number */
6654 int tportno = -1; /*!< RTP Text port number */
6655 int udptlportno = -1;
6656 int peert38capability = 0;
6657 char s[256];
6658 int old = 0;
6660 /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
6661 int peercapability = 0, peernoncodeccapability = 0;
6662 int vpeercapability = 0, vpeernoncodeccapability = 0;
6663 int tpeercapability = 0, tpeernoncodeccapability = 0;
6664 struct sockaddr_in sin; /*!< media socket address */
6665 struct sockaddr_in vsin; /*!< Video socket address */
6666 struct sockaddr_in tsin; /*!< Text socket address */
6668 const char *codecs;
6669 struct hostent *hp; /*!< RTP Audio host IP */
6670 struct hostent *vhp = NULL; /*!< RTP video host IP */
6671 struct hostent *thp = NULL; /*!< RTP text host IP */
6672 struct ast_hostent audiohp;
6673 struct ast_hostent videohp;
6674 struct ast_hostent texthp;
6675 int codec;
6676 int destiterator = 0;
6677 int iterator;
6678 int sendonly = -1;
6679 int numberofports;
6680 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp; /* Buffers for codec handling */
6681 int newjointcapability; /* Negotiated capability */
6682 int newpeercapability;
6683 int newnoncodeccapability;
6684 int numberofmediastreams = 0;
6685 int debug = sip_debug_test_pvt(p);
6687 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
6688 int last_rtpmap_codec=0;
6690 char buf[SIPBUFSIZE];
6691 int rua_version;
6693 int red_data_pt[10];
6694 int red_num_gen = 0;
6695 int red_pt = 0;
6697 char *red_cp; /* For T.140 red */
6698 char red_fmtp[100] = "empty"; /* For T.140 red */
6700 if (!p->rtp) {
6701 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
6702 return -1;
6705 /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
6706 #ifdef LOW_MEMORY
6707 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
6708 #else
6709 newaudiortp = alloca(ast_rtp_alloc_size());
6710 #endif
6711 memset(newaudiortp, 0, ast_rtp_alloc_size());
6712 ast_rtp_new_init(newaudiortp);
6713 ast_rtp_pt_clear(newaudiortp);
6715 #ifdef LOW_MEMORY
6716 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
6717 #else
6718 newvideortp = alloca(ast_rtp_alloc_size());
6719 #endif
6720 memset(newvideortp, 0, ast_rtp_alloc_size());
6721 ast_rtp_new_init(newvideortp);
6722 ast_rtp_pt_clear(newvideortp);
6724 #ifdef LOW_MEMORY
6725 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
6726 #else
6727 newtextrtp = alloca(ast_rtp_alloc_size());
6728 #endif
6729 memset(newtextrtp, 0, ast_rtp_alloc_size());
6730 ast_rtp_new_init(newtextrtp);
6731 ast_rtp_pt_clear(newtextrtp);
6733 /* Update our last rtprx when we receive an SDP, too */
6734 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
6736 /* Store the SDP version number of remote UA. This will allow us to
6737 distinguish between session modifications and session refreshes. If
6738 the remote UA does not send an incremented SDP version number in a
6739 subsequent RE-INVITE then that means its not changing media session.
6740 The RE-INVITE may have been sent to update connected party, remote
6741 target or to refresh the session (Session-Timers). Asterisk must not
6742 change media session and increment its own version number in answer
6743 SDP in this case. */
6745 o = get_sdp(req, "o");
6746 if (ast_strlen_zero(o)) {
6747 ast_log(LOG_WARNING, "SDP sytax error. SDP without an o= line\n");
6748 return -1;
6751 o_copy = ast_strdupa(o);
6752 token = strsep(&o_copy, " "); /* Skip username */
6753 if (!o_copy) {
6754 ast_log(LOG_WARNING, "SDP sytax error in o= line username\n");
6755 return -1;
6757 token = strsep(&o_copy, " "); /* Skip session-id */
6758 if (!o_copy) {
6759 ast_log(LOG_WARNING, "SDP sytax error in o= line session-id\n");
6760 return -1;
6762 token = strsep(&o_copy, " "); /* Version */
6763 if (!o_copy) {
6764 ast_log(LOG_WARNING, "SDP sytax error in o= line\n");
6765 return -1;
6767 if (!sscanf(token, "%d", &rua_version)) {
6768 ast_log(LOG_WARNING, "SDP sytax error in o= line version\n");
6769 return -1;
6772 if (p->sessionversion_remote < 0 || p->sessionversion_remote != rua_version) {
6773 p->sessionversion_remote = rua_version;
6774 p->session_modify = TRUE;
6775 } else if (p->sessionversion_remote == rua_version) {
6776 p->session_modify = FALSE;
6777 ast_debug(2, "SDP version number same as previous SDP\n");
6778 return 0;
6781 /* Try to find first media stream */
6782 m = get_sdp(req, "m");
6783 destiterator = req->sdp_start;
6784 c = get_sdp_iterate(&destiterator, req, "c");
6785 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
6786 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
6787 return -1;
6790 /* Check for IPv4 address (not IPv6 yet) */
6791 if (sscanf(c, "IN IP4 %256s", host) != 1) {
6792 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
6793 return -1;
6796 /* XXX This could block for a long time, and block the main thread! XXX */
6797 hp = ast_gethostbyname(host, &audiohp);
6798 if (!hp) {
6799 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
6800 return -1;
6802 vhp = hp; /* Copy to video address as default too */
6803 thp = hp; /* Copy to text address as default too */
6805 iterator = req->sdp_start;
6806 /* default: novideo and notext set */
6807 p->novideo = TRUE;
6808 p->notext = TRUE;
6810 if (p->vrtp)
6811 ast_rtp_pt_clear(newvideortp); /* Must be cleared in case no m=video line exists */
6813 if (p->trtp)
6814 ast_rtp_pt_clear(newtextrtp); /* Must be cleared in case no m=text line exists */
6816 /* Find media streams in this SDP offer */
6817 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
6818 int x;
6819 int audio = FALSE;
6820 int video = FALSE;
6821 int text = FALSE;
6823 numberofports = 1;
6824 if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
6825 (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
6826 audio = TRUE;
6827 numberofmediastreams++;
6828 /* Found audio stream in this media definition */
6829 portno = x;
6830 /* Scan through the RTP payload types specified in a "m=" line: */
6831 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
6832 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
6833 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
6834 return -1;
6836 if (debug)
6837 ast_verbose("Found RTP audio format %d\n", codec);
6838 ast_rtp_set_m_type(newaudiortp, codec);
6840 } else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
6841 (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
6842 video = TRUE;
6843 p->novideo = FALSE;
6844 numberofmediastreams++;
6845 vportno = x;
6846 /* Scan through the RTP payload types specified in a "m=" line: */
6847 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
6848 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
6849 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
6850 return -1;
6852 if (debug)
6853 ast_verbose("Found RTP video format %d\n", codec);
6854 ast_rtp_set_m_type(newvideortp, codec);
6856 } else if ((sscanf(m, "text %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
6857 (sscanf(m, "text %d RTP/AVP %n", &x, &len) == 1)) {
6858 text = TRUE;
6859 p->notext = FALSE;
6860 numberofmediastreams++;
6861 tportno = x;
6862 /* Scan through the RTP payload types specified in a "m=" line: */
6863 for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
6864 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
6865 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
6866 return -1;
6868 if (debug)
6869 ast_verbose("Found RTP text format %d\n", codec);
6870 ast_rtp_set_m_type(newtextrtp, codec);
6872 } else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) ||
6873 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
6874 if (debug)
6875 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
6876 udptlportno = x;
6877 numberofmediastreams++;
6878 } else
6879 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
6880 if (numberofports > 1)
6881 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
6884 /* Check for Media-description-level-address for audio */
6885 c = get_sdp_iterate(&destiterator, req, "c");
6886 if (!ast_strlen_zero(c)) {
6887 if (sscanf(c, "IN IP4 %256s", host) != 1) {
6888 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
6889 } else {
6890 /* XXX This could block for a long time, and block the main thread! XXX */
6891 if (audio) {
6892 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
6893 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
6894 return -2;
6896 } else if (video) {
6897 if (!(vhp = ast_gethostbyname(host, &videohp))) {
6898 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
6899 return -2;
6901 } else if (text) {
6902 if (!(thp = ast_gethostbyname(host, &texthp))) {
6903 ast_log(LOG_WARNING, "Unable to lookup RTP text host in secondary c= line, '%s'\n", c);
6904 return -2;
6911 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
6912 /* No acceptable offer found in SDP - we have no ports */
6913 /* Do not change RTP or VRTP if this is a re-invite */
6914 return -2;
6916 if (numberofmediastreams > 3)
6917 /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
6918 return -3;
6920 /* RTP addresses and ports for audio and video */
6921 sin.sin_family = AF_INET;
6922 vsin.sin_family = AF_INET;
6923 tsin.sin_family = AF_INET;
6924 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
6925 if (vhp)
6926 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
6927 if (thp)
6928 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
6930 /* Setup UDPTL port number */
6931 if (p->udptl) {
6932 if (udptlportno > 0) {
6933 sin.sin_port = htons(udptlportno);
6934 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
6935 struct sockaddr_in peer;
6936 ast_rtp_get_peer(p->rtp, &peer);
6937 if (peer.sin_addr.s_addr) {
6938 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(&sin.sin_addr));
6939 if (debug) {
6940 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));
6944 ast_udptl_set_peer(p->udptl, &sin);
6945 if (debug)
6946 ast_debug(1, "Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6947 } else {
6948 ast_udptl_stop(p->udptl);
6949 if (debug)
6950 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
6955 if (p->rtp) {
6956 if (portno > 0) {
6957 sin.sin_port = htons(portno);
6958 ast_rtp_set_peer(p->rtp, &sin);
6959 if (debug)
6960 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6961 } else {
6962 if (udptlportno > 0) {
6963 if (debug)
6964 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
6965 } else {
6966 ast_rtp_stop(p->rtp);
6967 if (debug)
6968 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
6972 /* Setup video port number, assumes we have audio */
6973 if (vportno != -1)
6974 vsin.sin_port = htons(vportno);
6976 /* Setup text port number, assumes we have audio */
6977 if (tportno != -1)
6978 tsin.sin_port = htons(tportno);
6980 /* Next, scan through each "a=xxxx:" line, noting each
6981 * specified RTP payload type (with corresponding MIME subtype):
6983 /* XXX This needs to be done per media stream, since it's media stream specific */
6984 iterator = req->sdp_start;
6985 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
6986 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
6987 if (option_debug > 1) {
6988 int breakout = FALSE;
6990 /* If we're debugging, check for unsupported sdp options */
6991 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
6992 if (debug)
6993 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
6994 breakout = TRUE;
6995 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
6996 /* Format parameters: Not supported */
6997 /* Note: This is used for codec parameters, like bitrate for
6998 G722 and video formats for H263 and H264
6999 See RFC2327 for an example */
7000 if (debug)
7001 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
7002 breakout = TRUE;
7003 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
7004 /* Video stuff: Not supported */
7005 if (debug)
7006 ast_verbose("Got unsupported a:framerate in SDP offer \n");
7007 breakout = TRUE;
7008 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
7009 /* Video stuff: Not supported */
7010 if (debug)
7011 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
7012 breakout = TRUE;
7013 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
7014 /* SRTP stuff, not yet supported */
7015 if (debug)
7016 ast_verbose("Got unsupported a:crypto in SDP offer \n");
7017 breakout = TRUE;
7019 if (breakout) /* We have a match, skip to next header */
7020 continue;
7022 if (!strcasecmp(a, "sendonly")) {
7023 if (sendonly == -1)
7024 sendonly = 1;
7025 continue;
7026 } else if (!strcasecmp(a, "inactive")) {
7027 if (sendonly == -1)
7028 sendonly = 2;
7029 continue;
7030 } else if (!strcasecmp(a, "sendrecv")) {
7031 if (sendonly == -1)
7032 sendonly = 0;
7033 continue;
7034 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
7035 char *tmp = strrchr(a, ':');
7036 long int framing = 0;
7037 if (tmp) {
7038 tmp++;
7039 framing = strtol(tmp, NULL, 10);
7040 if (framing == LONG_MIN || framing == LONG_MAX) {
7041 framing = 0;
7042 ast_debug(1, "Can't read framing from SDP: %s\n", a);
7045 if (framing && p->autoframing) {
7046 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
7047 int codec_n;
7048 int format = 0;
7049 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
7050 format = ast_rtp_codec_getformat(codec_n);
7051 if (!format) /* non-codec or not found */
7052 continue;
7053 if (option_debug)
7054 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
7055 ast_codec_pref_setsize(pref, format, framing);
7057 ast_rtp_codec_setpref(p->rtp, pref);
7059 continue;
7061 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
7062 /* count numbers of generations in fmtp */
7063 red_cp = &red_fmtp[strlen(red_fmtp)];
7064 strncpy(red_fmtp, a, 100);
7066 sscanf(red_cp, "%u", &red_data_pt[red_num_gen]);
7067 red_cp = strtok(red_cp, "/");
7068 while (red_cp && red_num_gen++ < RED_MAX_GENERATION) {
7069 sscanf(red_cp, "%u", &red_data_pt[red_num_gen]);
7070 red_cp = strtok(NULL, "/");
7072 red_cp = red_fmtp;
7074 } else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
7075 /* We have a rtpmap to handle */
7077 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
7078 /* Note: should really look at the 'freq' and '#chans' params too */
7079 /* Note: This should all be done in the context of the m= above */
7080 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) { /* Video */
7081 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
7082 if (debug)
7083 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
7084 found_rtpmap_codecs[last_rtpmap_codec] = codec;
7085 last_rtpmap_codec++;
7086 } else {
7087 ast_rtp_unset_m_type(newvideortp, codec);
7088 if (debug)
7089 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
7091 } else if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
7092 if (p->trtp) {
7093 /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
7094 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
7096 } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
7097 if (p->trtp) {
7098 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
7099 red_pt = codec;
7100 sprintf(red_fmtp, "fmtp:%d ", red_pt);
7102 if (debug)
7103 ast_verbose("Red submimetype has payload type: %d\n", red_pt);
7105 } else { /* Must be audio?? */
7106 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
7107 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
7108 if (debug)
7109 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
7110 found_rtpmap_codecs[last_rtpmap_codec] = codec;
7111 last_rtpmap_codec++;
7112 } else {
7113 ast_rtp_unset_m_type(newaudiortp, codec);
7114 if (debug)
7115 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
7118 } else {
7119 if (debug)
7120 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
7126 if (udptlportno != -1) {
7127 int found = 0, x;
7129 old = 0;
7131 /* Scan trough the a= lines for T38 attributes and set apropriate fileds */
7132 iterator = req->sdp_start;
7133 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
7134 if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
7135 found = 1;
7136 ast_debug(3, "MaxBufferSize:%d\n", x);
7137 } else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
7138 found = 1;
7139 ast_debug(3, "T38MaxBitRate: %d\n", x);
7140 switch (x) {
7141 case 14400:
7142 peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7143 break;
7144 case 12000:
7145 peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7146 break;
7147 case 9600:
7148 peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7149 break;
7150 case 7200:
7151 peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
7152 break;
7153 case 4800:
7154 peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
7155 break;
7156 case 2400:
7157 peert38capability |= T38FAX_RATE_2400;
7158 break;
7160 } else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
7161 found = 1;
7162 ast_debug(3, "FaxVersion: %d\n", x);
7163 if (x == 0)
7164 peert38capability |= T38FAX_VERSION_0;
7165 else if (x == 1)
7166 peert38capability |= T38FAX_VERSION_1;
7167 } else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
7168 found = 1;
7169 ast_debug(3, "FaxMaxDatagram: %d\n", x);
7170 ast_udptl_set_far_max_datagram(p->udptl, x);
7171 ast_udptl_set_local_max_datagram(p->udptl, x);
7172 } else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
7173 found = 1;
7174 ast_debug(3, "FillBitRemoval: %d\n", x);
7175 if (x == 1)
7176 peert38capability |= T38FAX_FILL_BIT_REMOVAL;
7177 } else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
7178 found = 1;
7179 ast_debug(3, "Transcoding MMR: %d\n", x);
7180 if (x == 1)
7181 peert38capability |= T38FAX_TRANSCODING_MMR;
7183 if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
7184 found = 1;
7185 ast_debug(3, "Transcoding JBIG: %d\n", x);
7186 if (x == 1)
7187 peert38capability |= T38FAX_TRANSCODING_JBIG;
7188 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
7189 found = 1;
7190 ast_debug(3, "RateManagement: %s\n", s);
7191 if (!strcasecmp(s, "localTCF"))
7192 peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
7193 else if (!strcasecmp(s, "transferredTCF"))
7194 peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
7195 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
7196 found = 1;
7197 ast_debug(3, "UDP EC: %s\n", s);
7198 if (!strcasecmp(s, "t38UDPRedundancy")) {
7199 peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
7200 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
7201 } else if (!strcasecmp(s, "t38UDPFEC")) {
7202 peert38capability |= T38FAX_UDP_EC_FEC;
7203 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
7204 } else {
7205 peert38capability |= T38FAX_UDP_EC_NONE;
7206 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
7210 if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
7211 p->t38.peercapability = peert38capability;
7212 p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
7213 peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
7214 p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
7216 if (debug)
7217 ast_debug(1, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
7218 p->t38.capability,
7219 p->t38.peercapability,
7220 p->t38.jointcapability);
7222 /* Remote party offers T38, we need to update state */
7223 if (t38action == SDP_T38_ACCEPT) {
7224 if (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)
7225 change_t38_state(p, T38_ENABLED);
7226 } else if (t38action == SDP_T38_INITIATE) {
7227 if (p->owner && p->lastinvite) {
7228 change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
7229 } else {
7230 change_t38_state(p, T38_PEER_DIRECT); /* T38 Offered directly from peer in first invite */
7233 } else {
7234 change_t38_state(p, T38_DISABLED);
7237 /* Now gather all of the codecs that we are asked for: */
7238 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
7239 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
7240 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
7242 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
7243 newpeercapability = (peercapability | vpeercapability | tpeercapability);
7244 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
7247 if (debug) {
7248 /* shame on whoever coded this.... */
7249 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
7251 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
7252 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
7253 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
7254 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
7255 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
7256 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
7258 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
7259 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
7260 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
7261 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
7263 if (!newjointcapability) {
7264 /* If T.38 was not negotiated either, totally bail out... */
7265 if (!p->t38.jointcapability || !udptlportno) {
7266 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
7267 /* Do NOT Change current setting */
7268 return -1;
7269 } else {
7270 ast_debug(3, "Have T.38 but no audio codecs, accepting offer anyway\n");
7271 return 0;
7275 /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
7276 they are acceptable */
7277 p->jointcapability = newjointcapability; /* Our joint codec profile for this call */
7278 p->peercapability = newpeercapability; /* The other sides capability in latest offer */
7279 p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
7281 if (p->jointcapability & AST_FORMAT_T140RED) {
7282 p->red = 1;
7283 rtp_red_init(p->trtp, 300, red_data_pt, 2);
7284 } else {
7285 p->red = 0;
7288 ast_rtp_pt_copy(p->rtp, newaudiortp);
7289 if (p->vrtp)
7290 ast_rtp_pt_copy(p->vrtp, newvideortp);
7291 if (p->trtp)
7292 ast_rtp_pt_copy(p->trtp, newtextrtp);
7294 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
7295 ast_clear_flag(&p->flags[0], SIP_DTMF);
7296 if (newnoncodeccapability & AST_RTP_DTMF) {
7297 /* XXX Would it be reasonable to drop the DSP at this point? XXX */
7298 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
7299 /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
7300 ast_rtp_setdtmf(p->rtp, 1);
7301 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
7302 } else {
7303 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
7307 /* Setup audio port number */
7308 if (p->rtp && sin.sin_port) {
7309 ast_rtp_set_peer(p->rtp, &sin);
7310 if (debug)
7311 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
7314 /* Setup video port number */
7315 if (p->vrtp && vsin.sin_port) {
7316 ast_rtp_set_peer(p->vrtp, &vsin);
7317 if (debug)
7318 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
7321 /* Setup text port number */
7322 if (p->trtp && tsin.sin_port) {
7323 ast_rtp_set_peer(p->trtp, &tsin);
7324 if (debug)
7325 ast_verbose("Peer text RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
7328 /* Ok, we're going with this offer */
7329 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
7331 if (!p->owner) /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
7332 return 0;
7334 ast_debug(4, "We have an owner, now see if we need to change this call\n");
7336 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
7337 if (debug) {
7338 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
7339 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
7340 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
7341 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
7343 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
7344 ast_set_read_format(p->owner, p->owner->readformat);
7345 ast_set_write_format(p->owner, p->owner->writeformat);
7348 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
7349 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
7350 /* Activate a re-invite */
7351 ast_queue_frame(p->owner, &ast_null_frame);
7352 /* Queue Manager Unhold event */
7353 append_history(p, "Unhold", "%s", req->data->str);
7354 if (global_callevents)
7355 manager_event(EVENT_FLAG_CALL, "Hold",
7356 "Status: Off\r\n"
7357 "Channel: %s\r\n"
7358 "Uniqueid: %s\r\n",
7359 p->owner->name,
7360 p->owner->uniqueid);
7361 if (global_notifyhold)
7362 sip_peer_hold(p, FALSE);
7363 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
7364 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
7365 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
7366 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
7367 S_OR(p->mohsuggest, NULL),
7368 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
7369 if (sendonly)
7370 ast_rtp_stop(p->rtp);
7371 /* RTCP needs to go ahead, even if we're on hold!!! */
7372 /* Activate a re-invite */
7373 ast_queue_frame(p->owner, &ast_null_frame);
7374 /* Queue Manager Hold event */
7375 append_history(p, "Hold", "%s", req->data->str);
7376 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
7377 manager_event(EVENT_FLAG_CALL, "Hold",
7378 "Status: On\r\n"
7379 "Channel: %s\r\n"
7380 "Uniqueid: %s\r\n",
7381 p->owner->name,
7382 p->owner->uniqueid);
7384 if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
7385 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
7386 else if (sendonly == 2) /* Inactive stream */
7387 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
7388 else
7389 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
7390 if (global_notifyhold && !already_on_hold)
7391 sip_peer_hold(p, TRUE);
7394 return 0;
7397 #ifdef LOW_MEMORY
7398 static void ts_ast_rtp_destroy(void *data)
7400 struct ast_rtp *tmp = data;
7401 ast_rtp_destroy(tmp);
7403 #endif
7405 /*! \brief Add header to SIP message */
7406 static int add_header(struct sip_request *req, const char *var, const char *value)
7408 if (req->headers == SIP_MAX_HEADERS) {
7409 ast_log(LOG_WARNING, "Out of SIP header space\n");
7410 return -1;
7413 if (req->lines) {
7414 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
7415 return -1;
7418 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
7419 req->header[req->headers] = req->data->str + req->len;
7421 if (compactheaders)
7422 var = find_alias(var, var);
7423 req->len += strlen(req->header[req->headers]);
7424 req->headers++;
7426 return 0;
7429 /*! \brief Add 'Content-Length' header to SIP message */
7430 static int add_header_contentLength(struct sip_request *req, int len)
7432 char clen[10];
7434 snprintf(clen, sizeof(clen), "%d", len);
7435 return add_header(req, "Content-Length", clen);
7438 /*! \brief Add content (not header) to SIP message */
7439 static int add_line(struct sip_request *req, const char *line)
7441 if (req->lines == SIP_MAX_LINES) {
7442 ast_log(LOG_WARNING, "Out of SIP line space\n");
7443 return -1;
7445 if (!req->lines)
7446 /* Add extra empty return */
7447 req->len += ast_str_append(&req->data, 0, "\r\n");
7448 if (req->len >= sizeof(req->data->str) - 4) {
7449 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
7450 return -1;
7452 req->line[req->lines] = req->data->str + req->len;
7453 ast_str_append(&req->data, 0, "%s", line);
7454 req->len += strlen(req->line[req->lines]);
7455 req->lines++;
7456 return 0;
7459 /*! \brief Copy one header field from one request to another */
7460 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
7462 const char *tmp = get_header(orig, field);
7464 if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
7465 return add_header(req, field, tmp);
7466 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
7467 return -1;
7470 /*! \brief Copy all headers from one request to another */
7471 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
7473 int start = 0;
7474 int copied = 0;
7475 for (;;) {
7476 const char *tmp = __get_header(orig, field, &start);
7478 if (ast_strlen_zero(tmp))
7479 break;
7480 /* Add what we're responding to */
7481 add_header(req, field, tmp);
7482 copied++;
7484 return copied ? 0 : -1;
7487 /*! \brief Copy SIP VIA Headers from the request to the response
7488 \note If the client indicates that it wishes to know the port we received from,
7489 it adds ;rport without an argument to the topmost via header. We need to
7490 add the port number (from our point of view) to that parameter.
7491 \verbatim
7492 We always add ;received=<ip address> to the topmost via header.
7493 \endverbatim
7494 Received: RFC 3261, rport RFC 3581 */
7495 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
7497 int copied = 0;
7498 int start = 0;
7500 for (;;) {
7501 char new[512];
7502 const char *oh = __get_header(orig, field, &start);
7504 if (ast_strlen_zero(oh))
7505 break;
7507 if (!copied) { /* Only check for empty rport in topmost via header */
7508 char leftmost[512], *others, *rport;
7510 /* Only work on leftmost value */
7511 ast_copy_string(leftmost, oh, sizeof(leftmost));
7512 others = strchr(leftmost, ',');
7513 if (others)
7514 *others++ = '\0';
7516 /* Find ;rport; (empty request) */
7517 rport = strstr(leftmost, ";rport");
7518 if (rport && *(rport+6) == '=')
7519 rport = NULL; /* We already have a parameter to rport */
7521 /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting) */
7522 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
7523 /* We need to add received port - rport */
7524 char *end;
7526 rport = strstr(leftmost, ";rport");
7528 if (rport) {
7529 end = strchr(rport + 1, ';');
7530 if (end)
7531 memmove(rport, end, strlen(end) + 1);
7532 else
7533 *rport = '\0';
7536 /* Add rport to first VIA header if requested */
7537 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
7538 leftmost, ast_inet_ntoa(p->recv.sin_addr),
7539 ntohs(p->recv.sin_port),
7540 others ? "," : "", others ? others : "");
7541 } else {
7542 /* We should *always* add a received to the topmost via */
7543 snprintf(new, sizeof(new), "%s;received=%s%s%s",
7544 leftmost, ast_inet_ntoa(p->recv.sin_addr),
7545 others ? "," : "", others ? others : "");
7547 oh = new; /* the header to copy */
7548 } /* else add the following via headers untouched */
7549 add_header(req, field, oh);
7550 copied++;
7552 if (!copied) {
7553 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
7554 return -1;
7556 return 0;
7559 /*! \brief Add route header into request per learned route */
7560 static void add_route(struct sip_request *req, struct sip_route *route)
7562 char r[SIPBUFSIZE*2], *p;
7563 int n, rem = sizeof(r);
7565 if (!route)
7566 return;
7568 p = r;
7569 for (;route ; route = route->next) {
7570 n = strlen(route->hop);
7571 if (rem < n+3) /* we need room for ",<route>" */
7572 break;
7573 if (p != r) { /* add a separator after fist route */
7574 *p++ = ',';
7575 --rem;
7577 *p++ = '<';
7578 ast_copy_string(p, route->hop, rem); /* cannot fail */
7579 p += n;
7580 *p++ = '>';
7581 rem -= (n+2);
7583 *p = '\0';
7584 add_header(req, "Route", r);
7587 /*! \brief Set destination from SIP URI */
7588 static void set_destination(struct sip_pvt *p, char *uri)
7590 char *h, *maddr, hostname[256];
7591 int port, hn;
7592 struct hostent *hp;
7593 struct ast_hostent ahp;
7594 int debug=sip_debug_test_pvt(p);
7596 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
7597 /* general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] */
7599 if (debug)
7600 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
7602 /* Find and parse hostname */
7603 h = strchr(uri, '@');
7604 if (h)
7605 ++h;
7606 else {
7607 h = uri;
7608 if (strncasecmp(h, "sip:", 4) == 0)
7609 h += 4;
7610 else if (strncasecmp(h, "sips:", 5) == 0)
7611 h += 5;
7613 hn = strcspn(h, ":;>") + 1;
7614 if (hn > sizeof(hostname))
7615 hn = sizeof(hostname);
7616 ast_copy_string(hostname, h, hn);
7617 /* XXX bug here if string has been trimmed to sizeof(hostname) */
7618 h += hn - 1;
7620 /* Is "port" present? if not default to STANDARD_SIP_PORT */
7621 if (*h == ':') {
7622 /* Parse port */
7623 ++h;
7624 port = strtol(h, &h, 10);
7626 else
7627 port = STANDARD_SIP_PORT;
7629 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
7630 maddr = strstr(h, "maddr=");
7631 if (maddr) {
7632 maddr += 6;
7633 hn = strspn(maddr, "0123456789.") + 1;
7634 if (hn > sizeof(hostname))
7635 hn = sizeof(hostname);
7636 ast_copy_string(hostname, maddr, hn);
7639 hp = ast_gethostbyname(hostname, &ahp);
7640 if (hp == NULL) {
7641 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
7642 return;
7644 p->sa.sin_family = AF_INET;
7645 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
7646 p->sa.sin_port = htons(port);
7647 if (debug)
7648 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
7651 /*! \brief Initialize SIP response, based on SIP request */
7652 static int init_resp(struct sip_request *resp, const char *msg)
7654 /* Initialize a response */
7655 memset(resp, 0, sizeof(*resp));
7656 resp->method = SIP_RESPONSE;
7657 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
7658 return -1;
7659 resp->header[0] = resp->data->str;
7660 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
7661 resp->len = strlen(resp->header[0]);
7662 resp->headers++;
7663 return 0;
7666 /*! \brief Initialize SIP request */
7667 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
7669 /* Initialize a request */
7670 memset(req, 0, sizeof(*req));
7671 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
7672 return -1;
7673 req->method = sipmethod;
7674 req->header[0] = req->data->str;
7675 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
7676 req->len = strlen(req->header[0]);
7677 req->headers++;
7678 return 0;
7682 /*! \brief Prepare SIP response packet */
7683 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
7685 char newto[256];
7686 const char *ot;
7688 init_resp(resp, msg);
7689 copy_via_headers(p, resp, req, "Via");
7690 if (msg[0] == '1' || msg[0] == '2')
7691 copy_all_header(resp, req, "Record-Route");
7692 copy_header(resp, req, "From");
7693 ot = get_header(req, "To");
7694 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
7695 /* Add the proper tag if we don't have it already. If they have specified
7696 their tag, use it. Otherwise, use our own tag */
7697 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
7698 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
7699 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
7700 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
7701 else
7702 ast_copy_string(newto, ot, sizeof(newto));
7703 ot = newto;
7705 add_header(resp, "To", ot);
7706 copy_header(resp, req, "Call-ID");
7707 copy_header(resp, req, "CSeq");
7708 if (!ast_strlen_zero(global_useragent))
7709 add_header(resp, "Server", global_useragent);
7710 add_header(resp, "Allow", ALLOWED_METHODS);
7711 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
7713 /* Add Session-Timers related headers if the feature is active for this session */
7714 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
7715 char se_hdr[256];
7716 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
7717 strefresher2str(p->stimer->st_ref));
7718 add_header(resp, "Require", "timer");
7719 add_header(resp, "Session-Expires", se_hdr);
7722 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
7723 /* For registration responses, we also need expiry and
7724 contact info */
7725 char tmp[256];
7727 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
7728 add_header(resp, "Expires", tmp);
7729 if (p->expiry) { /* Only add contact if we have an expiry time */
7730 char contact[SIPBUFSIZE];
7731 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
7732 add_header(resp, "Contact", contact); /* Not when we unregister */
7734 } else if (msg[0] != '4' && !ast_strlen_zero(p->our_contact)) {
7735 add_header(resp, "Contact", p->our_contact);
7738 if (!ast_strlen_zero(p->url)) {
7739 add_header(resp, "Access-URL", p->url);
7740 ast_string_field_set(p, url, NULL);
7743 return 0;
7746 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
7747 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
7749 struct sip_request *orig = &p->initreq;
7750 char stripped[80];
7751 char tmp[80];
7752 char newto[256];
7753 const char *c;
7754 const char *ot, *of;
7755 int is_strict = FALSE; /*!< Strict routing flag */
7756 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING); /* Session direction */
7758 memset(req, 0, sizeof(struct sip_request));
7760 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
7762 if (!seqno) {
7763 p->ocseq++;
7764 seqno = p->ocseq;
7767 if (newbranch) {
7768 p->branch ^= ast_random();
7769 build_via(p);
7772 /* Check for strict or loose router */
7773 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
7774 is_strict = TRUE;
7775 if (sipdebug)
7776 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
7779 if (sipmethod == SIP_CANCEL)
7780 c = p->initreq.rlPart2; /* Use original URI */
7781 else if (sipmethod == SIP_ACK) {
7782 /* Use URI from Contact: in 200 OK (if INVITE)
7783 (we only have the contacturi on INVITEs) */
7784 if (!ast_strlen_zero(p->okcontacturi))
7785 c = is_strict ? p->route->hop : p->okcontacturi;
7786 else
7787 c = p->initreq.rlPart2;
7788 } else if (!ast_strlen_zero(p->okcontacturi))
7789 c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
7790 else if (!ast_strlen_zero(p->uri))
7791 c = p->uri;
7792 else {
7793 char *n;
7794 /* We have no URI, use To: or From: header as URI (depending on direction) */
7795 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
7796 sizeof(stripped));
7797 n = get_in_brackets(stripped);
7798 c = remove_uri_parameters(n);
7800 init_req(req, sipmethod, c);
7802 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
7804 add_header(req, "Via", p->via);
7805 if (p->route) {
7806 set_destination(p, p->route->hop);
7807 add_route(req, is_strict ? p->route->next : p->route);
7809 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
7811 ot = get_header(orig, "To");
7812 of = get_header(orig, "From");
7814 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
7815 as our original request, including tag (or presumably lack thereof) */
7816 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
7817 /* Add the proper tag if we don't have it already. If they have specified
7818 their tag, use it. Otherwise, use our own tag */
7819 if (is_outbound && !ast_strlen_zero(p->theirtag))
7820 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
7821 else if (!is_outbound)
7822 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
7823 else
7824 snprintf(newto, sizeof(newto), "%s", ot);
7825 ot = newto;
7828 if (is_outbound) {
7829 add_header(req, "From", of);
7830 add_header(req, "To", ot);
7831 } else {
7832 add_header(req, "From", ot);
7833 add_header(req, "To", of);
7835 /* Do not add Contact for MESSAGE, BYE and Cancel requests */
7836 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
7837 add_header(req, "Contact", p->our_contact);
7839 copy_header(req, orig, "Call-ID");
7840 add_header(req, "CSeq", tmp);
7842 if (!ast_strlen_zero(global_useragent))
7843 add_header(req, "User-Agent", global_useragent);
7845 if (!ast_strlen_zero(p->rpid))
7846 add_header(req, "Remote-Party-ID", p->rpid);
7848 if (!ast_strlen_zero(p->url)) {
7849 add_header(req, "Access-URL", p->url);
7850 ast_string_field_set(p, url, NULL);
7853 /* Add Session-Timers related headers if the feature is active for this session.
7854 An exception to this behavior is the ACK request. Since Asterisk never requires
7855 session-timers support from a remote end-point (UAS) in an INVITE, it must
7856 not send 'Require: timer' header in the ACK request. Also, Require: header
7857 is not applicable for CANCEL method. */
7858 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
7859 && sipmethod != SIP_ACK && sipmethod != SIP_CANCEL) {
7860 char se_hdr[256];
7861 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
7862 strefresher2str(p->stimer->st_ref));
7863 add_header(req, "Require", "timer");
7864 add_header(req, "Session-Expires", se_hdr);
7865 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
7866 add_header(req, "Min-SE", se_hdr);
7869 return 0;
7872 /*! \brief Base transmit response function */
7873 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
7875 struct sip_request resp;
7876 int seqno = 0;
7878 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
7879 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
7880 return -1;
7882 respprep(&resp, p, msg, req);
7883 add_header_contentLength(&resp, 0);
7884 /* If we are cancelling an incoming invite for some reason, add information
7885 about the reason why we are doing this in clear text */
7886 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
7887 char buf[10];
7889 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
7890 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
7891 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
7893 return send_response(p, &resp, reliable, seqno);
7896 static int temp_pvt_init(void *data)
7898 struct sip_pvt *p = data;
7900 p->do_history = 0; /* XXX do we need it ? isn't already all 0 ? */
7901 return ast_string_field_init(p, 512);
7904 static void temp_pvt_cleanup(void *data)
7906 struct sip_pvt *p = data;
7908 ast_string_field_free_memory(p);
7910 ast_free(data);
7913 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
7914 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)
7916 struct sip_pvt *p = NULL;
7918 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
7919 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
7920 return -1;
7923 /* XXX the structure may be dirty from previous usage.
7924 * Here we should state clearly how we should reinitialize it
7925 * before using it.
7926 * E.g. certainly the threadstorage should be left alone,
7927 * but other thihngs such as flags etc. maybe need cleanup ?
7930 /* Initialize the bare minimum */
7931 p->method = intended_method;
7933 if (!sin)
7934 p->ourip = internip;
7935 else {
7936 p->sa = *sin;
7937 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
7940 p->branch = ast_random();
7941 make_our_tag(p->tag, sizeof(p->tag));
7942 p->ocseq = INITIAL_CSEQ;
7944 if (useglobal_nat && sin) {
7945 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
7946 p->recv = *sin;
7947 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
7950 ast_string_field_set(p, fromdomain, default_fromdomain);
7951 build_via(p);
7952 ast_string_field_set(p, callid, callid);
7954 copy_socket_data(&p->socket, &req->socket);
7956 /* Use this temporary pvt structure to send the message */
7957 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
7959 /* Free the string fields, but not the pool space */
7960 ast_string_field_init(p, 0);
7962 return 0;
7965 /*! \brief Transmit response, no retransmits */
7966 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
7968 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
7971 /*! \brief Transmit response, no retransmits */
7972 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
7974 struct sip_request resp;
7975 respprep(&resp, p, msg, req);
7976 append_date(&resp);
7977 add_header(&resp, "Unsupported", unsupported);
7978 add_header_contentLength(&resp, 0);
7979 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
7982 /*! \brief Transmit 422 response with Min-SE header (Session-Timers) */
7983 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
7985 struct sip_request resp;
7986 char minse_str[20];
7988 respprep(&resp, p, msg, req);
7989 append_date(&resp);
7991 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
7992 add_header(&resp, "Min-SE", minse_str);
7994 add_header_contentLength(&resp, 0);
7995 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
7999 /*! \brief Transmit response, Make sure you get an ACK
8000 This is only used for responses to INVITEs, where we need to make sure we get an ACK
8002 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
8004 return __transmit_response(p, msg, req, XMIT_CRITICAL);
8007 /*! \brief Append date to SIP message */
8008 static void append_date(struct sip_request *req)
8010 char tmpdat[256];
8011 struct tm tm;
8012 time_t t = time(NULL);
8014 gmtime_r(&t, &tm);
8015 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
8016 add_header(req, "Date", tmpdat);
8019 /*! \brief Append date and content length before transmitting response */
8020 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
8022 struct sip_request resp;
8023 respprep(&resp, p, msg, req);
8024 append_date(&resp);
8025 add_header_contentLength(&resp, 0);
8026 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
8029 /*! \brief Append Accept header, content length before transmitting response */
8030 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
8032 struct sip_request resp;
8033 respprep(&resp, p, msg, req);
8034 add_header(&resp, "Accept", "application/sdp");
8035 add_header_contentLength(&resp, 0);
8036 return send_response(p, &resp, reliable, 0);
8039 /*! \brief Respond with authorization request */
8040 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)
8042 struct sip_request resp;
8043 char tmp[512];
8044 int seqno = 0;
8046 if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
8047 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
8048 return -1;
8050 /* Stale means that they sent us correct authentication, but
8051 based it on an old challenge (nonce) */
8052 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
8053 respprep(&resp, p, msg, req);
8054 add_header(&resp, header, tmp);
8055 add_header_contentLength(&resp, 0);
8056 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
8057 return send_response(p, &resp, reliable, seqno);
8060 /*! \brief Add text body to SIP message */
8061 static int add_text(struct sip_request *req, const char *text)
8063 /* XXX Convert \n's to \r\n's XXX */
8064 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
8065 add_header_contentLength(req, strlen(text));
8066 add_line(req, text);
8067 return 0;
8070 /*! \brief Add DTMF INFO tone to sip message
8071 Mode = 0 for application/dtmf-relay (Cisco)
8072 1 for application/dtmf
8074 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
8076 char tmp[256];
8077 int event;
8078 if (mode) {
8079 /* Application/dtmf short version used by some implementations */
8080 if (digit == '*')
8081 event = 10;
8082 else if (digit == '#')
8083 event = 11;
8084 else if ((digit >= 'A') && (digit <= 'D'))
8085 event = 12 + digit - 'A';
8086 else
8087 event = atoi(&digit);
8088 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
8089 add_header(req, "Content-Type", "application/dtmf");
8090 add_header_contentLength(req, strlen(tmp));
8091 add_line(req, tmp);
8092 } else {
8093 /* Application/dtmf-relay as documented by Cisco */
8094 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
8095 add_header(req, "Content-Type", "application/dtmf-relay");
8096 add_header_contentLength(req, strlen(tmp));
8097 add_line(req, tmp);
8099 return 0;
8102 /*! \brief add XML encoded media control with update
8103 \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
8104 static int add_vidupdate(struct sip_request *req)
8106 const char *xml_is_a_huge_waste_of_space =
8107 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
8108 " <media_control>\r\n"
8109 " <vc_primitive>\r\n"
8110 " <to_encoder>\r\n"
8111 " <picture_fast_update>\r\n"
8112 " </picture_fast_update>\r\n"
8113 " </to_encoder>\r\n"
8114 " </vc_primitive>\r\n"
8115 " </media_control>\r\n";
8116 add_header(req, "Content-Type", "application/media_control+xml");
8117 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
8118 add_line(req, xml_is_a_huge_waste_of_space);
8119 return 0;
8122 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
8123 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
8124 struct ast_str **m_buf, struct ast_str **a_buf,
8125 int debug, int *min_packet_size)
8127 int rtp_code;
8128 struct ast_format_list fmt;
8131 if (debug)
8132 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
8133 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
8134 return;
8136 if (p->rtp) {
8137 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
8138 fmt = ast_codec_pref_getsize(pref, codec);
8139 } 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 */
8140 return;
8141 ast_str_append(m_buf, 0, " %d", rtp_code);
8142 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8143 ast_rtp_lookup_mime_subtype(1, codec,
8144 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
8145 sample_rate);
8146 if (codec == AST_FORMAT_G729A) {
8147 /* Indicate that we don't support VAD (G.729 annex B) */
8148 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
8149 } else if (codec == AST_FORMAT_G723_1) {
8150 /* Indicate that we don't support VAD (G.723.1 annex A) */
8151 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
8152 } else if (codec == AST_FORMAT_ILBC) {
8153 /* Add information about us using only 20/30 ms packetization */
8154 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
8157 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
8158 *min_packet_size = fmt.cur_ms;
8160 /* Our first codec packetization processed cannot be zero */
8161 if ((*min_packet_size)==0 && fmt.cur_ms)
8162 *min_packet_size = fmt.cur_ms;
8165 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
8166 /* This is different to the audio one now so we can add more caps later */
8167 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
8168 struct ast_str **m_buf, struct ast_str **a_buf,
8169 int debug, int *min_packet_size)
8171 int rtp_code;
8173 if (!p->vrtp)
8174 return;
8176 if (debug)
8177 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
8179 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
8180 return;
8182 ast_str_append(m_buf, 0, " %d", rtp_code);
8183 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8184 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
8185 /* Add fmtp code here */
8188 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
8189 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
8190 struct ast_str **m_buf, struct ast_str **a_buf,
8191 int debug, int *min_packet_size)
8193 int rtp_code;
8195 if (!p->trtp)
8196 return;
8198 if (debug)
8199 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
8201 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
8202 return;
8204 ast_str_append(m_buf, 0, " %d", rtp_code);
8205 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8206 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
8207 /* Add fmtp code here */
8209 if (codec == AST_FORMAT_T140RED) {
8210 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
8211 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
8212 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
8213 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
8219 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
8220 static int t38_get_rate(int t38cap)
8222 int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
8224 if (maxrate & T38FAX_RATE_14400) {
8225 ast_debug(2, "T38MaxFaxRate 14400 found\n");
8226 return 14400;
8227 } else if (maxrate & T38FAX_RATE_12000) {
8228 ast_debug(2, "T38MaxFaxRate 12000 found\n");
8229 return 12000;
8230 } else if (maxrate & T38FAX_RATE_9600) {
8231 ast_debug(2, "T38MaxFaxRate 9600 found\n");
8232 return 9600;
8233 } else if (maxrate & T38FAX_RATE_7200) {
8234 ast_debug(2, "T38MaxFaxRate 7200 found\n");
8235 return 7200;
8236 } else if (maxrate & T38FAX_RATE_4800) {
8237 ast_debug(2, "T38MaxFaxRate 4800 found\n");
8238 return 4800;
8239 } else if (maxrate & T38FAX_RATE_2400) {
8240 ast_debug(2, "T38MaxFaxRate 2400 found\n");
8241 return 2400;
8242 } else {
8243 ast_debug(2, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
8244 return 0;
8248 /*! \brief Add T.38 Session Description Protocol message */
8249 static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
8251 int len = 0;
8252 int x = 0;
8253 struct sockaddr_in udptlsin;
8254 struct ast_str *m_modem = ast_str_alloca(1024);
8255 struct ast_str *a_modem = ast_str_alloca(1024);
8256 struct sockaddr_in udptldest = { 0, };
8257 int debug;
8259 debug = sip_debug_test_pvt(p);
8260 len = 0;
8261 if (!p->udptl) {
8262 ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
8263 return -1;
8266 if (!p->sessionid) {
8267 p->sessionid = (int)ast_random();
8268 p->sessionversion = p->sessionid;
8269 } else
8270 p->sessionversion++;
8272 /* Our T.38 end is */
8273 ast_udptl_get_us(p->udptl, &udptlsin);
8275 /* Determine T.38 UDPTL destination */
8276 if (p->udptlredirip.sin_addr.s_addr) {
8277 udptldest.sin_port = p->udptlredirip.sin_port;
8278 udptldest.sin_addr = p->udptlredirip.sin_addr;
8279 } else {
8280 udptldest.sin_addr = p->ourip.sin_addr;
8281 udptldest.sin_port = udptlsin.sin_port;
8284 if (debug)
8285 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
8287 /* We break with the "recommendation" and send our IP, in order that our
8288 peer doesn't have to ast_gethostbyname() us */
8290 if (debug) {
8291 ast_debug(1, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
8292 p->t38.capability,
8293 p->t38.peercapability,
8294 p->t38.jointcapability);
8296 ast_str_append(&m_modem, 0, "v=0\r\n");
8297 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));
8298 ast_str_append(&m_modem, 0, "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
8299 ast_str_append(&m_modem, 0, "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
8300 ast_str_append(&m_modem, 0, "t=0 0\r\n");
8301 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
8303 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
8304 ast_str_append(&a_modem, 0, "a=T38FaxVersion:0\r\n");
8305 if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
8306 ast_str_append(&a_modem, 0, "a=T38FaxVersion:1\r\n");
8307 if ((x = t38_get_rate(p->t38.jointcapability)))
8308 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", x);
8309 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
8310 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
8311 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
8312 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
8313 x = ast_udptl_get_local_max_datagram(p->udptl);
8314 ast_str_append(&a_modem, 0, "a=T38FaxMaxBuffer:%d\r\n", x);
8315 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%d\r\n", x);
8316 if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
8317 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
8318 len = m_modem->used + a_modem->used;
8319 add_header(resp, "Content-Type", "application/sdp");
8320 add_header_contentLength(resp, len);
8321 add_line(resp, m_modem->str);
8322 add_line(resp, a_modem->str);
8324 /* Update lastrtprx when we send our SDP */
8325 p->lastrtprx = p->lastrtptx = time(NULL);
8327 return 0;
8331 /*! \brief Add RFC 2833 DTMF offer to SDP */
8332 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
8333 struct ast_str **m_buf, struct ast_str **a_buf,
8334 int debug)
8336 int rtp_code;
8338 if (debug)
8339 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
8340 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
8341 return;
8343 ast_str_append(m_buf, 0, " %d", rtp_code);
8344 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
8345 ast_rtp_lookup_mime_subtype(0, format, 0),
8346 sample_rate);
8347 if (format == AST_RTP_DTMF) /* Indicate we support DTMF and FLASH... */
8348 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
8351 /*! \brief Set all IP media addresses for this call
8352 \note called from add_sdp()
8354 static void get_our_media_address(struct sip_pvt *p, int needvideo,
8355 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
8356 struct sockaddr_in *dest, struct sockaddr_in *vdest)
8358 /* First, get our address */
8359 ast_rtp_get_us(p->rtp, sin);
8360 if (p->vrtp)
8361 ast_rtp_get_us(p->vrtp, vsin);
8362 if (p->trtp)
8363 ast_rtp_get_us(p->trtp, tsin);
8365 /* Now, try to figure out where we want them to send data */
8366 /* Is this a re-invite to move the media out, then use the original offer from caller */
8367 if (p->redirip.sin_addr.s_addr) { /* If we have a redirection IP, use it */
8368 dest->sin_port = p->redirip.sin_port;
8369 dest->sin_addr = p->redirip.sin_addr;
8370 } else {
8371 dest->sin_addr = p->ourip.sin_addr;
8372 dest->sin_port = sin->sin_port;
8374 if (needvideo) {
8375 /* Determine video destination */
8376 if (p->vredirip.sin_addr.s_addr) {
8377 vdest->sin_addr = p->vredirip.sin_addr;
8378 vdest->sin_port = p->vredirip.sin_port;
8379 } else {
8380 vdest->sin_addr = p->ourip.sin_addr;
8381 vdest->sin_port = vsin->sin_port;
8388 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
8389 * really 16 kHz. Update this macro for other formats as they are added in
8390 * the future.
8392 #define SDP_SAMPLE_RATE(x) 8000
8394 /*! \brief Add Session Description Protocol message
8396 If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
8397 is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
8398 without modifying the media session in any way.
8400 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp)
8402 int len = 0;
8403 int alreadysent = 0;
8405 struct sockaddr_in sin;
8406 struct sockaddr_in vsin;
8407 struct sockaddr_in tsin;
8408 struct sockaddr_in dest;
8409 struct sockaddr_in vdest = { 0, };
8410 struct sockaddr_in tdest = { 0, };
8412 /* SDP fields */
8413 char *version = "v=0\r\n"; /* Protocol version */
8414 char subject[256]; /* Subject of the session */
8415 char owner[256]; /* Session owner/creator */
8416 char connection[256]; /* Connection data */
8417 char *stime = "t=0 0\r\n"; /* Time the session is active */
8418 char bandwidth[256] = ""; /* Max bitrate */
8419 char *hold;
8420 struct ast_str *m_audio = ast_str_alloca(256); /* Media declaration line for audio */
8421 struct ast_str *m_video = ast_str_alloca(256); /* Media declaration line for video */
8422 struct ast_str *m_text = ast_str_alloca(256); /* Media declaration line for text */
8423 struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
8424 struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
8425 struct ast_str *a_text = ast_str_alloca(1024); /* Attributes for text */
8427 int x;
8428 int capability;
8429 int needaudio = FALSE;
8430 int needvideo = FALSE;
8431 int needtext = FALSE;
8432 int debug = sip_debug_test_pvt(p);
8433 int min_audio_packet_size = 0;
8434 int min_video_packet_size = 0;
8435 int min_text_packet_size = 0;
8437 char codecbuf[SIPBUFSIZE];
8438 char buf[SIPBUFSIZE];
8440 /* Set the SDP session name */
8441 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
8443 if (!p->rtp) {
8444 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
8445 return AST_FAILURE;
8447 /* XXX We should not change properties in the SIP dialog until
8448 we have acceptance of the offer if this is a re-invite */
8450 /* Set RTP Session ID and version */
8451 if (!p->sessionid) {
8452 p->sessionid = (int)ast_random();
8453 p->sessionversion = p->sessionid;
8454 } else {
8455 if (oldsdp == FALSE)
8456 p->sessionversion++;
8459 capability = p->jointcapability;
8461 /* XXX note, Video and Text are negated - 'true' means 'no' */
8462 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
8463 p->novideo ? "True" : "False", p->notext ? "True" : "False");
8464 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
8466 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
8467 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
8468 ast_str_append(&m_audio, 0, " %d", 191);
8469 ast_str_append(&a_audio, 0, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
8471 #endif
8473 /* Check if we need audio */
8474 if (capability & AST_FORMAT_AUDIO_MASK)
8475 needaudio = TRUE;
8477 /* Check if we need video in this call */
8478 if ((capability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
8479 if (p->vrtp) {
8480 needvideo = TRUE;
8481 ast_debug(2, "This call needs video offers!\n");
8482 } else
8483 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
8486 /* Get our media addresses */
8487 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
8489 if (debug)
8490 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
8492 /* Ok, we need video. Let's add what we need for video and set codecs.
8493 Video is handled differently than audio since we can not transcode. */
8494 if (needvideo) {
8495 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
8497 /* Build max bitrate string */
8498 if (p->maxcallbitrate)
8499 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
8500 if (debug)
8501 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vsin.sin_port));
8504 /* Check if we need text in this call */
8505 if((capability & AST_FORMAT_TEXT_MASK) && !p->notext) {
8506 if (sipdebug_text)
8507 ast_verbose("We think we can do text\n");
8508 if (p->trtp) {
8509 if (sipdebug_text)
8510 ast_verbose("And we have a text rtp object\n");
8511 needtext = TRUE;
8512 ast_debug(2, "This call needs text offers! \n");
8513 } else
8514 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
8517 /* Ok, we need text. Let's add what we need for text and set codecs.
8518 Text is handled differently than audio since we can not transcode. */
8519 if (needtext) {
8520 if (sipdebug_text)
8521 ast_verbose("Lets set up the text sdp\n");
8522 /* Determine text destination */
8523 if (p->tredirip.sin_addr.s_addr) {
8524 tdest.sin_addr = p->tredirip.sin_addr;
8525 tdest.sin_port = p->tredirip.sin_port;
8526 } else {
8527 tdest.sin_addr = p->ourip.sin_addr;
8528 tdest.sin_port = tsin.sin_port;
8530 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
8532 if (debug) /* XXX should I use tdest below ? */
8533 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
8537 /* Start building generic SDP headers */
8539 /* We break with the "recommendation" and send our IP, in order that our
8540 peer doesn't have to ast_gethostbyname() us */
8542 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));
8543 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
8544 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
8546 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
8547 hold = "a=recvonly\r\n";
8548 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
8549 hold = "a=inactive\r\n";
8550 else
8551 hold = "a=sendrecv\r\n";
8553 /* Now, start adding audio codecs. These are added in this order:
8554 - First what was requested by the calling channel
8555 - Then preferences in order from sip.conf device config for this peer/user
8556 - Then other codecs in capabilities, including video
8559 /* Prefer the audio codec we were requested to use, first, no matter what
8560 Note that p->prefcodec can include video codecs, so mask them out
8562 if (capability & p->prefcodec) {
8563 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
8565 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
8566 &m_audio, &a_audio,
8567 debug, &min_audio_packet_size);
8568 alreadysent |= codec;
8571 /* Start by sending our preferred audio/video codecs */
8572 for (x = 0; x < 32; x++) {
8573 int codec;
8575 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
8576 break;
8578 if (!(capability & codec))
8579 continue;
8581 if (alreadysent & codec)
8582 continue;
8584 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
8585 &m_audio, &a_audio,
8586 debug, &min_audio_packet_size);
8587 alreadysent |= codec;
8590 /* Now send any other common audio and video codecs, and non-codec formats: */
8591 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
8592 if (!(capability & x)) /* Codec not requested */
8593 continue;
8595 if (alreadysent & x) /* Already added to SDP */
8596 continue;
8598 if (x & AST_FORMAT_AUDIO_MASK)
8599 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
8600 &m_audio, &a_audio, debug, &min_audio_packet_size);
8601 else if (x & AST_FORMAT_VIDEO_MASK)
8602 add_vcodec_to_sdp(p, x, 90000,
8603 &m_video, &a_video, debug, &min_video_packet_size);
8604 else if (x & AST_FORMAT_TEXT_MASK)
8605 add_tcodec_to_sdp(p, x, 1000,
8606 &m_text, &a_text, debug, &min_text_packet_size);
8609 /* Now add DTMF RFC2833 telephony-event as a codec */
8610 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
8611 if (!(p->jointnoncodeccapability & x))
8612 continue;
8614 add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
8617 ast_debug(3, "-- Done with adding codecs to SDP\n");
8619 if (!p->owner || !ast_internal_timing_enabled(p->owner))
8620 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
8622 if (min_audio_packet_size)
8623 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
8625 /* XXX don't think you can have ptime for video */
8626 if (min_video_packet_size)
8627 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
8629 /* XXX don't think you can have ptime for text */
8630 if (min_text_packet_size)
8631 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
8633 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
8634 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
8635 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
8636 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
8638 if (needaudio)
8639 ast_str_append(&m_audio, 0, "\r\n");
8640 if (needvideo)
8641 ast_str_append(&m_video, 0, "\r\n");
8642 if (needtext)
8643 ast_str_append(&m_text, 0, "\r\n");
8645 len = strlen(version) + strlen(subject) + strlen(owner) +
8646 strlen(connection) + strlen(stime);
8647 if (needaudio)
8648 len += m_audio->used + a_audio->used + strlen(hold);
8649 if (needvideo) /* only if video response is appropriate */
8650 len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
8651 if (needtext) /* only if text response is appropriate */
8652 len += m_text->used + a_text->used + strlen(hold);
8654 add_header(resp, "Content-Type", "application/sdp");
8655 add_header_contentLength(resp, len);
8656 add_line(resp, version);
8657 add_line(resp, owner);
8658 add_line(resp, subject);
8659 add_line(resp, connection);
8660 if (needvideo) /* only if video response is appropriate */
8661 add_line(resp, bandwidth);
8662 add_line(resp, stime);
8663 if (needaudio) {
8664 add_line(resp, m_audio->str);
8665 add_line(resp, a_audio->str);
8666 add_line(resp, hold);
8668 if (needvideo) { /* only if video response is appropriate */
8669 add_line(resp, m_video->str);
8670 add_line(resp, a_video->str);
8671 add_line(resp, hold); /* Repeat hold for the video stream */
8673 if (needtext) { /* only if text response is appropriate */
8674 add_line(resp, m_text->str);
8675 add_line(resp, a_text->str);
8676 add_line(resp, hold); /* Repeat hold for the text stream */
8679 /* Update lastrtprx when we send our SDP */
8680 p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
8682 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
8684 return AST_SUCCESS;
8687 /*! \brief Used for 200 OK and 183 early media */
8688 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
8690 struct sip_request resp;
8691 int seqno;
8693 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
8694 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
8695 return -1;
8697 respprep(&resp, p, msg, req);
8698 if (p->udptl) {
8699 ast_udptl_offered_from_local(p->udptl, 0);
8700 add_t38_sdp(&resp, p);
8701 } else
8702 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
8703 if (retrans && !p->pendinginvite)
8704 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
8705 return send_response(p, &resp, retrans, seqno);
8708 /*! \brief copy SIP request (mostly used to save request for responses) */
8709 static void copy_request(struct sip_request *dst, const struct sip_request *src)
8711 long offset;
8712 int x;
8713 struct ast_str *dup = dst->data;
8715 /* First copy stuff */
8716 memcpy(dst, src, sizeof(*dst));
8717 dst->data = dup;
8719 /* All these + 1's are to account for the need to include the NULL terminator
8720 * Using typical string functions like ast_copy_string or ast_str_set will not
8721 * work in this case because the src's data string is riddled with \0's all over
8722 * the place and so a memcpy is the only way to accurately copy the string
8725 if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
8726 return;
8727 else if (dst->data->len < src->data->used + 1)
8728 ast_str_make_space(&dst->data, src->data->used + 1);
8730 memcpy(dst->data->str, src->data->str, src->data->used + 1);
8731 dst->data->used = src->data->used;
8732 offset = ((void *)dst->data->str) - ((void *)src->data->str);
8733 /* Now fix pointer arithmetic */
8734 for (x = 0; x < src->headers; x++)
8735 dst->header[x] += offset;
8736 for (x = 0; x < src->lines; x++)
8737 dst->line[x] += offset;
8738 /* On some occasions this function is called without parse_request being called first so lets not create an invalid pointer */
8739 if (src->rlPart1)
8740 dst->rlPart1 += offset;
8741 if (src->rlPart2)
8742 dst->rlPart2 += offset;
8745 /*! \brief Used for 200 OK and 183 early media
8746 \return Will return XMIT_ERROR for network errors.
8748 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
8750 struct sip_request resp;
8751 int seqno;
8752 if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
8753 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
8754 return -1;
8756 respprep(&resp, p, msg, req);
8757 if (p->rtp) {
8758 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
8759 ast_debug(1, "Setting framing from config on incoming call\n");
8760 ast_rtp_codec_setpref(p->rtp, &p->prefs);
8762 try_suggested_sip_codec(p);
8763 add_sdp(&resp, p, oldsdp);
8764 } else
8765 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
8766 if (reliable && !p->pendinginvite)
8767 p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
8768 return send_response(p, &resp, reliable, seqno);
8771 /*! \brief Parse first line of incoming SIP request */
8772 static int determine_firstline_parts(struct sip_request *req)
8774 char *e = ast_skip_blanks(req->header[0]); /* there shouldn't be any */
8776 if (!*e)
8777 return -1;
8778 req->rlPart1 = e; /* method or protocol */
8779 e = ast_skip_nonblanks(e);
8780 if (*e)
8781 *e++ = '\0';
8782 /* Get URI or status code */
8783 e = ast_skip_blanks(e);
8784 if ( !*e )
8785 return -1;
8786 ast_trim_blanks(e);
8788 if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
8789 if (strlen(e) < 3) /* status code is 3 digits */
8790 return -1;
8791 req->rlPart2 = e;
8792 } else { /* We have a request */
8793 if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
8794 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
8795 e++;
8796 if (!*e)
8797 return -1;
8799 req->rlPart2 = e; /* URI */
8800 e = ast_skip_nonblanks(e);
8801 if (*e)
8802 *e++ = '\0';
8803 e = ast_skip_blanks(e);
8804 if (strcasecmp(e, "SIP/2.0") ) {
8805 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
8806 return -1;
8809 return 1;
8812 /*! \brief Transmit reinvite with SDP
8813 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
8814 INVITE that opened the SIP dialogue
8815 We reinvite so that the audio stream (RTP) go directly between
8816 the SIP UAs. SIP Signalling stays with * in the path.
8818 If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
8819 T38 UDPTL transmission on the channel
8821 If oldsdp is TRUE then the SDP version number is not incremented. This
8822 is needed for Session-Timers so we can send a re-invite to refresh the
8823 SIP session without modifying the media session.
8825 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
8827 struct sip_request req;
8829 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
8831 add_header(&req, "Allow", ALLOWED_METHODS);
8832 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
8833 if (sipdebug) {
8834 if (oldsdp == TRUE)
8835 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
8836 else
8837 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
8840 if (p->do_history)
8841 append_history(p, "ReInv", "Re-invite sent");
8842 if (t38version)
8843 add_t38_sdp(&req, p);
8844 else
8845 add_sdp(&req, p, oldsdp);
8847 /* Use this as the basis */
8848 initialize_initreq(p, &req);
8849 p->lastinvite = p->ocseq;
8850 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
8852 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
8855 /* \brief Remove URI parameters at end of URI, not in username part though */
8856 static char *remove_uri_parameters(char *uri)
8858 char *atsign;
8859 atsign = strchr(uri, '@'); /* First, locate the at sign */
8860 if (!atsign)
8861 atsign = uri; /* Ok hostname only, let's stick with the rest */
8862 atsign = strchr(atsign, ';'); /* Locate semi colon */
8863 if (atsign)
8864 *atsign = '\0'; /* Kill at the semi colon */
8865 return uri;
8868 /*! \brief Check Contact: URI of SIP message */
8869 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
8871 char stripped[SIPBUFSIZE];
8872 char *c;
8874 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
8875 c = get_in_brackets(stripped);
8876 /* Cut the URI at the at sign after the @, not in the username part */
8877 c = remove_uri_parameters(c);
8878 if (!ast_strlen_zero(c))
8879 ast_string_field_set(p, uri, c);
8883 /*! \brief Build contact header - the contact header we send out */
8884 static void build_contact(struct sip_pvt *p)
8886 /* Construct Contact: header */
8887 if (p->socket.type & SIP_TRANSPORT_UDP) {
8888 if (!sip_standard_port(p->socket))
8889 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));
8890 else
8891 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));
8892 } else
8893 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(p->socket.type));
8896 /*! \brief Build the Remote Party-ID & From using callingpres options */
8897 static void build_rpid(struct sip_pvt *p)
8899 int send_pres_tags = TRUE;
8900 const char *privacy=NULL;
8901 const char *screen=NULL;
8902 char buf[256];
8903 const char *clid = default_callerid;
8904 const char *clin = NULL;
8905 const char *fromdomain;
8907 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
8908 return;
8910 if (p->owner && p->owner->cid.cid_num)
8911 clid = p->owner->cid.cid_num;
8912 if (p->owner && p->owner->cid.cid_name)
8913 clin = p->owner->cid.cid_name;
8914 if (ast_strlen_zero(clin))
8915 clin = clid;
8917 switch (p->callingpres) {
8918 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
8919 privacy = "off";
8920 screen = "no";
8921 break;
8922 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
8923 privacy = "off";
8924 screen = "yes";
8925 break;
8926 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
8927 privacy = "off";
8928 screen = "no";
8929 break;
8930 case AST_PRES_ALLOWED_NETWORK_NUMBER:
8931 privacy = "off";
8932 screen = "yes";
8933 break;
8934 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
8935 privacy = "full";
8936 screen = "no";
8937 break;
8938 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
8939 privacy = "full";
8940 screen = "yes";
8941 break;
8942 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
8943 privacy = "full";
8944 screen = "no";
8945 break;
8946 case AST_PRES_PROHIB_NETWORK_NUMBER:
8947 privacy = "full";
8948 screen = "yes";
8949 break;
8950 case AST_PRES_NUMBER_NOT_AVAILABLE:
8951 send_pres_tags = FALSE;
8952 break;
8953 default:
8954 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
8955 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
8956 privacy = "full";
8957 else
8958 privacy = "off";
8959 screen = "no";
8960 break;
8963 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
8965 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
8966 if (send_pres_tags)
8967 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
8968 ast_string_field_set(p, rpid, buf);
8970 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
8971 S_OR(p->fromuser, clid),
8972 fromdomain, p->tag);
8975 /*! \brief Initiate new SIP request to peer/user */
8976 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
8978 struct ast_str *invite = ast_str_alloca(256);
8979 char from[256];
8980 char to[256];
8981 char tmp_n[SIPBUFSIZE/2]; /* build a local copy of 'n' if needed */
8982 char tmp_l[SIPBUFSIZE/2]; /* build a local copy of 'l' if needed */
8983 const char *l = NULL; /* XXX what is this, exactly ? */
8984 const char *n = NULL; /* XXX what is this, exactly ? */
8985 const char *urioptions = "";
8987 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
8988 const char *s = p->username; /* being a string field, cannot be NULL */
8990 /* Test p->username against allowed characters in AST_DIGIT_ANY
8991 If it matches the allowed characters list, then sipuser = ";user=phone"
8992 If not, then sipuser = ""
8994 /* + is allowed in first position in a tel: uri */
8995 if (*s == '+')
8996 s++;
8997 for (; *s; s++) {
8998 if (!strchr(AST_DIGIT_ANYNUM, *s) )
8999 break;
9001 /* If we have only digits, add ;user=phone to the uri */
9002 if (*s)
9003 urioptions = ";user=phone";
9007 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
9009 if (p->owner) {
9010 l = p->owner->cid.cid_num;
9011 n = p->owner->cid.cid_name;
9013 /* if we are not sending RPID and user wants his callerid restricted */
9014 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
9015 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
9016 l = CALLERID_UNKNOWN;
9017 n = l;
9019 if (ast_strlen_zero(l))
9020 l = default_callerid;
9021 if (ast_strlen_zero(n))
9022 n = l;
9023 /* Allow user to be overridden */
9024 if (!ast_strlen_zero(p->fromuser))
9025 l = p->fromuser;
9026 else /* Save for any further attempts */
9027 ast_string_field_set(p, fromuser, l);
9029 /* Allow user to be overridden */
9030 if (!ast_strlen_zero(p->fromname))
9031 n = p->fromname;
9032 else /* Save for any further attempts */
9033 ast_string_field_set(p, fromname, n);
9035 if (pedanticsipchecking) {
9036 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
9037 n = tmp_n;
9038 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
9039 l = tmp_l;
9042 if (!sip_standard_port(p->socket) && ast_strlen_zero(p->fromdomain))
9043 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);
9044 else
9045 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);
9047 /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
9048 if (!ast_strlen_zero(p->fullcontact)) {
9049 /* If we have full contact, trust it */
9050 ast_str_append(&invite, 0, "%s", p->fullcontact);
9051 } else {
9052 /* Otherwise, use the username while waiting for registration */
9053 ast_str_append(&invite, 0, "sip:");
9054 if (!ast_strlen_zero(p->username)) {
9055 n = p->username;
9056 if (pedanticsipchecking) {
9057 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
9058 n = tmp_n;
9060 ast_str_append(&invite, 0, "%s@", n);
9062 ast_str_append(&invite, 0, "%s", p->tohost);
9063 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
9064 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
9065 ast_str_append(&invite, 0, "%s", urioptions);
9068 /* If custom URI options have been provided, append them */
9069 if (p->options && !ast_strlen_zero(p->options->uri_options))
9070 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
9072 /* This is the request URI, which is the next hop of the call
9073 which may or may not be the destination of the call
9075 ast_string_field_set(p, uri, invite->str);
9077 if (!ast_strlen_zero(p->todnid)) {
9078 /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
9079 if (!strchr(p->todnid, '@')) {
9080 /* We have no domain in the dnid */
9081 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
9082 } else {
9083 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
9085 } else {
9086 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
9087 /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
9088 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
9089 } else if (p->options && p->options->vxml_url) {
9090 /* If there is a VXML URL append it to the SIP URL */
9091 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
9092 } else
9093 snprintf(to, sizeof(to), "<%s>", p->uri);
9096 init_req(req, sipmethod, p->uri);
9097 /* now tmp_n is available so reuse it to build the CSeq */
9098 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
9100 add_header(req, "Via", p->via);
9101 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
9102 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
9103 * OTOH, then we won't have anything in p->route anyway */
9105 /* Build Remote Party-ID and From */
9106 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
9107 build_rpid(p);
9108 add_header(req, "From", p->rpid_from);
9109 } else
9110 add_header(req, "From", from);
9111 add_header(req, "To", to);
9112 ast_string_field_set(p, exten, l);
9113 build_contact(p);
9114 add_header(req, "Contact", p->our_contact);
9115 add_header(req, "Call-ID", p->callid);
9116 add_header(req, "CSeq", tmp_n);
9117 if (!ast_strlen_zero(global_useragent))
9118 add_header(req, "User-Agent", global_useragent);
9119 if (!ast_strlen_zero(p->rpid))
9120 add_header(req, "Remote-Party-ID", p->rpid);
9123 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it
9124 \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
9125 \param p sip_pvt structure
9126 \param sdp unknown
9127 \param sipmethod unknown
9130 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
9132 struct sip_request req;
9133 struct ast_variable *var;
9135 req.method = sipmethod;
9136 if (init) {/* Bump branch even on initial requests */
9137 p->branch ^= ast_random();
9138 build_via(p);
9140 if (init > 1)
9141 initreqprep(&req, p, sipmethod);
9142 else
9143 reqprep(&req, p, sipmethod, 0, 1);
9145 if (p->options && p->options->auth)
9146 add_header(&req, p->options->authheader, p->options->auth);
9147 append_date(&req);
9148 if (sipmethod == SIP_REFER) { /* Call transfer */
9149 if (p->refer) {
9150 char buf[SIPBUFSIZE];
9151 if (!ast_strlen_zero(p->refer->refer_to))
9152 add_header(&req, "Refer-To", p->refer->refer_to);
9153 if (!ast_strlen_zero(p->refer->referred_by)) {
9154 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
9155 add_header(&req, "Referred-By", buf);
9159 /* This new INVITE is part of an attended transfer. Make sure that the
9160 other end knows and replace the current call with this new call */
9161 if (p->options && !ast_strlen_zero(p->options->replaces)) {
9162 add_header(&req, "Replaces", p->options->replaces);
9163 add_header(&req, "Require", "replaces");
9166 /* Add Session-Timers related headers */
9167 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
9168 char i2astr[10];
9170 if (!p->stimer->st_interval)
9171 p->stimer->st_interval = st_get_se(p, TRUE);
9173 p->stimer->st_active = TRUE;
9175 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
9176 add_header(&req, "Session-Expires", i2astr);
9177 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
9178 add_header(&req, "Min-SE", i2astr);
9181 add_header(&req, "Allow", ALLOWED_METHODS);
9182 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
9184 if(p->notify_headers) {
9185 char buf[512];
9186 for (var = p->notify_headers; var; var = var->next) {
9187 ast_copy_string(buf, var->value, sizeof(buf));
9188 add_header(&req, var->name, ast_unescape_semicolon(buf));
9191 if (p->options && p->options->addsipheaders && p->owner) {
9192 struct ast_channel *chan = p->owner; /* The owner channel */
9193 struct varshead *headp;
9195 ast_channel_lock(chan);
9197 headp = &chan->varshead;
9199 if (!headp)
9200 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
9201 else {
9202 const struct ast_var_t *current;
9203 AST_LIST_TRAVERSE(headp, current, entries) {
9204 /* SIPADDHEADER: Add SIP header to outgoing call */
9205 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
9206 char *content, *end;
9207 const char *header = ast_var_value(current);
9208 char *headdup = ast_strdupa(header);
9210 /* Strip of the starting " (if it's there) */
9211 if (*headdup == '"')
9212 headdup++;
9213 if ((content = strchr(headdup, ':'))) {
9214 *content++ = '\0';
9215 content = ast_skip_blanks(content); /* Skip white space */
9216 /* Strip the ending " (if it's there) */
9217 end = content + strlen(content) -1;
9218 if (*end == '"')
9219 *end = '\0';
9221 add_header(&req, headdup, content);
9222 if (sipdebug)
9223 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
9229 ast_channel_unlock(chan);
9231 if (sdp) {
9232 if (p->udptl && (p->t38.state == T38_LOCAL_DIRECT || p->t38.state == T38_LOCAL_REINVITE)) {
9233 ast_udptl_offered_from_local(p->udptl, 1);
9234 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
9235 add_t38_sdp(&req, p);
9236 } else if (p->rtp)
9237 add_sdp(&req, p, FALSE);
9238 } else {
9239 if (!p->notify_headers) {
9240 add_header_contentLength(&req, 0);
9244 if (!p->initreq.headers)
9245 initialize_initreq(p, &req);
9246 p->lastinvite = p->ocseq;
9247 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
9250 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
9251 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
9253 struct ast_str *tmp = ast_str_alloca(4000);
9254 char from[256], to[256];
9255 char *c, *mfrom, *mto;
9256 struct sip_request req;
9257 char hint[AST_MAX_EXTENSION];
9258 char *statestring = "terminated";
9259 const struct cfsubscription_types *subscriptiontype;
9260 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
9261 char *pidfstate = "--";
9262 char *pidfnote= "Ready";
9264 memset(from, 0, sizeof(from));
9265 memset(to, 0, sizeof(to));
9267 switch (state) {
9268 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
9269 statestring = (global_notifyringing) ? "early" : "confirmed";
9270 local_state = NOTIFY_INUSE;
9271 pidfstate = "busy";
9272 pidfnote = "Ringing";
9273 break;
9274 case AST_EXTENSION_RINGING:
9275 statestring = "early";
9276 local_state = NOTIFY_INUSE;
9277 pidfstate = "busy";
9278 pidfnote = "Ringing";
9279 break;
9280 case AST_EXTENSION_INUSE:
9281 statestring = "confirmed";
9282 local_state = NOTIFY_INUSE;
9283 pidfstate = "busy";
9284 pidfnote = "On the phone";
9285 break;
9286 case AST_EXTENSION_BUSY:
9287 statestring = "confirmed";
9288 local_state = NOTIFY_CLOSED;
9289 pidfstate = "busy";
9290 pidfnote = "On the phone";
9291 break;
9292 case AST_EXTENSION_UNAVAILABLE:
9293 statestring = "terminated";
9294 local_state = NOTIFY_CLOSED;
9295 pidfstate = "away";
9296 pidfnote = "Unavailable";
9297 break;
9298 case AST_EXTENSION_ONHOLD:
9299 statestring = "confirmed";
9300 local_state = NOTIFY_CLOSED;
9301 pidfstate = "busy";
9302 pidfnote = "On hold";
9303 break;
9304 case AST_EXTENSION_NOT_INUSE:
9305 default:
9306 /* Default setting */
9307 break;
9310 subscriptiontype = find_subscription_type(p->subscribed);
9312 /* Check which device/devices we are watching and if they are registered */
9313 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
9314 char *hint2 = hint, *individual_hint = NULL;
9315 int hint_count = 0, unavailable_count = 0;
9317 while ((individual_hint = strsep(&hint2, "&"))) {
9318 hint_count++;
9320 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
9321 unavailable_count++;
9324 /* If none of the hinted devices are registered, we will
9325 * override notification and show no availability.
9327 if (hint_count > 0 && hint_count == unavailable_count) {
9328 local_state = NOTIFY_CLOSED;
9329 pidfstate = "away";
9330 pidfnote = "Not online";
9334 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
9335 c = get_in_brackets(from);
9336 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
9337 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
9338 return -1;
9341 mfrom = remove_uri_parameters(c);
9343 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
9344 c = get_in_brackets(to);
9345 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
9346 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
9347 return -1;
9349 mto = remove_uri_parameters(c);
9351 reqprep(&req, p, SIP_NOTIFY, 0, 1);
9354 add_header(&req, "Event", subscriptiontype->event);
9355 add_header(&req, "Content-Type", subscriptiontype->mediatype);
9356 switch(state) {
9357 case AST_EXTENSION_DEACTIVATED:
9358 if (timeout)
9359 add_header(&req, "Subscription-State", "terminated;reason=timeout");
9360 else {
9361 add_header(&req, "Subscription-State", "terminated;reason=probation");
9362 add_header(&req, "Retry-After", "60");
9364 break;
9365 case AST_EXTENSION_REMOVED:
9366 add_header(&req, "Subscription-State", "terminated;reason=noresource");
9367 break;
9368 default:
9369 if (p->expiry)
9370 add_header(&req, "Subscription-State", "active");
9371 else /* Expired */
9372 add_header(&req, "Subscription-State", "terminated;reason=timeout");
9374 switch (p->subscribed) {
9375 case XPIDF_XML:
9376 case CPIM_PIDF_XML:
9377 ast_str_append(&tmp, 0,
9378 "<?xml version=\"1.0\"?>\n"
9379 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
9380 "<presence>\n");
9381 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
9382 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
9383 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
9384 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
9385 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
9386 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
9387 break;
9388 case PIDF_XML: /* Eyebeam supports this format */
9389 ast_str_append(&tmp, 0,
9390 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
9391 "<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);
9392 ast_str_append(&tmp, 0, "<pp:person><status>\n");
9393 if (pidfstate[0] != '-')
9394 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
9395 ast_str_append(&tmp, 0, "</status></pp:person>\n");
9396 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
9397 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
9398 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
9399 if (pidfstate[0] == 'b') /* Busy? Still open ... */
9400 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
9401 else
9402 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
9403 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
9404 break;
9405 case DIALOG_INFO_XML: /* SNOM subscribes in this format */
9406 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
9407 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);
9408 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
9409 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
9410 else
9411 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
9412 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
9413 if (state == AST_EXTENSION_ONHOLD) {
9414 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
9415 "<param pname=\"+sip.rendering\" pvalue=\"no\">\n"
9416 "</target>\n</local>\n", mto);
9418 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
9419 break;
9420 case NONE:
9421 default:
9422 break;
9425 add_header_contentLength(&req, tmp->used);
9426 add_line(&req, tmp->str);
9428 p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
9430 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9433 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
9434 \note - Notification only works for registered peers with mailbox= definitions
9435 in sip.conf
9436 - We use the SIP Event package message-summary
9437 MIME type defaults to "application/simple-message-summary";
9439 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
9441 struct sip_request req;
9442 struct ast_str *out = ast_str_alloca(500);
9444 initreqprep(&req, p, SIP_NOTIFY);
9445 add_header(&req, "Event", "message-summary");
9446 add_header(&req, "Content-Type", default_notifymime);
9448 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
9449 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n",
9450 S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr)));
9451 /* Cisco has a bug in the SIP stack where it can't accept the
9452 (0/0) notification. This can temporarily be disabled in
9453 sip.conf with the "buggymwi" option */
9454 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
9455 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
9457 if (p->subscribed) {
9458 if (p->expiry)
9459 add_header(&req, "Subscription-State", "active");
9460 else /* Expired */
9461 add_header(&req, "Subscription-State", "terminated;reason=timeout");
9464 add_header_contentLength(&req, out->used);
9465 add_line(&req, out->str);
9467 if (!p->initreq.headers)
9468 initialize_initreq(p, &req);
9469 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9472 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
9473 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
9475 struct sip_request req;
9476 char tmp[SIPBUFSIZE/2];
9478 reqprep(&req, p, SIP_NOTIFY, 0, 1);
9479 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
9480 add_header(&req, "Event", tmp);
9481 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
9482 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
9483 add_header(&req, "Allow", ALLOWED_METHODS);
9484 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
9486 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
9487 add_header_contentLength(&req, strlen(tmp));
9488 add_line(&req, tmp);
9490 if (!p->initreq.headers)
9491 initialize_initreq(p, &req);
9493 p->lastnoninvite = p->ocseq;
9495 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9498 /*! \brief Notify device with custom headers from sip_notify.conf */
9499 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
9500 struct sip_request req;
9501 struct ast_variable *var, *newvar;
9503 initreqprep(&req, p, SIP_NOTIFY);
9505 /* Copy notify vars and add headers */
9506 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
9507 add_header(&req, newvar->name, newvar->value);
9508 for (var = vars; var; var = var->next) {
9509 char buf[512];
9510 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
9511 ast_copy_string(buf, var->value, sizeof(buf));
9512 add_header(&req, var->name, ast_unescape_semicolon(buf));
9513 newvar->next = ast_variable_new(var->name, var->value, "");
9514 newvar = newvar->next;
9517 if (!p->initreq.headers) { /* Initialize first request before sending */
9518 initialize_initreq(p, &req);
9521 return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
9524 static int manager_sipnotify(struct mansession *s, const struct message *m)
9526 const char *channame = astman_get_header(m, "Channel");
9527 struct ast_variable *vars = astman_get_variables(m);
9528 struct sip_pvt *p;
9530 if (!channame) {
9531 astman_send_error(s, m, "SIPNotify requires a channel name");
9532 return -1;
9535 if (strncasecmp(channame, "sip/", 4) == 0) {
9536 channame += 4;
9539 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
9540 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
9541 return -1;
9544 if (create_addr(p, channame, NULL)) {
9545 /* Maybe they're not registered, etc. */
9546 dialog_unlink_all(p, TRUE, TRUE);
9547 dialog_unref(p, "unref dialog inside for loop" );
9548 /* sip_destroy(p); */
9549 astman_send_error(s, m, "Could not create address");
9550 return -1;
9553 /* Notify is outgoing call */
9554 ast_set_flag(&p->flags[0], SIP_OUTGOING);
9556 /* Recalculate our side, and recalculate Call ID */
9557 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
9558 build_via(p);
9559 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
9560 build_callid_pvt(p);
9561 ao2_t_link(dialogs, p, "Linking in new name");
9562 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
9563 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
9565 if (!transmit_notify_custom(p, vars)) {
9566 astman_send_ack(s, m, "Notify Sent");
9567 } else {
9568 astman_send_error(s, m, "Unable to send notify");
9570 ast_variables_destroy(vars);
9571 return 0;
9574 static char mandescr_sipnotify[] =
9575 "Description: Sends a SIP Notify event\n"
9576 "All parameters for this event must be specified in the body of this request\n"
9577 "via multiple Variable: name=value sequences.\n"
9578 "Variables: \n"
9579 " *Channel: <peername> Peer to receive the notify. Required.\n"
9580 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
9581 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
9583 static const struct _map_x_s regstatestrings[] = {
9584 { REG_STATE_FAILED, "Failed" },
9585 { REG_STATE_UNREGISTERED, "Unregistered"},
9586 { REG_STATE_REGSENT, "Request Sent"},
9587 { REG_STATE_AUTHSENT, "Auth. Sent"},
9588 { REG_STATE_REGISTERED, "Registered"},
9589 { REG_STATE_REJECTED, "Rejected"},
9590 { REG_STATE_TIMEOUT, "Timeout"},
9591 { REG_STATE_NOAUTH, "No Authentication"},
9592 { -1, NULL } /* terminator */
9595 /*! \brief Convert registration state status to string */
9596 static const char *regstate2str(enum sipregistrystate regstate)
9598 return map_x_s(regstatestrings, regstate, "Unknown");
9601 /*! \brief Update registration with SIP Proxy.
9602 * Called from the scheduler when the previous registration expires,
9603 * so we don't have to cancel the pending event.
9604 * We assume the reference so the sip_registry is valid, since it
9605 * is stored in the scheduled event anyways.
9607 static int sip_reregister(const void *data)
9609 /* if we are here, we know that we need to reregister. */
9610 struct sip_registry *r= (struct sip_registry *) data;
9612 /* if we couldn't get a reference to the registry object, punt */
9613 if (!r)
9614 return 0;
9616 if (r->call && r->call->do_history)
9617 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
9618 /* Since registry's are only added/removed by the the monitor thread, this
9619 may be overkill to reference/dereference at all here */
9620 if (sipdebug)
9621 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
9623 r->expire = -1;
9624 __sip_do_register(r);
9625 registry_unref(r, "unreg the re-registered");
9626 return 0;
9629 /*! \brief Register with SIP proxy */
9630 static int __sip_do_register(struct sip_registry *r)
9632 int res;
9634 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
9635 return res;
9638 /*! \brief Registration timeout, register again
9639 * Registered as a timeout handler during transmit_register(),
9640 * to retransmit the packet if a reply does not come back.
9641 * This is called by the scheduler so the event is not pending anymore when
9642 * we are called.
9644 static int sip_reg_timeout(const void *data)
9647 /* if we are here, our registration timed out, so we'll just do it over */
9648 struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
9649 struct sip_pvt *p;
9650 int res;
9652 /* if we couldn't get a reference to the registry object, punt */
9653 if (!r)
9654 return 0;
9656 if (r->dnsmgr) {
9657 /* If the registration has timed out, maybe the IP changed. Force a refresh. */
9658 ast_dnsmgr_refresh(r->dnsmgr);
9661 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
9662 /* If the initial tranmission failed, we may not have an existing dialog,
9663 * so it is possible that r->call == NULL.
9664 * Otherwise destroy it, as we have a timeout so we don't want it.
9666 if (r->call) {
9667 /* Unlink us, destroy old call. Locking is not relevant here because all this happens
9668 in the single SIP manager thread. */
9669 p = r->call;
9670 sip_pvt_lock(p);
9671 p->needdestroy = 1;
9672 /* Pretend to ACK anything just in case */
9673 __sip_pretend_ack(p);
9674 sip_pvt_unlock(p);
9676 /* decouple the two objects */
9677 /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
9678 if (p->registry)
9679 p->registry = registry_unref(p->registry, "p->registry unreffed");
9680 r->call = dialog_unref(r->call, "unrefing r->call");
9682 /* If we have a limit, stop registration and give up */
9683 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
9684 /* Ok, enough is enough. Don't try any more */
9685 /* We could add an external notification here...
9686 steal it from app_voicemail :-) */
9687 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
9688 r->regstate = REG_STATE_FAILED;
9689 } else {
9690 r->regstate = REG_STATE_UNREGISTERED;
9691 r->timeout = -1;
9692 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
9694 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));
9695 registry_unref(r, "unreffing registry_unref r");
9696 return 0;
9699 /*! \brief Transmit register to SIP proxy or UA
9700 * auth = NULL on the initial registration (from sip_reregister())
9702 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
9704 struct sip_request req;
9705 char from[256];
9706 char to[256];
9707 char tmp[80];
9708 char addr[80];
9709 struct sip_pvt *p;
9710 int res;
9712 /* exit if we are already in process with this registrar ?*/
9713 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
9714 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
9715 return 0;
9718 if (r->dnsmgr == NULL) {
9719 char transport[MAXHOSTNAMELEN];
9720 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
9721 ast_dnsmgr_lookup(r->hostname, &r->us, &r->dnsmgr, global_srvlookup ? transport : NULL);
9724 if (r->call) { /* We have a registration */
9725 if (!auth) {
9726 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
9727 return 0;
9728 } else {
9729 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
9730 make_our_tag(p->tag, sizeof(p->tag)); /* create a new local tag for every register attempt */
9731 ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
9733 } else {
9734 /* Build callid for registration if we haven't registered before */
9735 if (!r->callid_valid) {
9736 build_callid_registry(r, internip.sin_addr, default_fromdomain);
9737 r->callid_valid = TRUE;
9739 /* Allocate SIP dialog for registration */
9740 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
9741 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
9742 return 0;
9745 if (p->do_history)
9746 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
9748 p->outboundproxy = obproxy_get(p, NULL);
9750 /* Use port number specified if no SRV record was found */
9751 if (!r->us.sin_port && r->portno)
9752 r->us.sin_port = htons(r->portno);
9754 /* Find address to hostname */
9755 if (create_addr(p, r->hostname, &r->us)) {
9756 /* we have what we hope is a temporary network error,
9757 * probably DNS. We need to reschedule a registration try */
9758 dialog_unlink_all(p, TRUE, TRUE);
9759 p = dialog_unref(p, "unref dialog after unlink_all");
9760 if (r->timeout > -1) {
9761 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
9762 registry_unref(_data, "del for REPLACE of registry ptr"),
9763 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
9764 registry_addref(r,"add for REPLACE registry ptr"));
9765 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
9766 } else {
9767 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
9768 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);
9770 r->regattempts++;
9771 return 0;
9774 /* Copy back Call-ID in case create_addr changed it */
9775 ast_string_field_set(r, callid, p->callid);
9776 if (!r->dnsmgr && r->portno) {
9777 p->sa.sin_port = htons(r->portno);
9778 p->recv.sin_port = htons(r->portno);
9779 } else { /* Set registry port to the port set from the peer definition/srv or default */
9780 r->portno = ntohs(p->sa.sin_port);
9782 ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
9783 r->call = dialog_ref(p, "copying dialog into registry r->call"); /* Save pointer to SIP dialog */
9784 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
9785 if (!ast_strlen_zero(r->secret)) /* Secret (password) */
9786 ast_string_field_set(p, peersecret, r->secret);
9787 if (!ast_strlen_zero(r->md5secret))
9788 ast_string_field_set(p, peermd5secret, r->md5secret);
9789 /* User name in this realm
9790 - if authuser is set, use that, otherwise use username */
9791 if (!ast_strlen_zero(r->authuser)) {
9792 ast_string_field_set(p, peername, r->authuser);
9793 ast_string_field_set(p, authname, r->authuser);
9794 } else if (!ast_strlen_zero(r->username)) {
9795 ast_string_field_set(p, peername, r->username);
9796 ast_string_field_set(p, authname, r->username);
9797 ast_string_field_set(p, fromuser, r->username);
9799 if (!ast_strlen_zero(r->username))
9800 ast_string_field_set(p, username, r->username);
9801 /* Save extension in packet */
9802 if (!ast_strlen_zero(r->callback))
9803 ast_string_field_set(p, exten, r->callback);
9805 /* Set transport and port so the correct contact is built */
9806 p->socket.type = r->transport;
9807 p->socket.port = htons(r->portno);
9810 check which address we should use in our contact header
9811 based on whether the remote host is on the external or
9812 internal network so we can register through nat
9814 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
9815 build_contact(p);
9818 /* set up a timeout */
9819 if (auth == NULL) {
9820 if (r->timeout > -1)
9821 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
9822 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
9823 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
9824 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
9825 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
9826 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
9829 if (strchr(r->username, '@')) {
9830 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
9831 if (!ast_strlen_zero(p->theirtag))
9832 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
9833 else
9834 snprintf(to, sizeof(to), "<sip:%s>", r->username);
9835 } else {
9836 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
9837 if (!ast_strlen_zero(p->theirtag))
9838 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
9839 else
9840 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
9843 /* Fromdomain is what we are registering to, regardless of actual
9844 host name from SRV */
9845 if (!ast_strlen_zero(p->fromdomain)) {
9846 if (r->portno && r->portno != STANDARD_SIP_PORT)
9847 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
9848 else
9849 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
9850 } else {
9851 if (r->portno && r->portno != STANDARD_SIP_PORT)
9852 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
9853 else
9854 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
9856 ast_string_field_set(p, uri, addr);
9858 p->branch ^= ast_random();
9860 init_req(&req, sipmethod, addr);
9862 /* Add to CSEQ */
9863 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
9864 p->ocseq = r->ocseq;
9866 build_via(p);
9867 add_header(&req, "Via", p->via);
9868 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
9869 add_header(&req, "From", from);
9870 add_header(&req, "To", to);
9871 add_header(&req, "Call-ID", p->callid);
9872 add_header(&req, "CSeq", tmp);
9873 if (!ast_strlen_zero(global_useragent))
9874 add_header(&req, "User-Agent", global_useragent);
9877 if (auth) /* Add auth header */
9878 add_header(&req, authheader, auth);
9879 else if (!ast_strlen_zero(r->nonce)) {
9880 char digest[1024];
9882 /* We have auth data to reuse, build a digest header.
9883 * Note, this is not always useful because some parties do not
9884 * like nonces to be reused (for good reasons!) so they will
9885 * challenge us anyways.
9887 if (sipdebug)
9888 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
9889 ast_string_field_set(p, realm, r->realm);
9890 ast_string_field_set(p, nonce, r->nonce);
9891 ast_string_field_set(p, domain, r->domain);
9892 ast_string_field_set(p, opaque, r->opaque);
9893 ast_string_field_set(p, qop, r->qop);
9894 p->noncecount = ++r->noncecount;
9896 memset(digest, 0, sizeof(digest));
9897 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
9898 add_header(&req, "Authorization", digest);
9899 else
9900 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
9904 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
9905 add_header(&req, "Expires", tmp);
9906 add_header(&req, "Contact", p->our_contact);
9907 add_header_contentLength(&req, 0);
9909 initialize_initreq(p, &req);
9910 if (sip_debug_test_pvt(p)) {
9911 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
9913 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
9914 r->regattempts++; /* Another attempt */
9915 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
9916 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
9917 dialog_unref(p, "p is finished here at the end of transmit_register");
9918 return res;
9921 /*! \brief Transmit text with SIP MESSAGE method */
9922 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
9924 struct sip_request req;
9926 reqprep(&req, p, SIP_MESSAGE, 0, 1);
9927 add_text(&req, text);
9928 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
9931 /*! \brief Allocate SIP refer structure */
9932 static int sip_refer_allocate(struct sip_pvt *p)
9934 p->refer = ast_calloc(1, sizeof(struct sip_refer));
9935 return p->refer ? 1 : 0;
9938 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
9939 \note this is currently broken as we have no way of telling the dialplan
9940 engine whether a transfer succeeds or fails.
9941 \todo Fix the transfer() dialplan function so that a transfer may fail
9943 static int transmit_refer(struct sip_pvt *p, const char *dest)
9945 struct sip_request req = {
9946 .headers = 0,
9948 char from[256];
9949 const char *of;
9950 char *c;
9951 char referto[256];
9952 char *ttag, *ftag;
9953 char *theirtag = ast_strdupa(p->theirtag);
9955 if (sipdebug)
9956 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
9958 /* Are we transfering an inbound or outbound call ? */
9959 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
9960 of = get_header(&p->initreq, "To");
9961 ttag = theirtag;
9962 ftag = p->tag;
9963 } else {
9964 of = get_header(&p->initreq, "From");
9965 ftag = theirtag;
9966 ttag = p->tag;
9969 ast_copy_string(from, of, sizeof(from));
9970 of = get_in_brackets(from);
9971 ast_string_field_set(p, from, of);
9972 if (!strncasecmp(of, "sip:", 4))
9973 of += 4;
9974 else if (!strncasecmp(of, "sips:", 5))
9975 of += 5;
9976 else
9977 ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
9978 /* Get just the username part */
9979 if ((c = strchr(dest, '@')))
9980 c = NULL;
9981 else if ((c = strchr(of, '@')))
9982 *c++ = '\0';
9983 if (c)
9984 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
9985 else
9986 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
9988 /* save in case we get 407 challenge */
9989 sip_refer_allocate(p);
9990 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
9991 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
9992 p->refer->status = REFER_SENT; /* Set refer status */
9994 reqprep(&req, p, SIP_REFER, 0, 1);
9996 add_header(&req, "Refer-To", referto);
9997 add_header(&req, "Allow", ALLOWED_METHODS);
9998 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
9999 if (!ast_strlen_zero(p->our_contact))
10000 add_header(&req, "Referred-By", p->our_contact);
10002 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10004 /* We should propably wait for a NOTIFY here until we ack the transfer */
10005 /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
10007 /*! \todo In theory, we should hang around and wait for a reply, before
10008 returning to the dial plan here. Don't know really how that would
10009 affect the transfer() app or the pbx, but, well, to make this
10010 useful we should have a STATUS code on transfer().
10015 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
10016 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
10018 struct sip_request req;
10020 reqprep(&req, p, SIP_INFO, 0, 1);
10021 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
10022 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10025 /*! \brief Send SIP INFO with video update request */
10026 static int transmit_info_with_vidupdate(struct sip_pvt *p)
10028 struct sip_request req;
10030 reqprep(&req, p, SIP_INFO, 0, 1);
10031 add_vidupdate(&req);
10032 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10035 /*! \brief Transmit generic SIP request
10036 returns XMIT_ERROR if transmit failed with a critical error (don't retry)
10038 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
10040 struct sip_request resp;
10042 if (sipmethod == SIP_ACK)
10043 p->invitestate = INV_CONFIRMED;
10045 reqprep(&resp, p, sipmethod, seqno, newbranch);
10046 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
10047 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
10049 add_header_contentLength(&resp, 0);
10050 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
10053 /*! \brief return the request and response heade for a 401 or 407 code */
10054 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
10056 if (code == WWW_AUTH) { /* 401 */
10057 *header = "WWW-Authenticate";
10058 *respheader = "Authorization";
10059 } else if (code == PROXY_AUTH) { /* 407 */
10060 *header = "Proxy-Authenticate";
10061 *respheader = "Proxy-Authorization";
10062 } else {
10063 ast_verbose("-- wrong response code %d\n", code);
10064 *header = *respheader = "Invalid";
10068 /*! \brief Transmit SIP request, auth added */
10069 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
10071 struct sip_request resp;
10073 reqprep(&resp, p, sipmethod, seqno, newbranch);
10074 if (!ast_strlen_zero(p->realm)) {
10075 char digest[1024];
10077 memset(digest, 0, sizeof(digest));
10078 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
10079 char *dummy, *response;
10080 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
10081 auth_headers(code, &dummy, &response);
10082 add_header(&resp, response, digest);
10083 } else
10084 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
10086 /* If we are hanging up and know a cause for that, send it in clear text to make
10087 debugging easier. */
10088 if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause) {
10089 char buf[10];
10091 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10092 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10093 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10096 add_header_contentLength(&resp, 0);
10097 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
10100 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
10101 static void destroy_association(struct sip_peer *peer)
10103 int realtimeregs = ast_check_realtime("sipregs");
10104 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
10106 if (!sip_cfg.ignore_regexpire) {
10107 if (peer->rt_fromcontact)
10108 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", NULL);
10109 else
10110 ast_db_del("SIP/Registry", peer->name);
10114 /*! \brief Expire registration of SIP peer */
10115 static int expire_register(const void *data)
10117 struct sip_peer *peer = (struct sip_peer *)data;
10119 if (!peer) /* Hmmm. We have no peer. Weird. */
10120 return 0;
10122 peer->expire = -1;
10123 memset(&peer->addr, 0, sizeof(peer->addr));
10125 destroy_association(peer); /* remove registration data from storage */
10127 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
10128 register_peer_exten(peer, FALSE); /* Remove regexten */
10129 ast_device_state_changed("SIP/%s", peer->name);
10131 /* Do we need to release this peer from memory?
10132 Only for realtime peers and autocreated peers
10134 if (peer->is_realtime)
10135 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
10137 if (peer->selfdestruct ||
10138 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
10139 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
10140 if (peer->addr.sin_addr.s_addr) {
10141 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
10146 return 0;
10149 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
10150 static int sip_poke_peer_s(const void *data)
10152 struct sip_peer *peer = (struct sip_peer *)data;
10154 peer->pokeexpire = -1;
10155 sip_poke_peer(peer, 0);
10156 return 0;
10159 /*! \brief Get registration details from Asterisk DB */
10160 static void reg_source_db(struct sip_peer *peer)
10162 char data[256];
10163 struct in_addr in;
10164 int expiry;
10165 int port;
10166 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
10168 if (peer->rt_fromcontact)
10169 return;
10170 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
10171 return;
10173 scan = data;
10174 addr = strsep(&scan, ":");
10175 port_str = strsep(&scan, ":");
10176 expiry_str = strsep(&scan, ":");
10177 username = strsep(&scan, ":");
10178 contact = scan; /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
10180 if (!inet_aton(addr, &in))
10181 return;
10183 if (port_str)
10184 port = atoi(port_str);
10185 else
10186 return;
10188 if (expiry_str)
10189 expiry = atoi(expiry_str);
10190 else
10191 return;
10193 if (username)
10194 ast_copy_string(peer->username, username, sizeof(peer->username));
10195 if (contact)
10196 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
10198 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
10199 peer->name, peer->username, ast_inet_ntoa(in), port, expiry);
10201 memset(&peer->addr, 0, sizeof(peer->addr));
10202 peer->addr.sin_family = AF_INET;
10203 peer->addr.sin_addr = in;
10204 peer->addr.sin_port = htons(port);
10205 if (sipsock < 0) {
10206 /* SIP isn't up yet, so schedule a poke only, pretty soon */
10207 AST_SCHED_REPLACE(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
10208 } else {
10209 sip_poke_peer(peer, 0);
10211 AST_SCHED_REPLACE(peer->expire, sched, (expiry + 10) * 1000, expire_register, peer);
10212 register_peer_exten(peer, TRUE);
10215 /*! \brief Save contact header for 200 OK on INVITE */
10216 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
10218 char contact[SIPBUFSIZE];
10219 char *c;
10221 /* Look for brackets */
10222 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10223 c = get_in_brackets(contact);
10225 /* Save full contact to call pvt for later bye or re-invite */
10226 ast_string_field_set(pvt, fullcontact, c);
10228 /* Save URI for later ACKs, BYE or RE-invites */
10229 ast_string_field_set(pvt, okcontacturi, c);
10231 /* We should return false for URI:s we can't handle,
10232 like tel:, mailto:,ldap: etc */
10233 return TRUE;
10236 /*! \brief Change the other partys IP address based on given contact */
10237 static int set_address_from_contact(struct sip_pvt *pvt)
10239 struct hostent *hp;
10240 struct ast_hostent ahp;
10241 int port;
10242 char *host, *pt;
10243 char contact_buf[256];
10244 char contact2_buf[256];
10245 char *contact, *contact2;
10247 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
10248 /* NAT: Don't trust the contact field. Just use what they came to us
10249 with. */
10250 pvt->sa = pvt->recv;
10251 return 0;
10254 /* Work on a copy */
10255 ast_copy_string(contact_buf, pvt->fullcontact, sizeof(contact_buf));
10256 ast_copy_string(contact2_buf, pvt->fullcontact, sizeof(contact2_buf));
10257 contact = contact_buf;
10258 contact2 = contact2_buf;
10260 /* We have only the part in <brackets> here so we just need to parse a SIP URI.*/
10262 if (pvt->socket.type == SIP_TRANSPORT_TLS) {
10263 if (parse_uri(contact, "sips:", &contact, NULL, &host, &pt, NULL)) {
10264 if (parse_uri(contact2, "sip:", &contact, NULL, &host, &pt, NULL))
10265 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10267 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10268 } else {
10269 if (parse_uri(contact, "sip:", &contact, NULL, &host, &pt, NULL))
10270 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10271 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10274 if (sip_debug_test_pvt(pvt)) {
10275 ast_verbose("--- set_address_from_contact host '%s'\n", host);
10278 /* XXX This could block for a long time XXX */
10279 /* We should only do this if it's a name, not an IP */
10280 hp = ast_gethostbyname(host, &ahp);
10281 if (!hp) {
10282 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
10283 return -1;
10285 pvt->sa.sin_family = AF_INET;
10286 memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
10287 pvt->sa.sin_port = htons(port);
10289 return 0;
10293 /*! \brief Parse contact header and save registration (peer registration) */
10294 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
10296 char contact[SIPBUFSIZE];
10297 char data[SIPBUFSIZE];
10298 const char *expires = get_header(req, "Expires");
10299 int expiry = atoi(expires);
10300 char *curi, *host, *pt, *curi2;
10301 int port;
10302 const char *useragent;
10303 struct hostent *hp;
10304 struct ast_hostent ahp;
10305 struct sockaddr_in oldsin;
10307 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10309 if (ast_strlen_zero(expires)) { /* No expires header, try look in Contact: */
10310 char *s = strcasestr(contact, ";expires=");
10311 if (s) {
10312 expires = strsep(&s, ";"); /* trim ; and beyond */
10313 if (sscanf(expires + 9, "%d", &expiry) != 1)
10314 expiry = default_expiry;
10315 } else {
10316 /* Nothing has been specified */
10317 expiry = default_expiry;
10321 copy_socket_data(&peer->socket, &req->socket);
10322 copy_socket_data(&pvt->socket, &peer->socket);
10324 /* Look for brackets */
10325 curi = contact;
10326 if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
10327 strsep(&curi, ";"); /* This is Header options, not URI options */
10328 curi = get_in_brackets(contact);
10329 curi2 = ast_strdupa(curi);
10331 /* if they did not specify Contact: or Expires:, they are querying
10332 what we currently have stored as their contact address, so return
10335 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
10336 /* If we have an active registration, tell them when the registration is going to expire */
10337 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
10338 pvt->expiry = ast_sched_when(sched, peer->expire);
10339 return PARSE_REGISTER_QUERY;
10340 } else if (!strcasecmp(curi, "*") || !expiry) { /* Unregister this peer */
10341 /* This means remove all registrations and return OK */
10342 memset(&peer->addr, 0, sizeof(peer->addr));
10343 AST_SCHED_DEL(sched, peer->expire);
10345 destroy_association(peer);
10347 register_peer_exten(peer, FALSE); /* Remove extension from regexten= setting in sip.conf */
10348 peer->fullcontact[0] = '\0';
10349 peer->useragent[0] = '\0';
10350 peer->sipoptions = 0;
10351 peer->lastms = 0;
10353 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
10354 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
10355 return PARSE_REGISTER_UPDATE;
10358 /* Store whatever we got as a contact from the client */
10359 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
10361 /* For the 200 OK, we should use the received contact */
10362 ast_string_field_build(pvt, our_contact, "<%s>", curi);
10364 /* Make sure it's a SIP URL */
10365 if (pvt->socket.type == SIP_TRANSPORT_TLS) {
10366 if (parse_uri(curi, "sips:", &curi, NULL, &host, &pt, NULL)) {
10367 if (parse_uri(curi2, "sip:", &curi, NULL, &host, &pt, NULL))
10368 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10370 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10371 } else {
10372 if (parse_uri(curi, "sip:", &curi, NULL, &host, &pt, NULL))
10373 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10374 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10377 oldsin = peer->addr;
10378 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
10379 /* XXX This could block for a long time XXX */
10380 hp = ast_gethostbyname(host, &ahp);
10381 if (!hp) {
10382 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
10383 return PARSE_REGISTER_FAILED;
10385 peer->addr.sin_family = AF_INET;
10386 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
10387 peer->addr.sin_port = htons(port);
10388 } else {
10389 /* Don't trust the contact field. Just use what they came to us
10390 with */
10391 peer->addr = pvt->recv;
10394 /* Save SIP options profile */
10395 peer->sipoptions = pvt->sipoptions;
10397 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
10398 ast_copy_string(peer->username, curi, sizeof(peer->username));
10400 AST_SCHED_DEL(sched, peer->expire);
10401 if (expiry > max_expiry)
10402 expiry = max_expiry;
10403 if (expiry < min_expiry)
10404 expiry = min_expiry;
10405 peer->expire = peer->is_realtime ? -1 :
10406 ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
10407 pvt->expiry = expiry;
10408 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);
10409 /* Saving TCP connections is useless, we won't be able to reconnect */
10410 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
10411 ast_db_put("SIP/Registry", peer->name, data);
10412 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));
10414 /* Is this a new IP address for us? */
10415 if (inaddrcmp(&peer->addr, &oldsin)) {
10416 sip_poke_peer(peer, 0);
10417 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);
10418 register_peer_exten(peer, TRUE);
10421 /* Save User agent */
10422 useragent = get_header(req, "User-Agent");
10423 if (strcasecmp(useragent, peer->useragent)) { /* XXX copy if they are different ? */
10424 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
10425 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
10427 return PARSE_REGISTER_UPDATE;
10430 /*! \brief Remove route from route list */
10431 static void free_old_route(struct sip_route *route)
10433 struct sip_route *next;
10435 while (route) {
10436 next = route->next;
10437 ast_free(route);
10438 route = next;
10442 /*! \brief List all routes - mostly for debugging */
10443 static void list_route(struct sip_route *route)
10445 if (!route)
10446 ast_verbose("list_route: no route\n");
10447 else {
10448 for (;route; route = route->next)
10449 ast_verbose("list_route: hop: <%s>\n", route->hop);
10453 /*! \brief Build route list from Record-Route header */
10454 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
10456 struct sip_route *thishop, *head, *tail;
10457 int start = 0;
10458 int len;
10459 const char *rr, *contact, *c;
10461 /* Once a persistant route is set, don't fool with it */
10462 if (p->route && p->route_persistant) {
10463 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
10464 return;
10467 if (p->route) {
10468 free_old_route(p->route);
10469 p->route = NULL;
10472 /* We only want to create the route set the first time this is called */
10473 p->route_persistant = 1;
10475 /* Build a tailq, then assign it to p->route when done.
10476 * If backwards, we add entries from the head so they end up
10477 * in reverse order. However, we do need to maintain a correct
10478 * tail pointer because the contact is always at the end.
10480 head = NULL;
10481 tail = head;
10482 /* 1st we pass through all the hops in any Record-Route headers */
10483 for (;;) {
10484 /* Each Record-Route header */
10485 rr = __get_header(req, "Record-Route", &start);
10486 if (*rr == '\0')
10487 break;
10488 for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
10489 ++rr;
10490 len = strcspn(rr, ">") + 1;
10491 /* Make a struct route */
10492 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
10493 /* ast_calloc is not needed because all fields are initialized in this block */
10494 ast_copy_string(thishop->hop, rr, len);
10495 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
10496 /* Link in */
10497 if (backwards) {
10498 /* Link in at head so they end up in reverse order */
10499 thishop->next = head;
10500 head = thishop;
10501 /* If this was the first then it'll be the tail */
10502 if (!tail)
10503 tail = thishop;
10504 } else {
10505 thishop->next = NULL;
10506 /* Link in at the end */
10507 if (tail)
10508 tail->next = thishop;
10509 else
10510 head = thishop;
10511 tail = thishop;
10517 /* Only append the contact if we are dealing with a strict router */
10518 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
10519 /* 2nd append the Contact: if there is one */
10520 /* Can be multiple Contact headers, comma separated values - we just take the first */
10521 contact = get_header(req, "Contact");
10522 if (!ast_strlen_zero(contact)) {
10523 ast_debug(2, "build_route: Contact hop: %s\n", contact);
10524 /* Look for <: delimited address */
10525 c = strchr(contact, '<');
10526 if (c) {
10527 /* Take to > */
10528 ++c;
10529 len = strcspn(c, ">") + 1;
10530 } else {
10531 /* No <> - just take the lot */
10532 c = contact;
10533 len = strlen(contact) + 1;
10535 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
10536 /* ast_calloc is not needed because all fields are initialized in this block */
10537 ast_copy_string(thishop->hop, c, len);
10538 thishop->next = NULL;
10539 /* Goes at the end */
10540 if (tail)
10541 tail->next = thishop;
10542 else
10543 head = thishop;
10548 /* Store as new route */
10549 p->route = head;
10551 /* For debugging dump what we ended up with */
10552 if (sip_debug_test_pvt(p))
10553 list_route(p->route);
10556 AST_THREADSTORAGE(check_auth_buf);
10557 #define CHECK_AUTH_BUF_INITLEN 256
10559 /*! \brief Check user authorization from peer definition
10560 Some actions, like REGISTER and INVITEs from peers require
10561 authentication (if peer have secret set)
10562 \return 0 on success, non-zero on error
10564 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
10565 const char *secret, const char *md5secret, int sipmethod,
10566 char *uri, enum xmittype reliable, int ignore)
10568 const char *response;
10569 char *reqheader, *respheader;
10570 const char *authtoken;
10571 char a1_hash[256];
10572 char resp_hash[256]="";
10573 char *c;
10574 int wrongnonce = FALSE;
10575 int good_response;
10576 const char *usednonce = p->randdata;
10577 struct ast_str *buf;
10578 int res;
10580 /* table of recognised keywords, and their value in the digest */
10581 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
10582 struct x {
10583 const char *key;
10584 const char *s;
10585 } *i, keys[] = {
10586 [K_RESP] = { "response=", "" },
10587 [K_URI] = { "uri=", "" },
10588 [K_USER] = { "username=", "" },
10589 [K_NONCE] = { "nonce=", "" },
10590 [K_LAST] = { NULL, NULL}
10593 /* Always OK if no secret */
10594 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
10595 return AUTH_SUCCESSFUL;
10597 /* Always auth with WWW-auth since we're NOT a proxy */
10598 /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
10599 response = "401 Unauthorized";
10602 * Note the apparent swap of arguments below, compared to other
10603 * usages of auth_headers().
10605 auth_headers(WWW_AUTH, &respheader, &reqheader);
10607 authtoken = get_header(req, reqheader);
10608 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
10609 /* This is a retransmitted invite/register/etc, don't reconstruct authentication
10610 information */
10611 if (!reliable) {
10612 /* Resend message if this was NOT a reliable delivery. Otherwise the
10613 retransmission should get it */
10614 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
10615 /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
10616 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10618 return AUTH_CHALLENGE_SENT;
10619 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
10620 /* We have no auth, so issue challenge and request authentication */
10621 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
10622 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
10623 /* Schedule auto destroy in 32 seconds */
10624 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10625 return AUTH_CHALLENGE_SENT;
10628 /* --- We have auth, so check it */
10630 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
10631 an example in the spec of just what it is you're doing a hash on. */
10633 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
10634 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
10636 /* Make a copy of the response and parse it */
10637 res = ast_str_set(&buf, 0, "%s", authtoken);
10639 if (res == AST_DYNSTR_BUILD_FAILED)
10640 return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
10642 c = buf->str;
10644 while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
10645 for (i = keys; i->key != NULL; i++) {
10646 const char *separator = ","; /* default */
10648 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
10649 continue;
10650 /* Found. Skip keyword, take text in quotes or up to the separator. */
10651 c += strlen(i->key);
10652 if (*c == '"') { /* in quotes. Skip first and look for last */
10653 c++;
10654 separator = "\"";
10656 i->s = c;
10657 strsep(&c, separator);
10658 break;
10660 if (i->key == NULL) /* not found, jump after space or comma */
10661 strsep(&c, " ,");
10664 /* Verify that digest username matches the username we auth as */
10665 if (strcmp(username, keys[K_USER].s)) {
10666 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
10667 username, keys[K_USER].s);
10668 /* Oops, we're trying something here */
10669 return AUTH_USERNAME_MISMATCH;
10672 /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
10673 if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
10674 wrongnonce = TRUE;
10675 usednonce = keys[K_NONCE].s;
10678 if (!ast_strlen_zero(md5secret))
10679 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
10680 else {
10681 char a1[256];
10682 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
10683 ast_md5_hash(a1_hash, a1);
10686 /* compute the expected response to compare with what we received */
10688 char a2[256];
10689 char a2_hash[256];
10690 char resp[256];
10692 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
10693 S_OR(keys[K_URI].s, uri));
10694 ast_md5_hash(a2_hash, a2);
10695 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
10696 ast_md5_hash(resp_hash, resp);
10699 good_response = keys[K_RESP].s &&
10700 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
10701 if (wrongnonce) {
10702 if (good_response) {
10703 if (sipdebug)
10704 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
10705 /* We got working auth token, based on stale nonce . */
10706 ast_string_field_build(p, randdata, "%08lx", ast_random());
10707 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
10708 } else {
10709 /* Everything was wrong, so give the device one more try with a new challenge */
10710 if (!req->ignore) {
10711 if (sipdebug)
10712 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
10713 ast_string_field_build(p, randdata, "%08lx", ast_random());
10714 } else {
10715 if (sipdebug)
10716 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
10718 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
10721 /* Schedule auto destroy in 32 seconds */
10722 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
10723 return AUTH_CHALLENGE_SENT;
10725 if (good_response) {
10726 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
10727 return AUTH_SUCCESSFUL;
10730 /* Ok, we have a bad username/secret pair */
10731 /* Tell the UAS not to re-send this authentication data, because
10732 it will continue to fail
10735 return AUTH_SECRET_FAILED;
10738 /*! \brief Change onhold state of a peer using a pvt structure */
10739 static void sip_peer_hold(struct sip_pvt *p, int hold)
10741 struct sip_peer *peer = find_peer(p->peername, NULL, 1);
10743 if (!peer)
10744 return;
10746 /* If they put someone on hold, increment the value... otherwise decrement it */
10747 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
10749 /* Request device state update */
10750 ast_device_state_changed("SIP/%s", peer->name);
10751 unref_peer(peer, "sip_peer_hold: from find_peer operation");
10753 return;
10756 /*! \brief Receive MWI events that we have subscribed to */
10757 static void mwi_event_cb(const struct ast_event *event, void *userdata)
10759 struct sip_peer *peer = userdata;
10761 ao2_lock(peer);
10762 sip_send_mwi_to_peer(peer, event, 0);
10763 ao2_unlock(peer);
10766 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
10767 \note If you add an "hint" priority to the extension in the dial plan,
10768 you will get notifications on device state changes */
10769 static int cb_extensionstate(char *context, char* exten, int state, void *data)
10771 struct sip_pvt *p = data;
10773 sip_pvt_lock(p);
10775 switch(state) {
10776 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
10777 case AST_EXTENSION_REMOVED: /* Extension is gone */
10778 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
10779 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
10780 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
10781 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
10782 p->stateid = -1;
10783 p->subscribed = NONE;
10784 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
10785 break;
10786 default: /* Tell user */
10787 p->laststate = state;
10788 break;
10790 if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
10791 if (!p->pendinginvite) {
10792 transmit_state_notify(p, state, 1, FALSE);
10793 } else {
10794 /* We already have a NOTIFY sent that is not answered. Queue the state up.
10795 if many state changes happen meanwhile, we will only send a notification of the last one */
10796 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
10799 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
10800 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
10802 sip_pvt_unlock(p);
10804 return 0;
10807 /*! \brief Send a fake 401 Unauthorized response when the administrator
10808 wants to hide the names of local users/peers from fishers
10810 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
10812 ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
10813 transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
10817 * Terminate the uri at the first ';' or space.
10818 * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
10819 * but don't do it for the time being. Remember the uri format is:
10820 *\verbatim
10822 * sip:user:password@host:port;uri-parameters?headers
10823 * sips:user:password@host:port;uri-parameters?headers
10825 *\endverbatim
10827 static char *terminate_uri(char *uri)
10829 char *t = uri;
10830 while (*t && *t > ' ' && *t != ';')
10831 t++;
10832 *t = '\0';
10833 return uri;
10836 /*! \brief Verify registration of user
10837 - Registration is done in several steps, first a REGISTER without auth
10838 to get a challenge (nonce) then a second one with auth
10839 - Registration requests are only matched with peers that are marked as "dynamic"
10841 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
10842 struct sip_request *req, char *uri)
10844 enum check_auth_result res = AUTH_NOT_FOUND;
10845 struct sip_peer *peer;
10846 char tmp[256];
10847 char *name, *c;
10848 char *domain;
10850 terminate_uri(uri); /* warning, overwrite the string */
10852 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
10853 if (pedanticsipchecking)
10854 ast_uri_decode(tmp);
10856 c = get_in_brackets(tmp);
10857 c = remove_uri_parameters(c);
10859 if (!strncasecmp(c, "sip:", 4)) {
10860 name = c + 4;
10861 } else if (!strncasecmp(c, "sips:", 5)) {
10862 name = c + 5;
10863 } else {
10864 name = c;
10865 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
10868 /* XXX here too we interpret a missing @domain as a name-only
10869 * URI, whereas the RFC says this is a domain-only uri.
10871 /* Strip off the domain name */
10872 if ((c = strchr(name, '@'))) {
10873 *c++ = '\0';
10874 domain = c;
10875 if ((c = strchr(domain, ':'))) /* Remove :port */
10876 *c = '\0';
10877 if (!AST_LIST_EMPTY(&domain_list)) {
10878 if (!check_sip_domain(domain, NULL, 0)) {
10879 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
10880 return AUTH_UNKNOWN_DOMAIN;
10884 c = strchr(name, ';'); /* Remove any Username parameters */
10885 if (c)
10886 *c = '\0';
10888 ast_string_field_set(p, exten, name);
10889 build_contact(p);
10890 peer = find_peer(name, NULL, 1);
10891 if (!(peer && ast_apply_ha(peer->ha, sin))) {
10892 /* Peer fails ACL check */
10893 if (peer) {
10894 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
10895 peer = NULL;
10896 res = AUTH_ACL_FAILED;
10897 } else
10898 res = AUTH_NOT_FOUND;
10901 if (peer) {
10902 /* Set Frame packetization */
10903 if (p->rtp) {
10904 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
10905 p->autoframing = peer->autoframing;
10907 if (!peer->host_dynamic) {
10908 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
10909 res = AUTH_PEER_NOT_DYNAMIC;
10910 } else {
10911 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
10912 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
10913 transmit_response(p, "100 Trying", req);
10914 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
10915 if (sip_cancel_destroy(p))
10916 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
10918 /* We have a successful registration attempt with proper authentication,
10919 now, update the peer */
10920 switch (parse_register_contact(p, peer, req)) {
10921 case PARSE_REGISTER_FAILED:
10922 ast_log(LOG_WARNING, "Failed to parse contact info\n");
10923 transmit_response_with_date(p, "400 Bad Request", req);
10924 peer->lastmsgssent = -1;
10925 res = 0;
10926 break;
10927 case PARSE_REGISTER_QUERY:
10928 transmit_response_with_date(p, "200 OK", req);
10929 peer->lastmsgssent = -1;
10930 res = 0;
10931 break;
10932 case PARSE_REGISTER_UPDATE:
10933 update_peer(peer, p->expiry);
10934 /* Say OK and ask subsystem to retransmit msg counter */
10935 transmit_response_with_date(p, "200 OK", req);
10936 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
10937 peer->lastmsgssent = -1;
10938 res = 0;
10939 break;
10944 if (!peer && autocreatepeer) {
10945 /* Create peer if we have autocreate mode enabled */
10946 peer = temp_peer(name);
10947 if (peer) {
10948 ao2_t_link(peers, peer, "link peer into peer table");
10949 if (peer->addr.sin_addr.s_addr) {
10950 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
10953 if (sip_cancel_destroy(p))
10954 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
10955 switch (parse_register_contact(p, peer, req)) {
10956 case PARSE_REGISTER_FAILED:
10957 ast_log(LOG_WARNING, "Failed to parse contact info\n");
10958 transmit_response_with_date(p, "400 Bad Request", req);
10959 peer->lastmsgssent = -1;
10960 res = 0;
10961 break;
10962 case PARSE_REGISTER_QUERY:
10963 transmit_response_with_date(p, "200 OK", req);
10964 peer->lastmsgssent = -1;
10965 res = 0;
10966 break;
10967 case PARSE_REGISTER_UPDATE:
10968 /* Say OK and ask subsystem to retransmit msg counter */
10969 transmit_response_with_date(p, "200 OK", req);
10970 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));
10971 peer->lastmsgssent = -1;
10972 res = 0;
10973 break;
10977 if (!res) {
10978 ast_device_state_changed("SIP/%s", peer->name);
10980 if (res < 0) {
10981 switch (res) {
10982 case AUTH_SECRET_FAILED:
10983 /* Wrong password in authentication. Go away, don't try again until you fixed it */
10984 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
10985 if (global_authfailureevents)
10986 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",
10987 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10988 break;
10989 case AUTH_USERNAME_MISMATCH:
10990 /* Username and digest username does not match.
10991 Asterisk uses the From: username for authentication. We need the
10992 users to use the same authentication user name until we support
10993 proper authentication by digest auth name */
10994 transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
10995 if (global_authfailureevents)
10996 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",
10997 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
10998 break;
10999 case AUTH_NOT_FOUND:
11000 case AUTH_PEER_NOT_DYNAMIC:
11001 case AUTH_ACL_FAILED:
11002 if (global_alwaysauthreject) {
11003 transmit_fake_auth_response(p, &p->initreq, 1);
11004 } else {
11005 /* URI not found */
11006 if (res == AUTH_PEER_NOT_DYNAMIC) {
11007 transmit_response(p, "403 Forbidden", &p->initreq);
11008 if (global_authfailureevents)
11009 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",
11010 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11012 else
11013 transmit_response(p, "404 Not found", &p->initreq);
11014 if (global_authfailureevents)
11015 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",
11016 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11018 break;
11019 default:
11020 break;
11023 if (peer)
11024 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
11026 return res;
11029 /*! \brief Translate referring cause */
11030 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
11032 if (strcmp(reason, "unknown")==0) {
11033 ast_string_field_set(p, redircause, "UNKNOWN");
11034 } else if (strcmp(reason, "user-busy")==0) {
11035 ast_string_field_set(p, redircause, "BUSY");
11036 } else if (strcmp(reason, "no-answer")==0) {
11037 ast_string_field_set(p, redircause, "NOANSWER");
11038 } else if (strcmp(reason, "unavailable")==0) {
11039 ast_string_field_set(p, redircause, "UNREACHABLE");
11040 } else if (strcmp(reason, "unconditional")==0) {
11041 ast_string_field_set(p, redircause, "UNCONDITIONAL");
11042 } else if (strcmp(reason, "time-of-day")==0) {
11043 ast_string_field_set(p, redircause, "UNKNOWN");
11044 } else if (strcmp(reason, "do-not-disturb")==0) {
11045 ast_string_field_set(p, redircause, "UNKNOWN");
11046 } else if (strcmp(reason, "deflection")==0) {
11047 ast_string_field_set(p, redircause, "UNKNOWN");
11048 } else if (strcmp(reason, "follow-me")==0) {
11049 ast_string_field_set(p, redircause, "UNKNOWN");
11050 } else if (strcmp(reason, "out-of-service")==0) {
11051 ast_string_field_set(p, redircause, "UNREACHABLE");
11052 } else if (strcmp(reason, "away")==0) {
11053 ast_string_field_set(p, redircause, "UNREACHABLE");
11054 } else {
11055 ast_string_field_set(p, redircause, "UNKNOWN");
11059 /*! \brief Get referring dnis */
11060 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
11062 char tmp[256], *exten, *rexten, *rdomain;
11063 char *params, *reason = NULL;
11064 struct sip_request *req;
11066 req = oreq ? oreq : &p->initreq;
11068 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
11069 if (ast_strlen_zero(tmp))
11070 return 0;
11072 exten = get_in_brackets(tmp);
11073 if (!strncasecmp(exten, "sip:", 4)) {
11074 exten += 4;
11075 } else if (!strncasecmp(exten, "sips:", 5)) {
11076 exten += 5;
11077 } else {
11078 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
11079 return -1;
11082 /* Get diversion-reason param if present */
11083 if ((params = strchr(tmp, ';'))) {
11084 *params = '\0'; /* Cut off parameters */
11085 params++;
11086 while (*params == ';' || *params == ' ')
11087 params++;
11088 /* Check if we have a reason parameter */
11089 if ((reason = strcasestr(params, "reason="))) {
11090 reason+=7;
11091 /* Remove enclosing double-quotes */
11092 if (*reason == '"')
11093 ast_strip_quoted(reason, "\"", "\"");
11094 if (!ast_strlen_zero(reason)) {
11095 sip_set_redirstr(p, reason);
11096 if (p->owner) {
11097 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
11098 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
11104 rdomain = exten;
11105 rexten = strsep(&rdomain, "@"); /* trim anything after @ */
11106 if (p->owner)
11107 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
11109 if (sip_debug_test_pvt(p))
11110 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
11112 ast_string_field_set(p, rdnis, rexten);
11114 return 0;
11117 /*! \brief Find out who the call is for.
11118 We use the request uri as a destination.
11119 This code assumes authentication has been done, so that the
11120 device (peer/user) context is already set.
11121 \return 0 on success (found a matching extension),
11122 1 for pickup extension or overlap dialling support (if we support it),
11123 -1 on error.
11125 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
11127 char tmp[256] = "", *uri, *a;
11128 char tmpf[256] = "", *from = NULL;
11129 struct sip_request *req;
11130 char *colon;
11132 req = oreq;
11133 if (!req)
11134 req = &p->initreq;
11136 /* Find the request URI */
11137 if (req->rlPart2)
11138 ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
11140 if (pedanticsipchecking)
11141 ast_uri_decode(tmp);
11143 uri = get_in_brackets(tmp);
11145 if (!strncasecmp(uri, "sip:", 4)) {
11146 uri += 4;
11147 } else if (!strncasecmp(uri, "sips:", 5)) {
11148 uri += 5;
11149 } else {
11150 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
11151 return -1;
11154 /* Now find the From: caller ID and name */
11155 /* XXX Why is this done in get_destination? Isn't it already done?
11156 Needs to be checked
11158 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
11159 if (!ast_strlen_zero(tmpf)) {
11160 if (pedanticsipchecking)
11161 ast_uri_decode(tmpf);
11162 from = get_in_brackets(tmpf);
11165 if (!ast_strlen_zero(from)) {
11166 if (!strncasecmp(from, "sip:", 4)) {
11167 from += 4;
11168 } else if (!strncasecmp(from, "sips:", 5)) {
11169 from += 5;
11170 } else {
11171 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
11172 return -1;
11174 if ((a = strchr(from, '@')))
11175 *a++ = '\0';
11176 else
11177 a = from; /* just a domain */
11178 from = strsep(&from, ";"); /* Remove userinfo options */
11179 a = strsep(&a, ";"); /* Remove URI options */
11180 ast_string_field_set(p, fromdomain, a);
11183 /* Skip any options and find the domain */
11185 /* Get the target domain */
11186 if ((a = strchr(uri, '@'))) {
11187 *a++ = '\0';
11188 } else { /* No username part */
11189 a = uri;
11190 uri = "s"; /* Set extension to "s" */
11192 colon = strchr(a, ':'); /* Remove :port */
11193 if (colon)
11194 *colon = '\0';
11196 uri = strsep(&uri, ";"); /* Remove userinfo options */
11197 a = strsep(&a, ";"); /* Remove URI options */
11199 ast_string_field_set(p, domain, a);
11201 if (!AST_LIST_EMPTY(&domain_list)) {
11202 char domain_context[AST_MAX_EXTENSION];
11204 domain_context[0] = '\0';
11205 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
11206 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
11207 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
11208 return -2;
11211 /* If we have a context defined, overwrite the original context */
11212 if (!ast_strlen_zero(domain_context))
11213 ast_string_field_set(p, context, domain_context);
11216 /* If the request coming in is a subscription and subscribecontext has been specified use it */
11217 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
11218 ast_string_field_set(p, context, p->subscribecontext);
11220 if (sip_debug_test_pvt(p))
11221 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
11223 /* If this is a subscription we actually just need to see if a hint exists for the extension */
11224 if (req->method == SIP_SUBSCRIBE) {
11225 char hint[AST_MAX_EXTENSION];
11226 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
11227 } else {
11228 /* Check the dialplan for the username part of the request URI,
11229 the domain will be stored in the SIPDOMAIN variable
11230 Since extensions.conf can have unescaped characters, try matching a decoded
11231 uri in addition to the non-decoded uri
11232 Return 0 if we have a matching extension */
11233 char *decoded_uri = ast_strdupa(uri);
11234 ast_uri_decode(decoded_uri);
11235 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)) ||
11236 !strcmp(uri, ast_pickup_ext())) {
11237 if (!oreq)
11238 ast_string_field_set(p, exten, uri);
11239 return 0;
11243 /* Return 1 for pickup extension or overlap dialling support (if we support it) */
11244 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
11245 ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) ||
11246 !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
11247 return 1;
11250 return -1;
11253 /*! \brief Lock dialog lock and find matching pvt lock
11254 - Their tag is fromtag, our tag is to-tag
11255 - This means that in some transactions, totag needs to be their tag :-)
11256 depending upon the direction
11257 \return a reference, remember to release it when done
11259 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
11261 struct sip_pvt *sip_pvt_ptr;
11262 struct sip_pvt tmp_dialog = {
11263 .callid = callid,
11266 if (totag)
11267 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
11269 /* Search dialogs and find the match */
11271 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
11272 if (sip_pvt_ptr) {
11273 char *ourtag = sip_pvt_ptr->tag;
11274 /* Go ahead and lock it (and its owner) before returning */
11275 sip_pvt_lock(sip_pvt_ptr);
11277 if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag)))) {
11278 sip_pvt_unlock(sip_pvt_ptr);
11279 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",
11280 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
11281 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
11282 return 0;
11285 if (totag)
11286 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
11287 ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
11288 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
11290 /* deadlock avoidance... */
11291 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
11292 sip_pvt_unlock(sip_pvt_ptr);
11293 usleep(1);
11294 sip_pvt_lock(sip_pvt_ptr);
11298 return sip_pvt_ptr;
11301 /*! \brief Call transfer support (the REFER method)
11302 * Extracts Refer headers into pvt dialog structure */
11303 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
11306 const char *p_referred_by = NULL;
11307 char *h_refer_to = NULL;
11308 char *h_referred_by = NULL;
11309 char *refer_to;
11310 const char *p_refer_to;
11311 char *referred_by_uri = NULL;
11312 char *ptr;
11313 struct sip_request *req = NULL;
11314 const char *transfer_context = NULL;
11315 struct sip_refer *referdata;
11318 req = outgoing_req;
11319 referdata = transferer->refer;
11321 if (!req)
11322 req = &transferer->initreq;
11324 p_refer_to = get_header(req, "Refer-To");
11325 if (ast_strlen_zero(p_refer_to)) {
11326 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
11327 return -2; /* Syntax error */
11329 h_refer_to = ast_strdupa(p_refer_to);
11330 refer_to = get_in_brackets(h_refer_to);
11331 if (pedanticsipchecking)
11332 ast_uri_decode(refer_to);
11334 if (!strncasecmp(refer_to, "sip:", 4)) {
11335 refer_to += 4; /* Skip sip: */
11336 } else if (!strncasecmp(refer_to, "sips:", 5)) {
11337 refer_to += 5;
11338 } else {
11339 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
11340 return -3;
11343 /* Get referred by header if it exists */
11344 p_referred_by = get_header(req, "Referred-By");
11346 /* Give useful transfer information to the dialplan */
11347 if (transferer->owner) {
11348 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
11349 if (peer) {
11350 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
11351 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
11355 if (!ast_strlen_zero(p_referred_by)) {
11356 char *lessthan;
11357 h_referred_by = ast_strdupa(p_referred_by);
11358 if (pedanticsipchecking)
11359 ast_uri_decode(h_referred_by);
11361 /* Store referrer's caller ID name */
11362 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
11363 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
11364 *(lessthan - 1) = '\0'; /* Space */
11367 referred_by_uri = get_in_brackets(h_referred_by);
11368 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
11369 referred_by_uri += 4; /* Skip sip: */
11370 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
11371 referred_by_uri += 5; /* Skip sips: */
11372 } else {
11373 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
11374 referred_by_uri = NULL;
11378 /* Check for arguments in the refer_to header */
11379 if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
11380 *ptr++ = '\0';
11381 if (!strncasecmp(ptr, "REPLACES=", 9)) {
11382 char *to = NULL, *from = NULL;
11384 /* This is an attended transfer */
11385 referdata->attendedtransfer = 1;
11386 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
11387 ast_uri_decode(referdata->replaces_callid);
11388 if ((ptr = strchr(referdata->replaces_callid, ';'))) /* Find options */ {
11389 *ptr++ = '\0';
11392 if (ptr) {
11393 /* Find the different tags before we destroy the string */
11394 to = strcasestr(ptr, "to-tag=");
11395 from = strcasestr(ptr, "from-tag=");
11398 /* Grab the to header */
11399 if (to) {
11400 ptr = to + 7;
11401 if ((to = strchr(ptr, '&')))
11402 *to = '\0';
11403 if ((to = strchr(ptr, ';')))
11404 *to = '\0';
11405 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
11408 if (from) {
11409 ptr = from + 9;
11410 if ((to = strchr(ptr, '&')))
11411 *to = '\0';
11412 if ((to = strchr(ptr, ';')))
11413 *to = '\0';
11414 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
11417 if (!pedanticsipchecking)
11418 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
11419 else
11420 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>" );
11424 if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
11425 char *urioption = NULL, *domain;
11426 *ptr++ = '\0';
11428 if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
11429 *urioption++ = '\0';
11431 domain = ptr;
11432 if ((ptr = strchr(domain, ':'))) /* Remove :port */
11433 *ptr = '\0';
11435 /* Save the domain for the dial plan */
11436 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
11437 if (urioption)
11438 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
11441 if ((ptr = strchr(refer_to, ';'))) /* Remove options */
11442 *ptr = '\0';
11443 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
11445 if (referred_by_uri) {
11446 if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
11447 *ptr = '\0';
11448 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
11449 } else {
11450 referdata->referred_by[0] = '\0';
11453 /* Determine transfer context */
11454 if (transferer->owner) /* Mimic behaviour in res_features.c */
11455 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
11457 /* By default, use the context in the channel sending the REFER */
11458 if (ast_strlen_zero(transfer_context)) {
11459 transfer_context = S_OR(transferer->owner->macrocontext,
11460 S_OR(transferer->context, default_context));
11463 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
11465 /* Either an existing extension or the parking extension */
11466 if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
11467 if (sip_debug_test_pvt(transferer)) {
11468 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
11470 /* We are ready to transfer to the extension */
11471 return 0;
11473 if (sip_debug_test_pvt(transferer))
11474 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
11476 /* Failure, we can't find this extension */
11477 return -1;
11481 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
11482 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
11484 char tmp[256] = "", *c, *a;
11485 struct sip_request *req = oreq ? oreq : &p->initreq;
11486 struct sip_refer *referdata = NULL;
11487 const char *transfer_context = NULL;
11489 if (!p->refer && !sip_refer_allocate(p))
11490 return -1;
11492 referdata = p->refer;
11494 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
11495 c = get_in_brackets(tmp);
11497 if (pedanticsipchecking)
11498 ast_uri_decode(c);
11500 if (!strncasecmp(c, "sip:", 4)) {
11501 c += 4;
11502 } else if (!strncasecmp(c, "sips:", 5)) {
11503 c += 5;
11504 } else {
11505 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
11506 return -1;
11509 if ((a = strchr(c, ';'))) /* Remove arguments */
11510 *a = '\0';
11512 if ((a = strchr(c, '@'))) { /* Separate Domain */
11513 *a++ = '\0';
11514 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
11517 if (sip_debug_test_pvt(p))
11518 ast_verbose("Looking for %s in %s\n", c, p->context);
11520 if (p->owner) /* Mimic behaviour in res_features.c */
11521 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
11523 /* By default, use the context in the channel sending the REFER */
11524 if (ast_strlen_zero(transfer_context)) {
11525 transfer_context = S_OR(p->owner->macrocontext,
11526 S_OR(p->context, default_context));
11528 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
11529 /* This is a blind transfer */
11530 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
11531 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
11532 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
11533 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
11534 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
11535 /* Set new context */
11536 ast_string_field_set(p, context, transfer_context);
11537 return 0;
11538 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
11539 return 1;
11542 return -1;
11545 /*! \brief check received= and rport= in a SIP response.
11546 * If we get a response with received= and/or rport= in the Via:
11547 * line, use them as 'p->ourip' (see RFC 3581 for rport,
11548 * and RFC 3261 for received).
11549 * Using these two fields SIP can produce the correct
11550 * address and port in the SIP headers without the need for STUN.
11551 * The address part is also reused for the media sessions.
11552 * Note that ast_sip_ouraddrfor() still rewrites p->ourip
11553 * if you specify externip/seternaddr/stunaddr.
11555 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
11557 char via[256];
11558 char *cur, *opts;
11560 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
11562 /* Work on the leftmost value of the topmost Via header */
11563 opts = strchr(via, ',');
11564 if (opts)
11565 *opts = '\0';
11567 /* parse all relevant options */
11568 opts = strchr(via, ';');
11569 if (!opts)
11570 return; /* no options to parse */
11571 *opts++ = '\0';
11572 while ( (cur = strsep(&opts, ";")) ) {
11573 if (!strncmp(cur, "rport=", 6)) {
11574 int port = strtol(cur+6, NULL, 10);
11575 /* XXX add error checking */
11576 p->ourip.sin_port = ntohs(port);
11577 } else if (!strncmp(cur, "received=", 9)) {
11578 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
11579 ; /* XXX add error checking */
11584 /*! \brief check Via: header for hostname, port and rport request/answer */
11585 static void check_via(struct sip_pvt *p, struct sip_request *req)
11587 char via[512];
11588 char *c, *pt;
11589 struct hostent *hp;
11590 struct ast_hostent ahp;
11592 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
11594 /* Work on the leftmost value of the topmost Via header */
11595 c = strchr(via, ',');
11596 if (c)
11597 *c = '\0';
11599 /* Check for rport */
11600 c = strstr(via, ";rport");
11601 if (c && (c[6] != '=')) /* rport query, not answer */
11602 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
11604 c = strchr(via, ';');
11605 if (c)
11606 *c = '\0';
11608 c = strchr(via, ' ');
11609 if (c) {
11610 *c = '\0';
11611 c = ast_skip_blanks(c+1);
11612 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
11613 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
11614 return;
11616 pt = strchr(c, ':');
11617 if (pt)
11618 *pt++ = '\0'; /* remember port pointer */
11619 hp = ast_gethostbyname(c, &ahp);
11620 if (!hp) {
11621 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
11622 return;
11624 memset(&p->sa, 0, sizeof(p->sa));
11625 p->sa.sin_family = AF_INET;
11626 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
11627 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
11629 if (sip_debug_test_pvt(p)) {
11630 const struct sockaddr_in *dst = sip_real_dst(p);
11631 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
11636 /*! \brief Get caller id name from SIP headers */
11637 static char *get_calleridname(const char *input, char *output, size_t outputsize)
11639 const char *end = strchr(input, '<'); /* first_bracket */
11640 const char *tmp = strchr(input, '"'); /* first quote */
11641 int bytes = 0;
11642 int maxbytes = outputsize - 1;
11644 if (!end || end == input) /* we require a part in brackets */
11645 return NULL;
11647 end--; /* move just before "<" */
11649 if (tmp && tmp <= end) {
11650 /* The quote (tmp) precedes the bracket (end+1).
11651 * Find the matching quote and return the content.
11653 end = strchr(tmp+1, '"');
11654 if (!end)
11655 return NULL;
11656 bytes = (int) (end - tmp);
11657 /* protect the output buffer */
11658 if (bytes > maxbytes)
11659 bytes = maxbytes;
11660 ast_copy_string(output, tmp + 1, bytes);
11661 } else {
11662 /* No quoted string, or it is inside brackets. */
11663 /* clear the empty characters in the begining*/
11664 input = ast_skip_blanks(input);
11665 /* clear the empty characters in the end */
11666 while(*end && *end < 33 && end > input)
11667 end--;
11668 if (end >= input) {
11669 bytes = (int) (end - input) + 2;
11670 /* protect the output buffer */
11671 if (bytes > maxbytes)
11672 bytes = maxbytes;
11673 ast_copy_string(output, input, bytes);
11674 } else
11675 return NULL;
11677 return output;
11680 /*! \brief Get caller id number from Remote-Party-ID header field
11681 * Returns true if number should be restricted (privacy setting found)
11682 * output is set to NULL if no number found
11684 static int get_rpid_num(const char *input, char *output, int maxlen)
11686 char *start;
11687 char *end;
11689 start = strchr(input, ':');
11690 if (!start) {
11691 output[0] = '\0';
11692 return 0;
11694 start++;
11696 /* we found "number" */
11697 ast_copy_string(output, start, maxlen);
11698 output[maxlen-1] = '\0';
11700 end = strchr(output, '@');
11701 if (end)
11702 *end = '\0';
11703 else
11704 output[0] = '\0';
11705 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
11706 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
11708 return 0;
11712 * duplicate a list of channel variables, \return the copy.
11714 static struct ast_variable *copy_vars(struct ast_variable *src)
11716 struct ast_variable *res = NULL, *tmp, *v = NULL;
11718 for (v = src ; v ; v = v->next) {
11719 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
11720 tmp->next = res;
11721 res = tmp;
11724 return res;
11727 /*! \brief helper function for check_{user|peer}_ok() */
11728 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
11730 /* replace callerid if rpid found, and not restricted */
11731 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
11732 char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
11733 if (!ast_strlen_zero(calleridname))
11734 ast_string_field_set(p, cid_name, calleridname);
11735 if (ast_is_shrinkable_phonenumber(tmp))
11736 ast_shrink_phone_number(tmp);
11737 ast_string_field_set(p, cid_num, tmp);
11741 /*! \brief Validate user authentication */
11742 static enum check_auth_result check_user_ok(struct sip_pvt *p, char *of,
11743 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
11744 enum xmittype reliable,
11745 char *rpid_num, char *calleridname, char *uri2)
11747 enum check_auth_result res;
11748 struct sip_user *user = find_user(of, 1);
11749 int debug=sip_debug_test_addr(sin);
11751 /* Find user based on user name in the from header */
11752 if (!user) {
11753 if (debug)
11754 ast_verbose("No user '%s' in SIP users list\n", of);
11755 return AUTH_DONT_KNOW;
11757 if (!ast_apply_ha(user->ha, sin)) {
11758 if (debug)
11759 ast_verbose("Found user '%s' for '%s', but fails host access\n",
11760 user->name, of);
11761 unref_user(user, "unref_user: from check_user_ok from find_user call, early return of AUTH_DONT_KNOW.");
11762 return AUTH_DONT_KNOW;
11764 if (debug)
11765 ast_verbose("Found user '%s' for '%s'\n", user->name, of);
11767 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
11768 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
11769 /* copy channel vars */
11770 p->chanvars = copy_vars(user->chanvars);
11771 p->prefs = user->prefs;
11772 /* Set Frame packetization */
11773 if (p->rtp) {
11774 ast_rtp_codec_setpref(p->rtp, &p->prefs);
11775 p->autoframing = user->autoframing;
11778 replace_cid(p, rpid_num, calleridname);
11779 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );
11781 if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, req->ignore))) {
11782 sip_cancel_destroy(p);
11783 ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
11784 ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
11785 /* Copy SIP extensions profile from INVITE */
11786 if (p->sipoptions)
11787 user->sipoptions = p->sipoptions;
11789 /* If we have a call limit, set flag */
11790 if (user->call_limit)
11791 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
11792 if (!ast_strlen_zero(user->context))
11793 ast_string_field_set(p, context, user->context);
11794 if (!ast_strlen_zero(user->cid_num)) {
11795 char *tmp = ast_strdupa(user->cid_num);
11796 if (ast_is_shrinkable_phonenumber(tmp))
11797 ast_shrink_phone_number(tmp);
11798 ast_string_field_set(p, cid_num, tmp);
11800 if (!ast_strlen_zero(user->cid_name))
11801 ast_string_field_set(p, cid_name, user->cid_name);
11802 ast_string_field_set(p, username, user->name);
11803 ast_string_field_set(p, peername, user->name);
11804 ast_string_field_set(p, peersecret, user->secret);
11805 ast_string_field_set(p, peermd5secret, user->md5secret);
11806 ast_string_field_set(p, subscribecontext, user->subscribecontext);
11807 ast_string_field_set(p, accountcode, user->accountcode);
11808 ast_string_field_set(p, language, user->language);
11809 ast_string_field_set(p, mohsuggest, user->mohsuggest);
11810 ast_string_field_set(p, mohinterpret, user->mohinterpret);
11811 ast_string_field_set(p, parkinglot, user->parkinglot);
11812 p->allowtransfer = user->allowtransfer;
11813 p->amaflags = user->amaflags;
11814 p->callgroup = user->callgroup;
11815 p->pickupgroup = user->pickupgroup;
11816 if (user->callingpres) /* User callingpres setting will override RPID header */
11817 p->callingpres = user->callingpres;
11819 /* Set default codec settings for this call */
11820 p->capability = user->capability; /* User codec choice */
11821 p->jointcapability = user->capability; /* Our codecs */
11822 if (p->peercapability) /* AND with peer's codecs */
11823 p->jointcapability &= p->peercapability;
11824 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
11825 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
11826 p->noncodeccapability |= AST_RTP_DTMF;
11827 else
11828 p->noncodeccapability &= ~AST_RTP_DTMF;
11829 p->jointnoncodeccapability = p->noncodeccapability;
11830 if (p->t38.peercapability)
11831 p->t38.jointcapability &= p->t38.peercapability;
11832 p->maxcallbitrate = user->maxcallbitrate;
11833 /* If we do not support video, remove video from call structure */
11834 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
11835 ast_rtp_destroy(p->vrtp);
11836 p->vrtp = NULL;
11838 /* If we do not support text, remove text from call structure */
11839 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && p->trtp) {
11840 ast_rtp_destroy(p->trtp);
11841 p->trtp = NULL;
11844 unref_user(user, "unref_user from check_auth_result, at end");
11845 return res;
11848 /*! \brief Validate peer authentication */
11849 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
11850 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
11851 struct sip_peer **authpeer,
11852 enum xmittype reliable,
11853 char *rpid_num, char *calleridname, char *uri2)
11855 enum check_auth_result res;
11856 int debug=sip_debug_test_addr(sin);
11857 struct sip_peer *peer;
11859 /* For subscribes, match on peer name only; for other methods,
11860 * match on IP address-port of the incoming request.
11862 peer = (sipmethod == SIP_SUBSCRIBE) ? find_peer(of, NULL, 1) : find_peer(NULL, &p->recv, 1);
11864 if (!peer) {
11865 if (debug)
11866 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
11867 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11868 return AUTH_DONT_KNOW;
11871 if (debug)
11872 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
11873 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
11875 /* XXX what about p->prefs = peer->prefs; ? */
11876 /* Set Frame packetization */
11877 if (p->rtp) {
11878 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
11879 p->autoframing = peer->autoframing;
11882 /* Take the peer */
11883 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
11884 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
11886 /* Copy SIP extensions profile to peer */
11887 /* XXX is this correct before a successful auth ? */
11888 if (p->sipoptions)
11889 peer->sipoptions = p->sipoptions;
11891 replace_cid(p, rpid_num, calleridname);
11892 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
11894 ast_string_field_set(p, peersecret, peer->secret);
11895 ast_string_field_set(p, peermd5secret, peer->md5secret);
11896 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
11897 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
11898 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
11899 ast_string_field_set(p, parkinglot, peer->parkinglot);
11900 if (peer->callingpres) /* Peer calling pres setting will override RPID */
11901 p->callingpres = peer->callingpres;
11902 if (peer->maxms && peer->lastms)
11903 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
11904 else
11905 p->timer_t1 = peer->timer_t1;
11907 /* Set timer B to control transaction timeouts */
11908 if (peer->timer_b)
11909 p->timer_b = peer->timer_b;
11910 else
11911 p->timer_b = 64 * p->timer_t1;
11913 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
11914 /* Pretend there is no required authentication */
11915 ast_string_field_set(p, peersecret, NULL);
11916 ast_string_field_set(p, peermd5secret, NULL);
11918 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
11919 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
11920 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
11921 /* If we have a call limit, set flag */
11922 if (peer->call_limit)
11923 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
11924 ast_string_field_set(p, peername, peer->name);
11925 ast_string_field_set(p, authname, peer->name);
11927 /* copy channel vars */
11928 p->chanvars = copy_vars(peer->chanvars);
11929 if (authpeer) {
11930 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
11931 (*authpeer) = peer; /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
11934 if (!ast_strlen_zero(peer->username)) {
11935 ast_string_field_set(p, username, peer->username);
11936 /* Use the default username for authentication on outbound calls */
11937 /* XXX this takes the name from the caller... can we override ? */
11938 ast_string_field_set(p, authname, peer->username);
11940 if (!ast_strlen_zero(peer->cid_num)) {
11941 char *tmp = ast_strdupa(peer->cid_num);
11942 if (ast_is_shrinkable_phonenumber(tmp))
11943 ast_shrink_phone_number(tmp);
11944 ast_string_field_set(p, cid_num, tmp);
11946 if (!ast_strlen_zero(peer->cid_name))
11947 ast_string_field_set(p, cid_name, peer->cid_name);
11948 ast_string_field_set(p, fullcontact, peer->fullcontact);
11949 if (!ast_strlen_zero(peer->context))
11950 ast_string_field_set(p, context, peer->context);
11951 ast_string_field_set(p, peersecret, peer->secret);
11952 ast_string_field_set(p, peermd5secret, peer->md5secret);
11953 ast_string_field_set(p, language, peer->language);
11954 ast_string_field_set(p, accountcode, peer->accountcode);
11955 p->amaflags = peer->amaflags;
11956 p->callgroup = peer->callgroup;
11957 p->pickupgroup = peer->pickupgroup;
11958 p->capability = peer->capability;
11959 p->prefs = peer->prefs;
11960 p->jointcapability = peer->capability;
11961 if (p->peercapability)
11962 p->jointcapability &= p->peercapability;
11963 p->maxcallbitrate = peer->maxcallbitrate;
11964 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
11965 ast_rtp_destroy(p->vrtp);
11966 p->vrtp = NULL;
11968 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
11969 ast_rtp_destroy(p->trtp);
11970 p->trtp = NULL;
11972 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
11973 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
11974 p->noncodeccapability |= AST_RTP_DTMF;
11975 else
11976 p->noncodeccapability &= ~AST_RTP_DTMF;
11977 p->jointnoncodeccapability = p->noncodeccapability;
11978 if (p->t38.peercapability)
11979 p->t38.jointcapability &= p->t38.peercapability;
11981 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
11982 return res;
11986 /*! \brief Check if matching user or peer is defined
11987 Match user on From: user name and peer on IP/port
11988 This is used on first invite (not re-invites) and subscribe requests
11989 \return 0 on success, non-zero on failure
11991 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
11992 int sipmethod, char *uri, enum xmittype reliable,
11993 struct sockaddr_in *sin, struct sip_peer **authpeer)
11995 char from[256];
11996 char *dummy; /* dummy return value for parse_uri */
11997 char *domain; /* dummy return value for parse_uri */
11998 char *of, *of2;
11999 char rpid_num[50];
12000 const char *rpid;
12001 enum check_auth_result res;
12002 char calleridname[50];
12003 char *uri2 = ast_strdupa(uri);
12005 terminate_uri(uri2); /* trim extra stuff */
12007 ast_copy_string(from, get_header(req, "From"), sizeof(from));
12008 if (pedanticsipchecking)
12009 ast_uri_decode(from);
12010 /* XXX here tries to map the username for invite things */
12011 memset(calleridname, 0, sizeof(calleridname));
12012 get_calleridname(from, calleridname, sizeof(calleridname));
12013 if (calleridname[0])
12014 ast_string_field_set(p, cid_name, calleridname);
12016 rpid = get_header(req, "Remote-Party-ID");
12017 memset(rpid_num, 0, sizeof(rpid_num));
12018 if (!ast_strlen_zero(rpid))
12019 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
12021 of = get_in_brackets(from);
12022 if (ast_strlen_zero(p->exten)) {
12023 char *t = uri2;
12024 if (!strncasecmp(t, "sip:", 4))
12025 t+= 4;
12026 else if (!strncasecmp(t, "sips:", 5))
12027 t += 5;
12028 ast_string_field_set(p, exten, t);
12029 t = strchr(p->exten, '@');
12030 if (t)
12031 *t = '\0';
12032 if (ast_strlen_zero(p->our_contact))
12033 build_contact(p);
12035 /* save the URI part of the From header */
12036 ast_string_field_set(p, from, of);
12038 of2 = ast_strdupa(of);
12040 /* ignore all fields but name */
12041 if (p->socket.type == SIP_TRANSPORT_TLS) {
12042 if (parse_uri(of, "sips:", &of, &dummy, &domain, &dummy, &dummy)) {
12043 if (parse_uri(of2, "sip:", &of, &dummy, &domain, &dummy, &dummy))
12044 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
12046 } else {
12047 if (parse_uri(of, "sip:", &of, &dummy, &domain, &dummy, &dummy))
12048 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
12051 if (ast_strlen_zero(of)) {
12052 /* XXX note: the original code considered a missing @host
12053 * as a username-only URI. The SIP RFC (19.1.1) says that
12054 * this is wrong, and it should be considered as a domain-only URI.
12055 * For backward compatibility, we keep this block, but it is
12056 * really a mistake and should go away.
12058 of = domain;
12061 char *tmp = ast_strdupa(of);
12062 /* We need to be able to handle auth-headers looking like
12063 <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
12065 tmp = strsep(&tmp, ";");
12066 if (ast_is_shrinkable_phonenumber(tmp))
12067 ast_shrink_phone_number(tmp);
12068 ast_string_field_set(p, cid_num, tmp);
12071 if (global_match_auth_username) {
12073 * XXX This is experimental code to grab the search key from the
12074 * Auth header's username instead of the 'From' name, if available.
12075 * Do not enable this block unless you understand the side effects (if any!)
12076 * Note, the search for "username" should be done in a more robust way.
12077 * Note2, at the moment we check both fields, though maybe we should
12078 * pick one or another depending on the request ? XXX
12080 const char *hdr = get_header(req, "Authorization");
12081 if (ast_strlen_zero(hdr))
12082 hdr = get_header(req, "Proxy-Authorization");
12084 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
12085 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
12086 of = from;
12087 of = strsep(&of, "\"");
12091 if (!authpeer) {
12092 /* If we are looking for a peer, don't check the
12093 user objects (or realtime) */
12094 res = check_user_ok(p, of, req, sipmethod, sin,
12095 reliable, rpid_num, calleridname, uri2);
12096 if (res != AUTH_DONT_KNOW)
12097 return res;
12100 res = check_peer_ok(p, of, req, sipmethod, sin,
12101 authpeer, reliable, rpid_num, calleridname, uri2);
12102 if (res != AUTH_DONT_KNOW)
12103 return res;
12105 /* Finally, apply the guest policy */
12106 if (global_allowguest) {
12107 replace_cid(p, rpid_num, calleridname);
12108 res = AUTH_SUCCESSFUL;
12109 } else if (global_alwaysauthreject)
12110 res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
12111 else
12112 res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
12114 return res;
12117 /*! \brief Find user
12118 If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
12120 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
12122 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
12125 /*! \brief Get text out of a SIP MESSAGE packet */
12126 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
12128 int x;
12129 int y;
12131 buf[0] = '\0';
12132 y = len - strlen(buf) - 5;
12133 if (y < 0)
12134 y = 0;
12135 for (x=0; x < req->lines; x++) {
12136 strncat(buf, req->line[x], y); /* safe */
12137 y -= strlen(req->line[x]) + 1;
12138 if (y < 0)
12139 y = 0;
12140 if (y != 0 && addnewline)
12141 strcat(buf, "\n"); /* safe */
12143 return 0;
12147 /*! \brief Receive SIP MESSAGE method messages
12148 \note We only handle messages within current calls currently
12149 Reference: RFC 3428 */
12150 static void receive_message(struct sip_pvt *p, struct sip_request *req)
12152 char buf[1400];
12153 struct ast_frame f;
12154 const char *content_type = get_header(req, "Content-Type");
12156 if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
12157 transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
12158 if (!p->owner)
12159 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12160 return;
12163 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
12164 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
12165 transmit_response(p, "202 Accepted", req);
12166 if (!p->owner)
12167 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12168 return;
12171 if (p->owner) {
12172 if (sip_debug_test_pvt(p))
12173 ast_verbose("SIP Text message received: '%s'\n", buf);
12174 memset(&f, 0, sizeof(f));
12175 f.frametype = AST_FRAME_TEXT;
12176 f.subclass = 0;
12177 f.offset = 0;
12178 f.data.ptr = buf;
12179 f.datalen = strlen(buf);
12180 ast_queue_frame(p->owner, &f);
12181 transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
12182 return;
12185 /* Message outside of a call, we do not support that */
12186 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);
12187 transmit_response(p, "405 Method Not Allowed", req);
12188 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12189 return;
12192 /*! \brief CLI Command to show calls within limits set by call_limit */
12193 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12195 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
12196 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
12197 char ilimits[40];
12198 char iused[40];
12199 int showall = FALSE;
12200 struct ao2_iterator i;
12201 struct sip_user *user;
12202 struct sip_peer *peer;
12204 switch (cmd) {
12205 case CLI_INIT:
12206 e->command = "sip show inuse";
12207 e->usage =
12208 "Usage: sip show inuse [all]\n"
12209 " List all SIP users and peers usage counters and limits.\n"
12210 " Add option \"all\" to show all devices, not only those with a limit.\n";
12211 return NULL;
12212 case CLI_GENERATE:
12213 return NULL;
12216 if (a->argc < 3)
12217 return CLI_SHOWUSAGE;
12219 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
12220 showall = TRUE;
12222 ast_cli(a->fd, FORMAT, "* User name", "In use", "Limit");
12224 i = ao2_iterator_init(users, 0);
12226 while ((user = ao2_t_iterator_next(&i, "iterate thru user table"))) {
12227 ao2_lock(user);
12229 if (user->call_limit)
12230 snprintf(ilimits, sizeof(ilimits), "%d", user->call_limit);
12231 else
12232 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
12233 snprintf(iused, sizeof(iused), "%d", user->inUse);
12234 if (showall || user->call_limit)
12235 ast_cli(a->fd, FORMAT2, user->name, iused, ilimits);
12236 ao2_unlock(user);
12237 unref_user(user, "toss iterator pointer");
12240 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
12242 i = ao2_iterator_init(peers, 0);
12244 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
12245 ao2_lock(peer);
12246 if (peer->call_limit)
12247 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
12248 else
12249 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
12250 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
12251 if (showall || peer->call_limit)
12252 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
12253 ao2_unlock(peer);
12254 unref_peer(peer, "toss iterator pointer");
12257 return CLI_SUCCESS;
12258 #undef FORMAT
12259 #undef FORMAT2
12263 /*! \brief Convert transfer mode to text string */
12264 static char *transfermode2str(enum transfermodes mode)
12266 if (mode == TRANSFER_OPENFORALL)
12267 return "open";
12268 else if (mode == TRANSFER_CLOSED)
12269 return "closed";
12270 return "strict";
12273 static struct _map_x_s natmodes[] = {
12274 { SIP_NAT_NEVER, "No"},
12275 { SIP_NAT_ROUTE, "Route"},
12276 { SIP_NAT_ALWAYS, "Always"},
12277 { SIP_NAT_RFC3581, "RFC3581"},
12278 { -1, NULL}, /* terminator */
12281 static struct _map_x_s natcfgmodes[] = {
12282 { SIP_NAT_NEVER, "never"},
12283 { SIP_NAT_ROUTE, "route"},
12284 { SIP_NAT_ALWAYS, "yes"},
12285 { SIP_NAT_RFC3581, "no"},
12286 { -1, NULL}, /* terminator */
12289 /*! \brief Convert NAT setting to text string */
12290 static const char *nat2str(int nat)
12292 return map_x_s(natmodes, nat, "Unknown");
12295 /*! \brief Convert NAT setting to text string appropriate for config files */
12296 static const char *nat2strconfig(int nat)
12298 return map_x_s(natcfgmodes, nat, "Unknown");
12301 /*! \brief Report Peer status in character string
12302 * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
12306 /* Session-Timer Modes */
12307 static struct _map_x_s stmodes[] = {
12308 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
12309 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
12310 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
12311 { -1, NULL},
12314 static const char *stmode2str(enum st_mode m)
12316 return map_x_s(stmodes, m, "Unknown");
12319 static enum st_mode str2stmode(const char *s)
12321 return map_s_x(stmodes, s, -1);
12324 /* Session-Timer Refreshers */
12325 static struct _map_x_s strefreshers[] = {
12326 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
12327 { SESSION_TIMER_REFRESHER_UAC, "uac"},
12328 { SESSION_TIMER_REFRESHER_UAS, "uas"},
12329 { -1, NULL},
12332 static const char *strefresher2str(enum st_refresher r)
12334 return map_x_s(strefreshers, r, "Unknown");
12337 static enum st_refresher str2strefresher(const char *s)
12339 return map_s_x(strefreshers, s, -1);
12343 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
12345 int res = 0;
12346 if (peer->maxms) {
12347 if (peer->lastms < 0) {
12348 ast_copy_string(status, "UNREACHABLE", statuslen);
12349 } else if (peer->lastms > peer->maxms) {
12350 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
12351 res = 1;
12352 } else if (peer->lastms) {
12353 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
12354 res = 1;
12355 } else {
12356 ast_copy_string(status, "UNKNOWN", statuslen);
12358 } else {
12359 ast_copy_string(status, "Unmonitored", statuslen);
12360 /* Checking if port is 0 */
12361 res = -1;
12363 return res;
12366 /*! \brief return Yes or No depending on the argument.
12367 * This is used in many places in CLI command, having a function to generate
12368 * this helps maintaining a consistent output (and possibly emitting the
12369 * output in other languages, at some point).
12371 static const char *cli_yesno(int x)
12373 return x ? "Yes" : "No";
12376 /*! \brief Show active TCP connections */
12377 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12379 struct sip_threadinfo *th;
12381 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
12382 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
12384 switch (cmd) {
12385 case CLI_INIT:
12386 e->command = "sip show tcp";
12387 e->usage =
12388 "Usage: sip show tcp\n"
12389 " Lists all active TCP/TLS sessions.\n";
12390 return NULL;
12391 case CLI_GENERATE:
12392 return NULL;
12395 if (a->argc != 3)
12396 return CLI_SHOWUSAGE;
12398 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
12399 AST_LIST_LOCK(&threadl);
12400 AST_LIST_TRAVERSE(&threadl, th, list) {
12401 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->ser->requestor.sin_addr),
12402 ntohs(th->ser->requestor.sin_port),
12403 get_transport(th->type),
12404 (th->ser->client ? "Client" : "Server"));
12407 AST_LIST_UNLOCK(&threadl);
12408 return CLI_SUCCESS;
12409 #undef FORMAT
12410 #undef FORMAT2
12413 int usercomparefunc(const void *a, const void *b);
12415 int usercomparefunc(const void *a, const void *b)
12417 struct sip_user **ap = (struct sip_user **)a;
12418 struct sip_user **bp = (struct sip_user **)b;
12419 return strcmp((*ap)->name, (*bp)->name);
12423 /*! \brief CLI Command 'SIP Show Users' */
12424 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12426 regex_t regexbuf;
12427 int havepattern = FALSE;
12428 int count = 0;
12429 int totcount = 0;
12430 struct sip_user *user;
12431 struct ao2_iterator i;
12432 int objcount = ao2_container_count(users);
12433 struct sip_user **userarray;
12434 int k;
12436 userarray = ast_calloc(sizeof(struct sip_user *), objcount);
12438 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
12440 switch (cmd) {
12441 case CLI_INIT:
12442 e->command = "sip show users";
12443 e->usage =
12444 "Usage: sip show users [like <pattern>]\n"
12445 " Lists all known SIP users.\n"
12446 " Optional regular expression pattern is used to filter the user list.\n";
12447 return NULL;
12448 case CLI_GENERATE:
12449 return NULL;
12452 switch (a->argc) {
12453 case 5:
12454 if (!strcasecmp(a->argv[3], "like")) {
12455 if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
12456 return CLI_SHOWUSAGE;
12457 havepattern = TRUE;
12458 } else
12459 return CLI_SHOWUSAGE;
12460 case 3:
12461 break;
12462 default:
12463 return CLI_SHOWUSAGE;
12466 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
12468 i = ao2_iterator_init(users, 0);
12470 while ((user = ao2_t_iterator_next(&i, "iterate thru user table"))) {
12471 ao2_lock(user);
12472 totcount++;
12473 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
12474 ao2_unlock(user);
12475 unref_user(user, "toss iterator pointer via a continue in iterator loop");
12476 continue;
12478 userarray[count++] = user;
12479 ao2_unlock(user);
12482 qsort(userarray, count, sizeof(struct sip_user *), usercomparefunc);
12484 for(k=0; k < count; k++) {
12485 user = userarray[k];
12487 ao2_lock(user);
12488 ast_cli(a->fd, FORMAT, user->name,
12489 user->secret,
12490 user->accountcode,
12491 user->context,
12492 cli_yesno(user->ha != NULL),
12493 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
12494 ao2_unlock(user);
12495 unref_user(user, "toss iterator pointer");
12498 if (havepattern)
12499 regfree(&regexbuf);
12500 if (havepattern)
12501 ast_cli(a->fd, "Total %d of %d user entries\n", count, totcount);
12502 else
12503 ast_cli(a->fd, "Total of %d user entries\n", totcount);
12505 ast_free(userarray);
12506 return CLI_SUCCESS;
12507 #undef FORMAT
12510 /*! \brief Manager Action SIPShowRegistry description */
12511 static char mandescr_show_registry[] =
12512 "Description: Lists all registration requests and status\n"
12513 "Registrations will follow as separate events. followed by a final event called\n"
12514 "RegistrationsComplete.\n"
12515 "Variables: \n"
12516 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
12518 /*! \brief Show SIP registrations in the manager API */
12519 static int manager_show_registry(struct mansession *s, const struct message *m)
12521 const char *id = astman_get_header(m, "ActionID");
12522 char idtext[256] = "";
12523 char tmpdat[256] = "";
12524 int total = 0;
12525 struct ast_tm tm;
12527 if (!ast_strlen_zero(id))
12528 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12530 astman_send_listack(s, m, "Registrations will follow", "start");
12532 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
12533 ASTOBJ_RDLOCK(iterator);
12534 if (iterator->regtime.tv_sec) {
12535 ast_localtime(&iterator->regtime, &tm, NULL);
12536 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
12537 } else
12538 tmpdat[0] = '\0';
12539 astman_append(s,
12540 "Event: RegistryEntry\r\n"
12541 "Host: %s\r\n"
12542 "Port: %d\r\n"
12543 "Username: %s\r\n"
12544 "Refresh: %d\r\n"
12545 "State: %s\r\n"
12546 "Reg.Time: %s\r\n"
12547 "\r\n", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
12548 iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
12549 ASTOBJ_UNLOCK(iterator);
12550 total++;
12551 } while(0));
12553 astman_append(s,
12554 "Event: RegistrationsComplete\r\n"
12555 "EventList: Complete\r\n"
12556 "ListItems: %d\r\n"
12557 "%s"
12558 "\r\n", total, idtext);
12560 return 0;
12563 static char mandescr_show_peers[] =
12564 "Description: Lists SIP peers in text format with details on current status.\n"
12565 "Peerlist will follow as separate events, followed by a final event called\n"
12566 "PeerlistComplete.\n"
12567 "Variables: \n"
12568 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
12570 /*! \brief Show SIP peers in the manager API */
12571 /* Inspired from chan_iax2 */
12572 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
12574 const char *id = astman_get_header(m, "ActionID");
12575 const char *a[] = {"sip", "show", "peers"};
12576 char idtext[256] = "";
12577 int total = 0;
12579 if (!ast_strlen_zero(id))
12580 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12582 astman_send_listack(s, m, "Peer status list will follow", "start");
12583 /* List the peers in separate manager events */
12584 _sip_show_peers(-1, &total, s, m, 3, a);
12585 /* Send final confirmation */
12586 astman_append(s,
12587 "Event: PeerlistComplete\r\n"
12588 "EventList: Complete\r\n"
12589 "ListItems: %d\r\n"
12590 "%s"
12591 "\r\n", total, idtext);
12592 return 0;
12595 /*! \brief CLI Show Peers command */
12596 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12598 switch (cmd) {
12599 case CLI_INIT:
12600 e->command = "sip show peers";
12601 e->usage =
12602 "Usage: sip show peers [like <pattern>]\n"
12603 " Lists all known SIP peers.\n"
12604 " Optional regular expression pattern is used to filter the peer list.\n";
12605 return NULL;
12606 case CLI_GENERATE:
12607 return NULL;
12610 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
12613 static char *sip_dbdump(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12615 switch (cmd) {
12616 case CLI_INIT:
12617 e->command = "sip dbdump";
12618 e->usage =
12619 "Usage: sip dbdump [<file>]\n"
12620 " dumps user/peer info to the screen in SQL INSERT command form\n"
12621 " Optional file path will be output instead of to console if present.\n";
12622 return NULL;
12623 case CLI_GENERATE:
12624 return NULL;
12627 return _sip_dbdump(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
12630 /*! \brief Execute sip show peers command */
12631 static char *_sip_dbdump(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
12633 struct sip_peer *peer;
12634 struct sip_user *user;
12635 struct ao2_iterator i;
12636 char fname[1024];
12637 const char *id;
12638 FILE *f1;
12639 char idtext[256] = "";
12640 int realtimepeers;
12642 realtimepeers = ast_check_realtime("sippeers");
12644 if (s) { /* Manager - get ActionID */
12645 id = astman_get_header(m, "ActionID");
12646 if (!ast_strlen_zero(id))
12647 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12650 switch (argc) {
12651 case 3:
12652 strncpy(fname, argv[2], sizeof(fname));
12653 f1 = fopen(fname, "w");
12654 if (!f1) {
12655 ast_cli(fd, "Sorry, could not open %s for writing!", fname);
12656 return CLI_SHOWUSAGE;
12658 break;
12659 case 2:
12660 ast_cli(fd, "Sorry, will only generate a file at the moment. Please run again with a file name to write to.\n");
12661 default:
12662 return CLI_SHOWUSAGE;
12665 i = ao2_iterator_init(peers, 0);
12666 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
12668 user = find_user(peer->name,realtimepeers);
12670 ao2_lock(peer);
12672 fprintf(f1, "INSERT INTO sipbuddies (");
12674 /* print out the populated field names in order */
12675 fprintf(f1,"name");
12677 if (peer->host_dynamic)
12678 fprintf(f1,",host");
12679 if (ast_test_flag(&peer->flags[0], SIP_NAT))
12680 fprintf(f1,",nat");
12681 fprintf(f1,",type");
12682 if (!ast_strlen_zero(peer->accountcode))
12683 fprintf(f1,",accountcode");
12684 if (peer->amaflags)
12685 fprintf(f1,",amaflags");
12686 fprintf(f1,",`call-limit`");
12687 if (peer->callgroup)
12688 fprintf(f1,",callgroup");
12689 if (user && !ast_strlen_zero(user->cid_num))
12690 fprintf(f1,",callerid");
12691 if (ast_test_flag(&peer->flags[0], SIP_REINVITE))
12692 fprintf(f1,",canreinvite");
12693 if (!ast_strlen_zero(peer->context))
12694 fprintf(f1,",context");
12695 if (peer->defaddr.sin_addr.s_addr)
12696 fprintf(f1,",defaultip");
12697 if (ast_test_flag(&peer->flags[0], SIP_DTMF))
12698 fprintf(f1,",dtmfmode");
12699 if (!ast_strlen_zero(peer->fromuser))
12700 fprintf(f1,",fromuser");
12701 if (!ast_strlen_zero(peer->fromdomain))
12702 fprintf(f1,",fromdomain");
12703 if (ast_test_flag(&peer->flags[0], SIP_INSECURE))
12704 fprintf(f1,",insecure");
12705 if (!ast_strlen_zero(peer->language))
12706 fprintf(f1,",language");
12707 if (!AST_LIST_EMPTY(&peer->mailboxes)) {
12708 fprintf(f1,",mailbox");
12710 if (!ast_strlen_zero(peer->md5secret))
12711 fprintf(f1,",md5secret");
12712 if (peer->ha) {
12713 if (peer->ha->sense == AST_SENSE_DENY) {
12714 fprintf(f1,",deny");
12716 if (peer->ha->next && peer->ha->next->sense == AST_SENSE_ALLOW) {
12717 fprintf(f1,",permit");
12720 if (!ast_strlen_zero(peer->mohinterpret))
12721 fprintf(f1,",mohinterpret");
12722 if (!ast_strlen_zero(peer->mohsuggest))
12723 fprintf(f1,",mohsuggest");
12724 if (peer->pickupgroup)
12725 fprintf(f1,",pickupgroup");
12726 if (peer->maxms)
12727 fprintf(f1,",qualify");
12728 if (!ast_strlen_zero(peer->regexten))
12729 fprintf(f1,",regexten");
12730 if (peer->rtptimeout)
12731 fprintf(f1,",rtptimeout");
12732 if (peer->rtpholdtimeout)
12733 fprintf(f1,",rtpholdtimeout");
12734 if (!ast_strlen_zero(peer->secret))
12735 fprintf(f1,",secret");
12736 if (peer->chanvars)
12737 fprintf(f1,",setvar");
12738 if (ast_codec_pref_index(&peer->prefs, 0)) { /* print the codecs wanted in order */
12739 fprintf(f1,",allow");
12741 if (!ast_strlen_zero(peer->fullcontact))
12742 fprintf(f1,",fullcontact");
12743 if (peer->addr.sin_addr.s_addr)
12744 fprintf(f1,",ipaddr");
12745 if (peer->addr.sin_port)
12746 fprintf(f1,",port");
12747 if (!ast_strlen_zero(peer->username))
12748 fprintf(f1,",username");
12750 /* print out the values in order */
12751 fprintf(f1, ") VALUES (");
12753 fprintf(f1,"'%s'", peer->name);
12755 if (peer->host_dynamic)
12756 fprintf(f1,",'dynamic'");
12757 if (ast_test_flag(&peer->flags[0], SIP_NAT)) {
12758 fprintf(f1,",'%s'",nat2strconfig(ast_test_flag(&peer->flags[0], SIP_NAT)));
12760 if (user)
12761 fprintf(f1,",'friend'");
12762 else
12763 fprintf(f1,",'peer'");
12764 if (!ast_strlen_zero(peer->accountcode))
12765 fprintf(f1,",'%s'", peer->accountcode);
12766 if (peer->amaflags)
12767 fprintf(f1,",'%s'", ast_cdr_flags2str(peer->amaflags));
12768 fprintf(f1,",%d", peer->call_limit);
12769 if (peer->callgroup) {
12770 char buf[256];
12772 fprintf(f1,",'%s'", ast_print_group(buf, sizeof(buf), peer->callgroup));
12774 if (user && !ast_strlen_zero(user->cid_num))
12775 fprintf(f1,",\"%s<%s>\"", user->cid_name, user->cid_num);
12776 if (ast_test_flag(&peer->flags[0], SIP_REINVITE)) {
12777 switch (ast_test_flag(&peer->flags[0], SIP_REINVITE)) {
12778 case SIP_REINVITE_NONE:
12779 fprintf(f1,",'no'");
12780 break;
12781 case SIP_CAN_REINVITE:
12782 fprintf(f1,",'yes'");
12783 break;
12784 case SIP_CAN_REINVITE_NAT:
12785 fprintf(f1,",'nonat'");
12786 break;
12787 case SIP_REINVITE_UPDATE:
12788 fprintf(f1,",'update'");
12789 break;
12790 default:
12791 fprintf(f1,",'no'");
12792 break;
12795 if (!ast_strlen_zero(peer->context))
12796 fprintf(f1,",'%s'",peer->context);
12797 if (peer->defaddr.sin_addr.s_addr)
12798 fprintf(f1,",'%s'", ast_inet_ntoa(peer->defaddr.sin_addr));
12799 if (ast_test_flag(&peer->flags[0], SIP_DTMF)) {
12800 fprintf(f1,",'%s'", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
12802 if (!ast_strlen_zero(peer->fromuser))
12803 fprintf(f1,",'%s'", peer->fromuser);
12804 if (!ast_strlen_zero(peer->fromdomain))
12805 fprintf(f1,",'%s'", peer->fromdomain);
12806 if (ast_test_flag(&peer->flags[0], SIP_INSECURE)) {
12808 fprintf(f1,",'%s'", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
12810 if (!ast_strlen_zero(peer->language))
12811 fprintf(f1,",'%s'", peer->language);
12813 if (!AST_LIST_EMPTY(&peer->mailboxes)) {
12814 struct ast_str *mailbox_str = ast_str_alloca(512);
12815 peer_mailboxes_to_str(&mailbox_str, peer);
12816 fprintf(f1,",'%s'", mailbox_str->str);
12819 if (!ast_strlen_zero(peer->md5secret))
12820 fprintf(f1,",'%s'", peer->md5secret);
12821 if (peer->ha) {
12822 if (peer->ha->sense == AST_SENSE_DENY) {
12823 fprintf(f1,",'%s/%s'", ast_inet_ntoa(peer->ha->netaddr), ast_inet_ntoa(peer->ha->netmask));
12825 if (peer->ha->next && peer->ha->next->sense == AST_SENSE_ALLOW) {
12826 fprintf(f1,",'%s/%s'", ast_inet_ntoa(peer->ha->next->netaddr), ast_inet_ntoa(peer->ha->next->netmask));
12830 if (!ast_strlen_zero(peer->mohinterpret))
12831 fprintf(f1,",'%s'", peer->mohinterpret);
12832 if (!ast_strlen_zero(peer->mohsuggest))
12833 fprintf(f1,",'%s'", peer->mohsuggest);
12834 if (peer->pickupgroup) {
12835 char buf[256];
12837 fprintf(f1,",'%s'", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
12839 if (peer->maxms)
12840 fprintf(f1,",'%d'", peer->maxms);
12841 if (!ast_strlen_zero(peer->regexten))
12842 fprintf(f1,",'%s'", peer->regexten);
12843 if (peer->rtptimeout)
12844 fprintf(f1,",'%d'", peer->rtptimeout);
12845 if (peer->rtpholdtimeout)
12846 fprintf(f1,",'%d'", peer->rtpholdtimeout);
12847 if (!ast_strlen_zero(peer->secret))
12848 fprintf(f1,",'%s'", peer->secret);
12849 if (peer->chanvars) {
12850 int first=1;
12851 struct ast_variable *p1 = peer->chanvars;
12852 fprintf(f1,",'");
12853 while (p1)
12855 if (!first)
12856 fprintf(f1,";");
12857 else
12858 first = 0;
12860 fprintf(f1,"%s=%s", p1->name, p1->value);
12861 p1 = p1->next;
12863 fprintf(f1,"'");
12866 if (ast_codec_pref_index(&peer->prefs, 0)) { /* print the codecs wanted in order */
12867 /* this code isn't general, it assumes deny=all; but that's pretty common.
12868 people who use this differently will have to modify the results by hand. sorry. */
12869 int x, codec;
12870 fprintf(f1,",'");
12871 for(x = 0; x < 32 ; x++) {
12872 codec = ast_codec_pref_index(&peer->prefs, x);
12873 if (!codec)
12874 break;
12875 fprintf(f1, "%s", ast_getformatname(codec));
12876 fprintf(f1, ":%d", peer->prefs.framing[x]);
12877 if (x < 31 && ast_codec_pref_index(&peer->prefs, x + 1))
12878 fprintf(f1, ",");
12880 fprintf(f1,"'");
12883 if (!ast_strlen_zero(peer->fullcontact))
12884 fprintf(f1,",'%s'", peer->fullcontact);
12885 if (peer->addr.sin_addr.s_addr)
12886 fprintf(f1,",'%s'", ast_inet_ntoa(peer->addr.sin_addr));
12887 if (peer->addr.sin_port)
12888 fprintf(f1,",%d", peer->addr.sin_port);
12889 if (!ast_strlen_zero(peer->username))
12890 fprintf(f1,",'%s'", peer->username);
12892 fprintf(f1, ");\n");
12894 fclose(f1);
12895 return CLI_SUCCESS;
12898 int peercomparefunc(const void *a, const void *b);
12900 int peercomparefunc(const void *a, const void *b)
12902 struct sip_peer **ap = (struct sip_peer **)a;
12903 struct sip_peer **bp = (struct sip_peer **)b;
12904 return strcmp((*ap)->name, (*bp)->name);
12908 /*! \brief Execute sip show peers command */
12909 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
12911 regex_t regexbuf;
12912 int havepattern = FALSE;
12913 struct sip_peer *peer;
12914 struct ao2_iterator i;
12916 /* the last argument is left-aligned, so we don't need a size anyways */
12917 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
12918 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
12920 char name[256];
12921 int total_peers = 0;
12922 int peers_mon_online = 0;
12923 int peers_mon_offline = 0;
12924 int peers_unmon_offline = 0;
12925 int peers_unmon_online = 0;
12926 const char *id;
12927 char idtext[256] = "";
12928 int realtimepeers;
12929 int objcount = ao2_container_count(peers);
12930 struct sip_peer **peerarray;
12931 int k;
12934 realtimepeers = ast_check_realtime("sippeers");
12935 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
12937 if (s) { /* Manager - get ActionID */
12938 id = astman_get_header(m, "ActionID");
12939 if (!ast_strlen_zero(id))
12940 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
12943 switch (argc) {
12944 case 5:
12945 if (!strcasecmp(argv[3], "like")) {
12946 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
12947 return CLI_SHOWUSAGE;
12948 havepattern = TRUE;
12949 } else
12950 return CLI_SHOWUSAGE;
12951 case 3:
12952 break;
12953 default:
12954 return CLI_SHOWUSAGE;
12957 if (!s) /* Normal list */
12958 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
12961 i = ao2_iterator_init(peers, 0);
12962 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
12963 ao2_lock(peer);
12964 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
12965 objcount--;
12966 ao2_unlock(peer);
12967 unref_peer(peer, "toss iterator peer ptr before continue");
12968 continue;
12971 peerarray[total_peers++] = peer;
12972 ao2_unlock(peer);
12975 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
12977 for(k=0; k < total_peers; k++) {
12978 char status[20] = "";
12979 char srch[2000];
12980 char pstatus;
12981 peer = peerarray[k];
12983 ao2_lock(peer);
12984 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
12985 ao2_unlock(peer);
12986 unref_peer(peer, "toss iterator peer ptr before continue");
12987 continue;
12990 if (!ast_strlen_zero(peer->username) && !s)
12991 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
12992 else
12993 ast_copy_string(name, peer->name, sizeof(name));
12995 pstatus = peer_status(peer, status, sizeof(status));
12996 if (pstatus == 1)
12997 peers_mon_online++;
12998 else if (pstatus == 0)
12999 peers_mon_offline++;
13000 else {
13001 if (peer->addr.sin_port == 0)
13002 peers_unmon_offline++;
13003 else
13004 peers_unmon_online++;
13007 snprintf(srch, sizeof(srch), FORMAT, name,
13008 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13009 peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
13010 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
13011 peer->ha ? " A " : " ", /* permit/deny */
13012 ntohs(peer->addr.sin_port), status,
13013 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13015 if (!s) {/* Normal CLI list */
13016 ast_cli(fd, FORMAT, name,
13017 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13018 peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
13019 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
13020 peer->ha ? " A " : " ", /* permit/deny */
13022 ntohs(peer->addr.sin_port), status,
13023 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13024 } else { /* Manager format */
13025 /* The names here need to be the same as other channels */
13026 astman_append(s,
13027 "Event: PeerEntry\r\n%s"
13028 "Channeltype: SIP\r\n"
13029 "ObjectName: %s\r\n"
13030 "ChanObjectType: peer\r\n" /* "peer" or "user" */
13031 "IPaddress: %s\r\n"
13032 "IPport: %d\r\n"
13033 "Dynamic: %s\r\n"
13034 "Natsupport: %s\r\n"
13035 "VideoSupport: %s\r\n"
13036 "TextSupport: %s\r\n"
13037 "ACL: %s\r\n"
13038 "Status: %s\r\n"
13039 "RealtimeDevice: %s\r\n\r\n",
13040 idtext,
13041 peer->name,
13042 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
13043 ntohs(peer->addr.sin_port),
13044 peer->host_dynamic ? "yes" : "no", /* Dynamic or not? */
13045 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no", /* NAT=yes? */
13046 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
13047 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no", /* TEXTSUPPORT=yes? */
13048 peer->ha ? "yes" : "no", /* permit/deny */
13049 status,
13050 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
13052 ao2_unlock(peer);
13053 unref_peer(peer, "toss iterator peer ptr");
13056 if (!s)
13057 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
13058 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
13060 if (havepattern)
13061 regfree(&regexbuf);
13063 if (total)
13064 *total = total_peers;
13066 ast_free(peerarray);
13068 return CLI_SUCCESS;
13069 #undef FORMAT
13070 #undef FORMAT2
13073 static int user_dump_func(void *userobj, void *arg, int flags)
13075 struct sip_user *user = userobj;
13076 int refc = ao2_t_ref(userobj, 0, "");
13077 int *fd = arg;
13079 ast_cli(*fd, "name: %s\ntype: user\nobjflags: %d\nrefcount: %d\n\n", user->name, 0, refc);
13080 return 0;
13083 static int peer_dump_func(void *userobj, void *arg, int flags)
13085 struct sip_peer *peer = userobj;
13086 int refc = ao2_t_ref(userobj, 0, "");
13087 int *fd = arg;
13089 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
13090 peer->name, 0, refc);
13091 return 0;
13094 static int dialog_dump_func(void *userobj, void *arg, int flags)
13096 struct sip_pvt *pvt = userobj;
13097 int refc = ao2_t_ref(userobj, 0, "");
13098 int *fd = arg;
13100 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
13101 pvt->callid, 0, refc);
13102 return 0;
13106 /*! \brief List all allocated SIP Objects (realtime or static) */
13107 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13109 char tmp[256];
13111 switch (cmd) {
13112 case CLI_INIT:
13113 e->command = "sip show objects";
13114 e->usage =
13115 "Usage: sip show objects\n"
13116 " Lists status of known SIP objects\n";
13117 return NULL;
13118 case CLI_GENERATE:
13119 return NULL;
13122 if (a->argc != 3)
13123 return CLI_SHOWUSAGE;
13124 ast_cli(a->fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
13125 ao2_t_callback(users, OBJ_NODATA, user_dump_func, &a->fd, "initiate ao2_callback to dump users");
13126 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
13127 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
13128 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
13129 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
13130 ast_cli(a->fd, "-= Dialog objects:\n\n");
13131 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
13132 return CLI_SUCCESS;
13134 /*! \brief Print call group and pickup group */
13135 static void print_group(int fd, ast_group_t group, int crlf)
13137 char buf[256];
13138 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
13141 /*! \brief mapping between dtmf flags and strings */
13142 static struct _map_x_s dtmfstr[] = {
13143 { SIP_DTMF_RFC2833, "rfc2833" },
13144 { SIP_DTMF_INFO, "info" },
13145 { SIP_DTMF_SHORTINFO, "shortinfo" },
13146 { SIP_DTMF_INBAND, "inband" },
13147 { SIP_DTMF_AUTO, "auto" },
13148 { -1, NULL }, /* terminator */
13151 /*! \brief Convert DTMF mode to printable string */
13152 static const char *dtmfmode2str(int mode)
13154 return map_x_s(dtmfstr, mode, "<error>");
13157 /*! \brief maps a string to dtmfmode, returns -1 on error */
13158 static int str2dtmfmode(const char *str)
13160 return map_s_x(dtmfstr, str, -1);
13163 static struct _map_x_s insecurestr[] = {
13164 { SIP_INSECURE_PORT, "port" },
13165 { SIP_INSECURE_INVITE, "invite" },
13166 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
13167 { 0, "no" },
13168 { -1, NULL }, /* terminator */
13171 /*! \brief Convert Insecure setting to printable string */
13172 static const char *insecure2str(int mode)
13174 return map_x_s(insecurestr, mode, "<error>");
13177 /*! \brief Destroy disused contexts between reloads
13178 Only used in reload_config so the code for regcontext doesn't get ugly
13180 static void cleanup_stale_contexts(char *new, char *old)
13182 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
13184 while ((oldcontext = strsep(&old, "&"))) {
13185 stalecontext = '\0';
13186 ast_copy_string(newlist, new, sizeof(newlist));
13187 stringp = newlist;
13188 while ((newcontext = strsep(&stringp, "&"))) {
13189 if (strcmp(newcontext, oldcontext) == 0) {
13190 /* This is not the context you're looking for */
13191 stalecontext = '\0';
13192 break;
13193 } else if (strcmp(newcontext, oldcontext)) {
13194 stalecontext = oldcontext;
13198 if (stalecontext)
13199 ast_context_destroy(ast_context_find(stalecontext), "SIP");
13203 /* this func is used with ao2_callback to unlink/delete all dialogs that
13204 are marked needdestroy. It will return CMP_MATCH for candidates, and they
13205 will be unlinked */
13207 /* TODO: Implement a queue and instead of marking a dialog
13208 to be destroyed, toss it into the queue. Have a separate
13209 thread do the locking and destruction */
13211 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
13213 struct sip_pvt *dialog = dialogobj;
13214 time_t *t = arg;
13216 /* log_show_lock(ao2_object_get_lockaddr(dialog)); this is an example of how to use log_show_lock() */
13217 if (sip_pvt_trylock(dialog)) {
13218 /* In very short-duration calls via sipp,
13219 this path gets executed fairly frequently (3% or so) even in low load
13220 situations; the routines we most commonly fight for a lock with:
13221 sip_answer (7 out of 9)
13222 sip_hangup (2 out of 9)
13224 ao2_unlock(dialogs);
13225 usleep(1);
13226 ao2_lock(dialogs);
13227 /* I had previously returned CMP_STOP here; but changed it to return
13228 a zero instead, because there is no need to stop at the first sign
13229 of trouble. The old algorithm would restart in such circumstances,
13230 but there is no need for this now in astobj2-land. We'll
13231 just skip over this element this time, and catch it on the
13232 next traversal, which is about once a second or so. See the
13233 ao2_callback call in do_monitor. We don't want the number of
13234 dialogs to back up too much between runs.
13236 return 0;
13239 /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
13240 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
13241 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
13242 sip_pvt_unlock(dialog);
13243 return 0;
13246 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
13247 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
13248 sip_pvt_unlock(dialog);
13249 return 0;
13251 /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
13252 check_rtp_timeout(dialog, *t);
13254 /* If we have sessions that needs to be destroyed, do it now */
13255 /* Check if we have outstanding requests not responsed to or an active call
13256 - if that's the case, wait with destruction */
13257 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
13258 sip_pvt_unlock(dialog);
13259 /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
13260 /* the CMP_MATCH will unlink this dialog from the dialog hash table */
13261 dialog_unlink_all(dialog, TRUE, FALSE);
13262 return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
13264 sip_pvt_unlock(dialog);
13265 return 0;
13268 /* this func is used with ao2_callback to unlink/delete all marked
13269 peers */
13270 static int peer_is_marked(void *peerobj, void *arg, int flags)
13272 struct sip_peer *peer = peerobj;
13273 return peer->the_mark ? CMP_MATCH : 0;
13276 /* this func is used with ao2_callback to unlink/delete all marked
13277 users */
13278 static int user_is_marked(void *userobj, void *arg, int flags)
13280 struct sip_user *user = userobj;
13281 return user->the_mark ? CMP_MATCH : 0;
13284 /*! \brief Remove temporary realtime objects from memory (CLI) */
13285 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13287 struct sip_peer *peer, *pi;
13288 struct sip_user *user, *ui;
13289 int pruneuser = FALSE;
13290 int prunepeer = FALSE;
13291 int multi = FALSE;
13292 char *name = NULL;
13293 regex_t regexbuf;
13294 struct ao2_iterator i;
13296 if (cmd == CLI_INIT) {
13297 e->command = "sip prune realtime [peer|user|all] [all|like]";
13298 e->usage =
13299 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
13300 " Prunes object(s) from the cache.\n"
13301 " Optional regular expression pattern is used to filter the objects.\n";
13302 return NULL;
13303 } else if (cmd == CLI_GENERATE) {
13304 if (a->pos == 4) {
13305 if (strcasestr(a->line, "realtime peer"))
13306 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
13307 else if (strcasestr(a->line, "realtime user"))
13308 return complete_sip_user(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
13310 return NULL;
13312 switch (a->argc) {
13313 case 4:
13314 name = a->argv[3];
13315 /* we accept a name in position 3, but keywords are not good. */
13316 if (!strcasecmp(name, "user") || !strcasecmp(name, "peer") ||
13317 !strcasecmp(name, "like"))
13318 return CLI_SHOWUSAGE;
13319 pruneuser = prunepeer = TRUE;
13320 if (!strcasecmp(name, "all")) {
13321 multi = TRUE;
13322 name = NULL;
13324 /* else a single name, already set */
13325 break;
13326 case 5:
13327 /* sip prune realtime {user|peer|like} name */
13328 name = a->argv[4];
13329 if (!strcasecmp(a->argv[3], "user"))
13330 pruneuser = TRUE;
13331 else if (!strcasecmp(a->argv[3], "peer"))
13332 prunepeer = TRUE;
13333 else if (!strcasecmp(a->argv[3], "like")) {
13334 pruneuser = prunepeer = TRUE;
13335 multi = TRUE;
13336 } else
13337 return CLI_SHOWUSAGE;
13338 if (!strcasecmp(a->argv[4], "like"))
13339 return CLI_SHOWUSAGE;
13340 if (!multi && !strcasecmp(a->argv[4], "all")) {
13341 multi = TRUE;
13342 name = NULL;
13344 break;
13345 case 6:
13346 name = a->argv[5];
13347 multi = TRUE;
13348 /* sip prune realtime {user|peer} like name */
13349 if (strcasecmp(a->argv[4], "like"))
13350 return CLI_SHOWUSAGE;
13351 if (!strcasecmp(a->argv[3], "user")) {
13352 pruneuser = TRUE;
13353 } else if (!strcasecmp(a->argv[3], "peer")) {
13354 prunepeer = TRUE;
13355 } else
13356 return CLI_SHOWUSAGE;
13357 break;
13358 default:
13359 return CLI_SHOWUSAGE;
13362 if (multi && name) {
13363 if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
13364 return CLI_SHOWUSAGE;
13367 if (multi) {
13368 if (prunepeer) {
13369 int pruned = 0;
13371 i = ao2_iterator_init(peers, 0);
13372 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13373 ao2_lock(pi);
13374 if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
13375 unref_peer(pi, "toss iterator peer ptr before continue");
13376 ao2_unlock(pi);
13377 continue;
13379 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13380 pi->the_mark = 1;
13381 pruned++;
13383 ao2_unlock(pi);
13384 unref_peer(pi, "toss iterator peer ptr");
13386 if (pruned) {
13387 ao2_t_callback(peers, OBJ_NODATA|OBJ_UNLINK, peer_is_marked, 0, "initiating callback to remove marked peers");
13388 ast_cli(a->fd, "%d peers pruned.\n", pruned);
13389 } else
13390 ast_cli(a->fd, "No peers found to prune.\n");
13392 if (pruneuser) {
13393 int pruned = 0;
13395 i = ao2_iterator_init(users, 0);
13396 while ((ui = ao2_t_iterator_next(&i, "iterate thru users table"))) {
13397 ao2_lock(ui);
13398 if (name && regexec(&regexbuf, ui->name, 0, NULL, 0)) {
13399 unref_user(ui, "toss iterator user ptr before continue");
13400 ao2_unlock(ui);
13401 continue;
13403 if (ast_test_flag(&ui->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13404 ui->the_mark = 1;
13405 pruned++;
13407 ao2_unlock(ui);
13408 unref_user(ui, "toss iterator user ptr");
13410 if (pruned) {
13411 ao2_t_callback(users, OBJ_NODATA|OBJ_UNLINK, user_is_marked, 0, "callback to remove marked users");
13412 ast_cli(a->fd, "%d users pruned.\n", pruned);
13413 } else
13414 ast_cli(a->fd, "No users found to prune.\n");
13416 } else {
13417 if (prunepeer) {
13418 struct sip_peer tmp;
13419 ast_copy_string(tmp.name, name, sizeof(tmp.name));
13420 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER|OBJ_UNLINK, "finding to unlink from peers"))) {
13421 if (peer->addr.sin_addr.s_addr) {
13422 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
13424 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13425 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
13426 /* put it back! */
13427 ao2_t_link(peers, peer, "link peer into peer table");
13428 if (peer->addr.sin_addr.s_addr) {
13429 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
13432 } else
13433 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
13434 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
13435 } else
13436 ast_cli(a->fd, "Peer '%s' not found.\n", name);
13438 if (pruneuser) {
13439 struct sip_user tmp;
13440 ast_copy_string(tmp.name, name, sizeof(tmp.name));
13441 if ((user = ao2_t_find(users, &tmp, OBJ_POINTER|OBJ_UNLINK, "finding to unlink from users table"))) {
13442 if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13443 ast_cli(a->fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
13444 /* put it back! */
13445 ao2_t_link(users, user, "link unlinked user back into users table");
13446 } else
13447 ast_cli(a->fd, "User '%s' pruned.\n", name);
13448 unref_user(user, "unref_user: Tossing temp user ptr");
13449 } else
13450 ast_cli(a->fd, "User '%s' not found.\n", name);
13454 return CLI_SUCCESS;
13457 /*! \brief Print codec list from preference to CLI/manager */
13458 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
13460 int x, codec;
13462 for(x = 0; x < 32 ; x++) {
13463 codec = ast_codec_pref_index(pref, x);
13464 if (!codec)
13465 break;
13466 ast_cli(fd, "%s", ast_getformatname(codec));
13467 ast_cli(fd, ":%d", pref->framing[x]);
13468 if (x < 31 && ast_codec_pref_index(pref, x + 1))
13469 ast_cli(fd, ",");
13471 if (!x)
13472 ast_cli(fd, "none");
13475 /*! \brief Print domain mode to cli */
13476 static const char *domain_mode_to_text(const enum domain_mode mode)
13478 switch (mode) {
13479 case SIP_DOMAIN_AUTO:
13480 return "[Automatic]";
13481 case SIP_DOMAIN_CONFIG:
13482 return "[Configured]";
13485 return "";
13488 /*! \brief CLI command to list local domains */
13489 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13491 struct domain *d;
13492 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
13494 switch (cmd) {
13495 case CLI_INIT:
13496 e->command = "sip show domains";
13497 e->usage =
13498 "Usage: sip show domains\n"
13499 " Lists all configured SIP local domains.\n"
13500 " Asterisk only responds to SIP messages to local domains.\n";
13501 return NULL;
13502 case CLI_GENERATE:
13503 return NULL;
13506 if (AST_LIST_EMPTY(&domain_list)) {
13507 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
13508 return CLI_SUCCESS;
13509 } else {
13510 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
13511 AST_LIST_LOCK(&domain_list);
13512 AST_LIST_TRAVERSE(&domain_list, d, list)
13513 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
13514 domain_mode_to_text(d->mode));
13515 AST_LIST_UNLOCK(&domain_list);
13516 ast_cli(a->fd, "\n");
13517 return CLI_SUCCESS;
13520 #undef FORMAT
13522 static char mandescr_show_peer[] =
13523 "Description: Show one SIP peer with details on current status.\n"
13524 "Variables: \n"
13525 " Peer: <name> The peer name you want to check.\n"
13526 " ActionID: <id> Optional action ID for this AMI transaction.\n";
13528 /*! \brief Show SIP peers in the manager API */
13529 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
13531 const char *a[4];
13532 const char *peer;
13534 peer = astman_get_header(m, "Peer");
13535 if (ast_strlen_zero(peer)) {
13536 astman_send_error(s, m, "Peer: <name> missing.\n");
13537 return 0;
13539 a[0] = "sip";
13540 a[1] = "show";
13541 a[2] = "peer";
13542 a[3] = peer;
13544 _sip_show_peer(1, -1, s, m, 4, a);
13545 astman_append(s, "\r\n\r\n" );
13546 return 0;
13549 /*! \brief Show one peer in detail */
13550 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13552 switch (cmd) {
13553 case CLI_INIT:
13554 e->command = "sip show peer";
13555 e->usage =
13556 "Usage: sip show peer <name> [load]\n"
13557 " Shows all details on one SIP peer and the current status.\n"
13558 " Option \"load\" forces lookup of peer in realtime storage.\n";
13559 return NULL;
13560 case CLI_GENERATE:
13561 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
13563 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
13566 /*! \brief Show one peer in detail (main function) */
13567 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13569 struct sip_peer *peer;
13570 int load_realtime;
13572 if (argc < 4)
13573 return CLI_SHOWUSAGE;
13575 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13576 if ((peer = find_peer(argv[3], NULL, load_realtime))) {
13577 sip_poke_peer(peer, 1);
13578 unref_peer(peer, "qualify: done with peer");
13579 } else if (type == 0) {
13580 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
13581 } else {
13582 astman_send_error(s, m, "Peer not found\n");
13584 return CLI_SUCCESS;
13587 /*! \brief Qualify SIP peers in the manager API */
13588 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
13590 const char *a[4];
13591 const char *peer;
13593 peer = astman_get_header(m, "Peer");
13594 if (ast_strlen_zero(peer)) {
13595 astman_send_error(s, m, "Peer: <name> missing.\n");
13596 return 0;
13598 a[0] = "sip";
13599 a[1] = "qualify";
13600 a[2] = "peer";
13601 a[3] = peer;
13603 _sip_qualify_peer(1, -1, s, m, 4, a);
13604 astman_append(s, "\r\n\r\n" );
13605 return 0;
13608 /*! \brief Send an OPTIONS packet to a SIP peer */
13609 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13611 switch (cmd) {
13612 case CLI_INIT:
13613 e->command = "sip qualify peer";
13614 e->usage =
13615 "Usage: sip qualify peer <name> [load]\n"
13616 " Requests a response from one SIP peer and the current status.\n"
13617 " Option \"load\" forces lookup of peer in realtime storage.\n";
13618 return NULL;
13619 case CLI_GENERATE:
13620 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
13622 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
13625 /*! \brief list peer mailboxes to CLI */
13626 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
13628 struct sip_mailbox *mailbox;
13630 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
13631 ast_str_append(mailbox_str, 0, "%s%s%s%s",
13632 mailbox->mailbox,
13633 ast_strlen_zero(mailbox->context) ? "" : "@",
13634 S_OR(mailbox->context, ""),
13635 AST_LIST_NEXT(mailbox, entry) ? "," : "");
13639 /*! \brief Show one peer in detail (main function) */
13640 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13642 char status[30] = "";
13643 char cbuf[256];
13644 struct sip_peer *peer;
13645 char codec_buf[512];
13646 struct ast_codec_pref *pref;
13647 struct ast_variable *v;
13648 struct sip_auth *auth;
13649 int x = 0, codec = 0, load_realtime;
13650 int realtimepeers;
13652 realtimepeers = ast_check_realtime("sippeers");
13654 if (argc < 4)
13655 return CLI_SHOWUSAGE;
13657 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13658 peer = find_peer(argv[3], NULL, load_realtime);
13659 if (s) { /* Manager */
13660 if (peer) {
13661 const char *id = astman_get_header(m, "ActionID");
13663 astman_append(s, "Response: Success\r\n");
13664 if (!ast_strlen_zero(id))
13665 astman_append(s, "ActionID: %s\r\n", id);
13666 } else {
13667 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
13668 astman_send_error(s, m, cbuf);
13669 return CLI_SUCCESS;
13672 if (peer && type==0 ) { /* Normal listing */
13673 struct ast_str *mailbox_str = ast_str_alloca(512);
13674 ast_cli(fd, "\n\n");
13675 ast_cli(fd, " * Name : %s\n", peer->name);
13676 if (realtimepeers) { /* Realtime is enabled */
13677 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
13679 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
13680 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
13681 for (auth = peer->auth; auth; auth = auth->next) {
13682 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
13683 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
13685 ast_cli(fd, " Context : %s\n", peer->context);
13686 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
13687 ast_cli(fd, " Language : %s\n", peer->language);
13688 if (!ast_strlen_zero(peer->accountcode))
13689 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
13690 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
13691 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
13692 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
13693 if (!ast_strlen_zero(peer->fromuser))
13694 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
13695 if (!ast_strlen_zero(peer->fromdomain))
13696 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
13697 ast_cli(fd, " Callgroup : ");
13698 print_group(fd, peer->callgroup, 0);
13699 ast_cli(fd, " Pickupgroup : ");
13700 print_group(fd, peer->pickupgroup, 0);
13701 peer_mailboxes_to_str(&mailbox_str, peer);
13702 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
13703 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
13704 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
13705 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
13706 if (peer->busy_level)
13707 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
13708 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
13709 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
13710 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
13711 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
13712 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
13713 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
13714 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
13715 ast_cli(fd, " T38 pt UDPTL : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)));
13716 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
13717 ast_cli(fd, " T38 pt RTP : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)));
13718 ast_cli(fd, " T38 pt TCP : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)));
13719 #endif
13720 ast_cli(fd, " CanReinvite : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
13721 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
13722 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
13723 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
13724 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
13725 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
13726 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
13727 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
13728 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
13729 if (peer->outboundproxy)
13730 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
13731 peer->outboundproxy->force ? "(forced)" : "");
13733 /* - is enumerated */
13734 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
13735 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
13736 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
13737 ast_cli(fd, " ToHost : %s\n", peer->tohost);
13738 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));
13739 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
13740 ast_cli(fd, " Transport : %s\n", get_transport(peer->socket.type));
13741 if (!ast_strlen_zero(global_regcontext))
13742 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
13743 ast_cli(fd, " Def. Username: %s\n", peer->username);
13744 ast_cli(fd, " SIP Options : ");
13745 if (peer->sipoptions) {
13746 int lastoption = -1;
13747 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
13748 if (sip_options[x].id != lastoption) {
13749 if (peer->sipoptions & sip_options[x].id)
13750 ast_cli(fd, "%s ", sip_options[x].text);
13751 lastoption = x;
13754 } else
13755 ast_cli(fd, "(none)");
13757 ast_cli(fd, "\n");
13758 ast_cli(fd, " Codecs : ");
13759 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
13760 ast_cli(fd, "%s\n", codec_buf);
13761 ast_cli(fd, " Codec Order : (");
13762 print_codec_to_cli(fd, &peer->prefs);
13763 ast_cli(fd, ")\n");
13765 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
13766 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
13767 ast_cli(fd, " Status : ");
13768 peer_status(peer, status, sizeof(status));
13769 ast_cli(fd, "%s\n", status);
13770 ast_cli(fd, " Useragent : %s\n", peer->useragent);
13771 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
13772 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
13773 if (peer->chanvars) {
13774 ast_cli(fd, " Variables :\n");
13775 for (v = peer->chanvars ; v ; v = v->next)
13776 ast_cli(fd, " %s = %s\n", v->name, v->value);
13779 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
13780 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
13781 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
13782 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
13783 ast_cli(fd, "\n");
13784 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
13785 } else if (peer && type == 1) { /* manager listing */
13786 char buf[256];
13787 struct ast_str *mailbox_str = ast_str_alloca(512);
13788 astman_append(s, "Channeltype: SIP\r\n");
13789 astman_append(s, "ObjectName: %s\r\n", peer->name);
13790 astman_append(s, "ChanObjectType: peer\r\n");
13791 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
13792 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
13793 astman_append(s, "Context: %s\r\n", peer->context);
13794 astman_append(s, "Language: %s\r\n", peer->language);
13795 if (!ast_strlen_zero(peer->accountcode))
13796 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
13797 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
13798 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
13799 if (!ast_strlen_zero(peer->fromuser))
13800 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
13801 if (!ast_strlen_zero(peer->fromdomain))
13802 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
13803 astman_append(s, "Callgroup: ");
13804 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
13805 astman_append(s, "Pickupgroup: ");
13806 astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
13807 peer_mailboxes_to_str(&mailbox_str, peer);
13808 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
13809 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
13810 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
13811 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
13812 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
13813 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
13814 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
13815 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
13816 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
13817 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
13818 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
13819 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
13820 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
13821 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
13822 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
13823 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
13824 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
13825 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
13826 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
13827 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
13828 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
13830 /* - is enumerated */
13831 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
13832 astman_append(s, "ToHost: %s\r\n", peer->tohost);
13833 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));
13834 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));
13835 astman_append(s, "Default-Username: %s\r\n", peer->username);
13836 if (!ast_strlen_zero(global_regcontext))
13837 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
13838 astman_append(s, "Codecs: ");
13839 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
13840 astman_append(s, "%s\r\n", codec_buf);
13841 astman_append(s, "CodecOrder: ");
13842 pref = &peer->prefs;
13843 for(x = 0; x < 32 ; x++) {
13844 codec = ast_codec_pref_index(pref, x);
13845 if (!codec)
13846 break;
13847 astman_append(s, "%s", ast_getformatname(codec));
13848 if (x < 31 && ast_codec_pref_index(pref, x+1))
13849 astman_append(s, ",");
13852 astman_append(s, "\r\n");
13853 astman_append(s, "Status: ");
13854 peer_status(peer, status, sizeof(status));
13855 astman_append(s, "%s\r\n", status);
13856 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
13857 astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
13858 astman_append(s, "QualifyFreq : %d ms\n", peer->qualifyfreq);
13859 if (peer->chanvars) {
13860 for (v = peer->chanvars ; v ; v = v->next) {
13861 astman_append(s, "ChanVariable:\n");
13862 astman_append(s, " %s,%s\r\n", v->name, v->value);
13866 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
13868 } else {
13869 ast_cli(fd, "Peer %s not found.\n", argv[3]);
13870 ast_cli(fd, "\n");
13873 return CLI_SUCCESS;
13876 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13878 char cbuf[2256];
13879 struct ast_cb_names cbnames = {9, { "retrans_pkt",
13880 "__sip_autodestruct",
13881 "expire_register",
13882 "auto_congest",
13883 "sip_reg_timeout",
13884 "sip_poke_peer_s",
13885 "sip_poke_noanswer",
13886 "sip_reregister",
13887 "sip_reinvite_retry"},
13888 { retrans_pkt,
13889 __sip_autodestruct,
13890 expire_register,
13891 auto_congest,
13892 sip_reg_timeout,
13893 sip_poke_peer_s,
13894 sip_poke_noanswer,
13895 sip_reregister,
13896 sip_reinvite_retry}};
13898 switch (cmd) {
13899 case CLI_INIT:
13900 e->command = "sip show sched";
13901 e->usage =
13902 "Usage: sip show sched\n"
13903 " Shows stats on what's in the sched queue at the moment\n";
13904 return NULL;
13905 case CLI_GENERATE:
13906 return NULL;
13908 ast_cli(a->fd, "\n");
13909 ast_sched_report(sched, cbuf, sizeof(cbuf), &cbnames);
13910 ast_cli(a->fd, "%s", cbuf);
13911 return CLI_SUCCESS;
13914 /*! \brief Show one user in detail */
13915 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13917 char cbuf[256];
13918 struct sip_user *user;
13919 struct ast_variable *v;
13920 int load_realtime;
13922 switch (cmd) {
13923 case CLI_INIT:
13924 e->command = "sip show user";
13925 e->usage =
13926 "Usage: sip show user <name> [load]\n"
13927 " Shows all details on one SIP user and the current status.\n"
13928 " Option \"load\" forces lookup of peer in realtime storage.\n";
13929 return NULL;
13930 case CLI_GENERATE:
13931 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
13934 if (a->argc < 4)
13935 return CLI_SHOWUSAGE;
13937 /* Load from realtime storage? */
13938 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
13940 user = find_user(a->argv[3], load_realtime);
13941 if (user) {
13942 ast_cli(a->fd, "\n\n");
13943 ast_cli(a->fd, " * Name : %s\n", user->name);
13944 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
13945 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
13946 ast_cli(a->fd, " Context : %s\n", user->context);
13947 ast_cli(a->fd, " Language : %s\n", user->language);
13948 if (!ast_strlen_zero(user->accountcode))
13949 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
13950 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
13951 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
13952 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
13953 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
13954 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
13955 ast_cli(a->fd, " Callgroup : ");
13956 print_group(a->fd, user->callgroup, 0);
13957 ast_cli(a->fd, " Pickupgroup : ");
13958 print_group(a->fd, user->pickupgroup, 0);
13959 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
13960 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
13961 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
13962 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
13963 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
13964 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
13966 ast_cli(a->fd, " Codec Order : (");
13967 print_codec_to_cli(a->fd, &user->prefs);
13968 ast_cli(a->fd, ")\n");
13970 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
13971 if (user->chanvars) {
13972 ast_cli(a->fd, " Variables :\n");
13973 for (v = user->chanvars ; v ; v = v->next)
13974 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
13977 ast_cli(a->fd, "\n");
13978 unref_user(user, "unref_user from sip_show_user, near end");
13979 } else {
13980 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
13981 ast_cli(a->fd, "\n");
13984 return CLI_SUCCESS;
13987 /*! \brief Show SIP Registry (registrations with other SIP proxies */
13988 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13990 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
13991 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
13992 char host[80];
13993 char tmpdat[256];
13994 struct ast_tm tm;
13995 int counter = 0;
13997 switch (cmd) {
13998 case CLI_INIT:
13999 e->command = "sip show registry";
14000 e->usage =
14001 "Usage: sip show registry\n"
14002 " Lists all registration requests and status.\n";
14003 return NULL;
14004 case CLI_GENERATE:
14005 return NULL;
14008 if (a->argc != 3)
14009 return CLI_SHOWUSAGE;
14010 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
14012 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14013 ASTOBJ_RDLOCK(iterator);
14014 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
14015 if (iterator->regtime.tv_sec) {
14016 ast_localtime(&iterator->regtime, &tm, NULL);
14017 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
14018 } else
14019 tmpdat[0] = '\0';
14020 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
14021 ASTOBJ_UNLOCK(iterator);
14022 counter++;
14023 } while(0));
14024 ast_cli(a->fd, "%d SIP registrations.\n", counter);
14025 return CLI_SUCCESS;
14026 #undef FORMAT
14027 #undef FORMAT2
14030 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
14031 \note This function does not tell the SIP device what's going on,
14032 so use it with great care.
14034 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14036 struct sip_peer *peer;
14037 int load_realtime = 0;
14039 switch (cmd) {
14040 case CLI_INIT:
14041 e->command = "sip unregister";
14042 e->usage =
14043 "Usage: sip unregister <peer>\n"
14044 " Unregister (force expiration) a SIP peer from the registry\n";
14045 return NULL;
14046 case CLI_GENERATE:
14047 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
14050 if (a->argc != 3)
14051 return CLI_SHOWUSAGE;
14053 if ((peer = find_peer(a->argv[2], NULL, load_realtime))) {
14054 if (peer->expire > 0) {
14055 expire_register(peer);
14056 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
14057 } else {
14058 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
14060 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
14061 } else {
14062 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
14065 return CLI_SUCCESS;
14068 /*! \brief List global settings for the SIP channel */
14069 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14071 int realtimepeers;
14072 int realtimeusers;
14073 int realtimeregs;
14074 char codec_buf[SIPBUFSIZE];
14075 const char *msg; /* temporary msg pointer */
14077 switch (cmd) {
14078 case CLI_INIT:
14079 e->command = "sip show settings";
14080 e->usage =
14081 "Usage: sip show settings\n"
14082 " Provides detailed list of the configuration of the SIP channel.\n";
14083 return NULL;
14084 case CLI_GENERATE:
14085 return NULL;
14089 realtimepeers = ast_check_realtime("sippeers");
14090 realtimeusers = ast_check_realtime("sipusers");
14091 realtimeregs = ast_check_realtime("sipregs");
14093 if (a->argc != 3)
14094 return CLI_SHOWUSAGE;
14095 ast_cli(a->fd, "\n\nGlobal Settings:\n");
14096 ast_cli(a->fd, "----------------\n");
14097 ast_cli(a->fd, " SIP Port: %d\n", ntohs(bindaddr.sin_port));
14098 ast_cli(a->fd, " Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
14099 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14100 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
14101 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(autocreatepeer));
14102 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
14103 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(global_allowguest));
14104 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14105 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
14106 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14107 ast_cli(a->fd, " Promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
14108 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
14109 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
14110 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
14111 ast_cli(a->fd, " Our auth realm %s\n", global_realm);
14112 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
14113 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(global_alwaysauthreject));
14114 ast_cli(a->fd, " Call limit peers only: %s\n", cli_yesno(global_limitonpeers));
14115 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(global_directrtpsetup));
14116 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
14117 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
14118 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
14119 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
14120 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(global_regextenonqualify));
14121 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
14122 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
14123 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
14124 ast_cli(a->fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
14125 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
14127 ast_cli(a->fd, " T38 fax pt UDPTL: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)));
14128 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
14129 ast_cli(a->fd, " T38 fax pt RTP: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP)));
14130 ast_cli(a->fd, " T38 fax pt TCP: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP)));
14131 #endif
14132 if (!realtimepeers && !realtimeusers && !realtimeregs)
14133 ast_cli(a->fd, " SIP realtime: Disabled\n" );
14134 else
14135 ast_cli(a->fd, " SIP realtime: Enabled\n" );
14136 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
14137 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
14138 ast_cli(a->fd, "---------------------------\n");
14139 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
14140 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
14141 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
14142 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
14143 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
14144 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
14145 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
14146 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
14147 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
14148 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
14149 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
14150 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
14151 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
14152 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
14154 ast_cli(a->fd, "\nNetwork Settings:\n");
14155 ast_cli(a->fd, "---------------------------\n");
14156 /* determine if/how SIP address can be remapped */
14157 if (localaddr == NULL)
14158 msg = "Disabled, no localnet list";
14159 else if (externip.sin_addr.s_addr == 0)
14160 msg = "Disabled, externip is 0.0.0.0";
14161 else if (stunaddr.sin_addr.s_addr != 0)
14162 msg = "Enabled using STUN";
14163 else if (!ast_strlen_zero(externhost))
14164 msg = "Enabled using externhost";
14165 else
14166 msg = "Enabled using externip";
14167 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
14168 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
14169 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
14170 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
14171 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
14173 struct ast_ha *d;
14174 const char *prefix = "Localnet:";
14175 char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
14177 for (d = localaddr; d ; prefix = "", d = d->next) {
14178 ast_cli(a->fd, " %-24s%s/%s\n",
14179 prefix, ast_inet_ntoa(d->netaddr),
14180 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
14183 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
14185 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
14186 ast_cli(a->fd, "---------------------------\n");
14187 ast_cli(a->fd, " Codecs: ");
14188 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
14189 ast_cli(a->fd, "%s\n", codec_buf);
14190 ast_cli(a->fd, " Codec Order: ");
14191 print_codec_to_cli(a->fd, &default_prefs);
14192 ast_cli(a->fd, "\n");
14193 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
14194 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
14195 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(compactheaders));
14196 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
14197 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
14198 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
14199 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
14200 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(global_srvlookup));
14201 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(pedanticsipchecking));
14202 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
14203 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
14204 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
14205 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
14206 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
14207 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(global_notifyringing));
14208 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(global_notifyhold));
14209 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
14210 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
14211 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
14212 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
14213 global_outboundproxy.force ? "(forced)" : "");
14214 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
14215 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
14216 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
14217 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
14218 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
14219 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
14220 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
14222 ast_cli(a->fd, "\nDefault Settings:\n");
14223 ast_cli(a->fd, "-----------------\n");
14224 ast_cli(a->fd, " Context: %s\n", default_context);
14225 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
14226 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
14227 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
14228 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
14229 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" );
14230 ast_cli(a->fd, " Language: %s\n", default_language);
14231 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
14232 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
14233 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
14236 if (realtimepeers || realtimeusers || realtimeregs) {
14237 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
14238 ast_cli(a->fd, "----------------------\n");
14239 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
14240 ast_cli(a->fd, " Realtime Users: %s\n", cli_yesno(realtimeusers));
14241 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
14242 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
14243 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
14244 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
14245 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
14246 ast_cli(a->fd, " Auto Clear: %d\n", global_rtautoclear);
14248 ast_cli(a->fd, "\n----\n");
14249 return CLI_SUCCESS;
14252 /*! \brief Show subscription type in string format */
14253 static const char *subscription_type2str(enum subscriptiontype subtype)
14255 int i;
14257 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
14258 if (subscription_types[i].type == subtype) {
14259 return subscription_types[i].text;
14262 return subscription_types[0].text;
14265 /*! \brief Find subscription type in array */
14266 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
14268 int i;
14270 for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
14271 if (subscription_types[i].type == subtype) {
14272 return &subscription_types[i];
14275 return &subscription_types[0];
14279 * We try to structure all functions that loop on data structures as
14280 * a handler for individual entries, and a mainloop that iterates
14281 * on the main data structure. This way, moving the code to containers
14282 * that support iteration through callbacks will be a lot easier.
14285 /*! \brief argument for the 'show channels|subscriptions' callback. */
14286 struct __show_chan_arg {
14287 int fd;
14288 int subscriptions;
14289 int numchans; /* return value */
14292 #define FORMAT4 "%-15.15s %-10.10s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
14293 #define FORMAT3 "%-15.15s %-10.10s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
14294 #define FORMAT2 "%-15.15s %-10.10s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
14295 #define FORMAT "%-15.15s %-10.10s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
14297 /*! \brief callback for show channel|subscription */
14298 static int show_channels_cb(void *__cur, void *__arg, int flags)
14300 struct sip_pvt *cur = __cur;
14301 struct __show_chan_arg *arg = __arg;
14302 const struct sockaddr_in *dst = sip_real_dst(cur);
14304 /* XXX indentation preserved to reduce diff. Will be fixed later */
14305 if (cur->subscribed == NONE && !arg->subscriptions) {
14306 /* set if SIP transfer in progress */
14307 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
14308 char formatbuf[SIPBUFSIZE/2];
14310 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
14311 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
14312 cur->callid,
14313 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
14314 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
14315 cur->needdestroy ? "(d)" : "",
14316 cur->lastmsg ,
14317 referstatus
14319 arg->numchans++;
14321 if (cur->subscribed != NONE && arg->subscriptions) {
14322 struct ast_str *mailbox_str = ast_str_alloca(512);
14323 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
14324 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
14325 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
14326 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
14327 cur->callid,
14328 /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
14329 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
14330 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
14331 subscription_type2str(cur->subscribed),
14332 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
14333 cur->expiry
14335 arg->numchans++;
14337 return 0; /* don't care, we scan all channels */
14340 /*! \brief CLI for show channels or subscriptions.
14341 * This is a new-style CLI handler so a single function contains
14342 * the prototype for the function, the 'generator' to produce multiple
14343 * entries in case it is required, and the actual handler for the command.
14345 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14347 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
14350 if (cmd == CLI_INIT) {
14351 e->command = "sip show {channels|subscriptions}";
14352 e->usage =
14353 "Usage: sip show channels\n"
14354 " Lists all currently active SIP calls (dialogs).\n"
14355 "Usage: sip show subscriptions\n"
14356 " Lists active SIP subscriptions.\n";
14357 return NULL;
14358 } else if (cmd == CLI_GENERATE)
14359 return NULL;
14361 if (a->argc != e->args)
14362 return CLI_SHOWUSAGE;
14363 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
14364 if (!arg.subscriptions)
14365 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
14366 else
14367 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
14369 /* iterate on the container and invoke the callback on each item */
14370 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
14372 /* print summary information */
14373 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
14374 (arg.subscriptions ? "subscription" : "dialog"),
14375 ESS(arg.numchans)); /* ESS(n) returns an "s" if n>1 */
14376 return CLI_SUCCESS;
14377 #undef FORMAT
14378 #undef FORMAT2
14379 #undef FORMAT3
14382 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
14383 * This is in charge of generating all strings that match a prefix in the
14384 * given position. As many functions of this kind, each invokation has
14385 * O(state) time complexity so be careful in using it.
14389 static char *complete_sipch(const char *line, const char *word, int pos, int state)
14391 int which=0;
14392 struct sip_pvt *cur;
14393 char *c = NULL;
14394 int wordlen = strlen(word);
14395 struct ao2_iterator i;
14397 if (pos != 3) {
14398 return NULL;
14401 i = ao2_iterator_init(dialogs, 0);
14403 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14404 sip_pvt_lock(cur);
14405 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
14406 c = ast_strdup(cur->callid);
14407 sip_pvt_unlock(cur);
14408 dialog_unref(cur, "drop ref in iterator loop break");
14409 break;
14411 sip_pvt_unlock(cur);
14412 dialog_unref(cur, "drop ref in iterator loop");
14414 return c;
14418 /*! \brief Do completion on peer name */
14419 static char *complete_sip_peer(const char *word, int state, int flags2)
14421 char *result = NULL;
14422 int wordlen = strlen(word);
14423 int which = 0;
14424 struct ao2_iterator i = ao2_iterator_init(peers, 0);
14425 struct sip_peer *peer;
14427 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14428 /* locking of the object is not required because only the name and flags are being compared */
14429 if (!strncasecmp(word, peer->name, wordlen) &&
14430 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
14431 ++which > state)
14432 result = ast_strdup(peer->name);
14433 unref_peer(peer, "toss iterator peer ptr before break");
14434 if (result) {
14435 break;
14438 return result;
14441 /*! \brief Do completion on registered peer name */
14442 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
14444 char *result = NULL;
14445 int wordlen = strlen(word);
14446 int which = 0;
14447 struct ao2_iterator i;
14448 struct sip_peer *peer;
14450 i = ao2_iterator_init(peers, 0);
14451 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14452 if (!strncasecmp(word, peer->name, wordlen) &&
14453 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
14454 ++which > state && peer->expire > 0)
14455 result = ast_strdup(peer->name);
14456 if (result) {
14457 unref_peer(peer, "toss iterator peer ptr before break");
14458 break;
14460 unref_peer(peer, "toss iterator peer ptr");
14462 return result;
14465 /*! \brief Support routine for 'sip show history' CLI */
14466 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
14468 if (pos == 3)
14469 return complete_sipch(line, word, pos, state);
14471 return NULL;
14474 /*! \brief Support routine for 'sip show peer' CLI */
14475 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
14477 if (pos == 3) {
14478 return complete_sip_peer(word, state, 0);
14481 return NULL;
14484 /*! \brief Support routine for 'sip unregister' CLI */
14485 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
14487 if (pos == 2)
14488 return complete_sip_registered_peer(word, state, 0);
14490 return NULL;
14493 /*! \brief Do completion on user name */
14494 static char *complete_sip_user(const char *word, int state, int flags2)
14496 char *result = NULL;
14497 int wordlen = strlen(word);
14498 int which = 0;
14499 struct ao2_iterator i;
14500 struct sip_user *user;
14502 i = ao2_iterator_init(users, 0);
14504 while ((user = ao2_t_iterator_next(&i, "iterate thru users table"))) {
14505 /* locking of the object is not required because only the name and flags are being compared */
14506 if (!strncasecmp(word, user->name, wordlen)) {
14507 if (flags2 && !ast_test_flag(&user->flags[1], flags2)) {
14508 unref_user(user, "toss iterator user ptr before continue");
14509 continue;
14511 if (++which > state) {
14512 result = ast_strdup(user->name);
14515 if (result) {
14516 unref_user(user, "toss iterator user ptr before break");
14517 break;
14519 unref_user(user, "toss iterator user ptr");
14521 return result;
14524 /*! \brief Support routine for 'sip show user' CLI */
14525 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
14527 if (pos == 3)
14528 return complete_sip_user(word, state, 0);
14530 return NULL;
14533 /*! \brief Support routine for 'sip notify' CLI */
14534 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
14536 char *c = NULL;
14538 if (pos == 2) {
14539 int which = 0;
14540 char *cat = NULL;
14541 int wordlen = strlen(word);
14543 /* do completion for notify type */
14545 if (!notify_types)
14546 return NULL;
14548 while ( (cat = ast_category_browse(notify_types, cat)) ) {
14549 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
14550 c = ast_strdup(cat);
14551 break;
14554 return c;
14557 if (pos > 2)
14558 return complete_sip_peer(word, state, 0);
14560 return NULL;
14563 /*! \brief Show details of one active dialog */
14564 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14566 struct sip_pvt *cur;
14567 size_t len;
14568 int found = 0;
14569 struct ao2_iterator i;
14571 switch (cmd) {
14572 case CLI_INIT:
14573 e->command = "sip show channel";
14574 e->usage =
14575 "Usage: sip show channel <call-id>\n"
14576 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
14577 return NULL;
14578 case CLI_GENERATE:
14579 return complete_sipch(a->line, a->word, a->pos, a->n);
14582 if (a->argc != 4)
14583 return CLI_SHOWUSAGE;
14584 len = strlen(a->argv[3]);
14586 i = ao2_iterator_init(dialogs, 0);
14588 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14589 sip_pvt_lock(cur);
14591 if (!strncasecmp(cur->callid, a->argv[3], len)) {
14592 char formatbuf[SIPBUFSIZE/2];
14593 ast_cli(a->fd, "\n");
14594 if (cur->subscribed != NONE)
14595 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
14596 else
14597 ast_cli(a->fd, " * SIP Call\n");
14598 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
14599 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
14600 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
14601 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
14602 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
14603 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
14604 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
14605 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
14606 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
14607 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
14608 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
14609 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
14610 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
14611 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
14612 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
14613 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)" );
14614 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
14615 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
14616 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
14617 if (!ast_strlen_zero(cur->username))
14618 ast_cli(a->fd, " Username: %s\n", cur->username);
14619 if (!ast_strlen_zero(cur->peername))
14620 ast_cli(a->fd, " Peername: %s\n", cur->peername);
14621 if (!ast_strlen_zero(cur->uri))
14622 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
14623 if (!ast_strlen_zero(cur->cid_num))
14624 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
14625 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
14626 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
14627 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
14628 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
14629 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
14630 ast_cli(a->fd, " SIP Options: ");
14631 if (cur->sipoptions) {
14632 int x;
14633 for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
14634 if (cur->sipoptions & sip_options[x].id)
14635 ast_cli(a->fd, "%s ", sip_options[x].text);
14637 ast_cli(a->fd, "\n");
14638 } else
14639 ast_cli(a->fd, "(none)\n");
14641 if (!cur->stimer)
14642 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
14643 else {
14644 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
14645 if (cur->stimer->st_active == TRUE) {
14646 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
14647 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
14648 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
14649 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
14650 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
14651 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
14652 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
14653 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
14654 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
14658 ast_cli(a->fd, "\n\n");
14660 found++;
14663 sip_pvt_unlock(cur);
14665 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
14668 if (!found)
14669 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
14671 return CLI_SUCCESS;
14674 /*! \brief Show history details of one dialog */
14675 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14677 struct sip_pvt *cur;
14678 size_t len;
14679 int found = 0;
14680 struct ao2_iterator i;
14682 switch (cmd) {
14683 case CLI_INIT:
14684 e->command = "sip show history";
14685 e->usage =
14686 "Usage: sip show history <call-id>\n"
14687 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
14688 return NULL;
14689 case CLI_GENERATE:
14690 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
14693 if (a->argc != 4)
14694 return CLI_SHOWUSAGE;
14696 if (!recordhistory)
14697 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
14699 len = strlen(a->argv[3]);
14701 i = ao2_iterator_init(dialogs, 0);
14702 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14703 sip_pvt_lock(cur);
14704 if (!strncasecmp(cur->callid, a->argv[3], len)) {
14705 struct sip_history *hist;
14706 int x = 0;
14708 ast_cli(a->fd, "\n");
14709 if (cur->subscribed != NONE)
14710 ast_cli(a->fd, " * Subscription\n");
14711 else
14712 ast_cli(a->fd, " * SIP Call\n");
14713 if (cur->history)
14714 AST_LIST_TRAVERSE(cur->history, hist, list)
14715 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
14716 if (x == 0)
14717 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
14718 found++;
14720 sip_pvt_unlock(cur);
14721 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
14724 if (!found)
14725 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
14727 return CLI_SUCCESS;
14730 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
14731 static void sip_dump_history(struct sip_pvt *dialog)
14733 int x = 0;
14734 struct sip_history *hist;
14735 static int errmsg = 0;
14737 if (!dialog)
14738 return;
14740 if (!option_debug && !sipdebug) {
14741 if (!errmsg) {
14742 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
14743 errmsg = 1;
14745 return;
14748 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
14749 if (dialog->subscribed)
14750 ast_debug(1, " * Subscription\n");
14751 else
14752 ast_debug(1, " * SIP Call\n");
14753 if (dialog->history)
14754 AST_LIST_TRAVERSE(dialog->history, hist, list)
14755 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
14756 if (!x)
14757 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
14758 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
14762 /*! \brief Receive SIP INFO Message */
14763 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
14765 char buf[1024];
14766 unsigned int event;
14767 const char *c = get_header(req, "Content-Type");
14769 /* Need to check the media/type */
14770 if (!strcasecmp(c, "application/dtmf-relay") ||
14771 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
14772 unsigned int duration = 0;
14774 if (!p->owner) { /* not a PBX call */
14775 transmit_response(p, "481 Call leg/transaction does not exist", req);
14776 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14777 return;
14780 /* Try getting the "signal=" part */
14781 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
14782 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
14783 transmit_response(p, "200 OK", req); /* Should return error */
14784 return;
14785 } else {
14786 ast_copy_string(buf, c, sizeof(buf));
14789 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
14790 duration = atoi(c);
14791 if (!duration)
14792 duration = 100; /* 100 ms */
14795 if (ast_strlen_zero(buf)) {
14796 transmit_response(p, "200 OK", req);
14797 return;
14800 if (buf[0] == '*')
14801 event = 10;
14802 else if (buf[0] == '#')
14803 event = 11;
14804 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
14805 event = 12 + buf[0] - 'A';
14806 else if (buf[0] == '!')
14807 event = 16;
14808 else
14809 event = atoi(buf);
14810 if (event == 16) {
14811 /* send a FLASH event */
14812 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
14813 ast_queue_frame(p->owner, &f);
14814 if (sipdebug)
14815 ast_verbose("* DTMF-relay event received: FLASH\n");
14816 } else {
14817 /* send a DTMF event */
14818 struct ast_frame f = { AST_FRAME_DTMF, };
14819 if (event < 10) {
14820 f.subclass = '0' + event;
14821 } else if (event < 11) {
14822 f.subclass = '*';
14823 } else if (event < 12) {
14824 f.subclass = '#';
14825 } else if (event < 16) {
14826 f.subclass = 'A' + (event - 12);
14828 f.len = duration;
14829 ast_queue_frame(p->owner, &f);
14830 if (sipdebug)
14831 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
14833 transmit_response(p, "200 OK", req);
14834 return;
14835 } else if (!strcasecmp(c, "application/dtmf")) {
14836 /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
14837 unsigned int duration = 0;
14839 if (!p->owner) { /* not a PBX call */
14840 transmit_response(p, "481 Call leg/transaction does not exist", req);
14841 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14842 return;
14845 get_msg_text(buf, sizeof(buf), req, TRUE);
14846 duration = 100; /* 100 ms */
14848 if (ast_strlen_zero(buf)) {
14849 transmit_response(p, "200 OK", req);
14850 return;
14852 event = atoi(buf);
14853 if (event == 16) {
14854 /* send a FLASH event */
14855 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
14856 ast_queue_frame(p->owner, &f);
14857 if (sipdebug)
14858 ast_verbose("* DTMF-relay event received: FLASH\n");
14859 } else {
14860 /* send a DTMF event */
14861 struct ast_frame f = { AST_FRAME_DTMF, };
14862 if (event < 10) {
14863 f.subclass = '0' + event;
14864 } else if (event < 11) {
14865 f.subclass = '*';
14866 } else if (event < 12) {
14867 f.subclass = '#';
14868 } else if (event < 16) {
14869 f.subclass = 'A' + (event - 12);
14871 f.len = duration;
14872 ast_queue_frame(p->owner, &f);
14873 if (sipdebug)
14874 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
14876 transmit_response(p, "200 OK", req);
14877 return;
14879 } else if (!strcasecmp(c, "application/media_control+xml")) {
14880 /* Eh, we'll just assume it's a fast picture update for now */
14881 if (p->owner)
14882 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
14883 transmit_response(p, "200 OK", req);
14884 return;
14885 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
14886 /* Client code (from SNOM phone) */
14887 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
14888 if (p->owner && p->owner->cdr)
14889 ast_cdr_setuserfield(p->owner, c);
14890 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
14891 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
14892 transmit_response(p, "200 OK", req);
14893 } else {
14894 transmit_response(p, "403 Forbidden", req);
14896 return;
14897 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
14898 /* INFO messages generated by some phones to start/stop recording
14899 on phone calls.
14900 OEJ: I think this should be something that is enabled/disabled
14901 per device. I don't want incoming callers to record calls in my
14902 pbx.
14904 /* first, get the feature string, if it exists */
14905 struct ast_call_feature *feat;
14906 int j;
14907 struct ast_frame f = { AST_FRAME_DTMF, };
14909 ast_rdlock_call_features();
14910 feat = ast_find_call_feature("automon");
14911 if (!feat || ast_strlen_zero(feat->exten)) {
14912 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
14913 /* 403 means that we don't support this feature, so don't request it again */
14914 transmit_response(p, "403 Forbidden", req);
14915 ast_unlock_call_features();
14916 return;
14918 /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
14919 f.len = 100;
14920 for (j=0; j < strlen(feat->exten); j++) {
14921 f.subclass = feat->exten[j];
14922 ast_queue_frame(p->owner, &f);
14923 if (sipdebug)
14924 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
14926 ast_unlock_call_features();
14928 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
14929 transmit_response(p, "200 OK", req);
14930 return;
14931 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
14932 /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
14933 transmit_response(p, "200 OK", req);
14934 return;
14937 /* Other type of INFO message, not really understood by Asterisk */
14938 /* if (get_msg_text(buf, sizeof(buf), req)) { */
14940 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
14941 transmit_response(p, "415 Unsupported media type", req);
14942 return;
14945 /*! \brief Enable SIP Debugging for a single IP */
14946 static char *sip_do_debug_ip(int fd, char *arg)
14948 struct hostent *hp;
14949 struct ast_hostent ahp;
14950 int port = 0;
14951 char *p;
14953 p = arg;
14954 strsep(&p, ":");
14955 if (p)
14956 port = atoi(p);
14957 hp = ast_gethostbyname(arg, &ahp);
14958 if (hp == NULL)
14959 return CLI_SHOWUSAGE;
14961 debugaddr.sin_family = AF_INET;
14962 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
14963 debugaddr.sin_port = htons(port);
14964 if (port == 0)
14965 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
14966 else
14967 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
14969 sipdebug |= sip_debug_console;
14971 return CLI_SUCCESS;
14974 /*! \brief Turn on SIP debugging for a given peer */
14975 static char *sip_do_debug_peer(int fd, char *arg)
14977 struct sip_peer *peer = find_peer(arg, NULL, 1);
14978 if (!peer)
14979 ast_cli(fd, "No such peer '%s'\n", arg);
14980 else if (peer->addr.sin_addr.s_addr == 0)
14981 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
14982 else {
14983 debugaddr.sin_family = AF_INET;
14984 debugaddr.sin_addr = peer->addr.sin_addr;
14985 debugaddr.sin_port = peer->addr.sin_port;
14986 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
14987 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
14988 sipdebug |= sip_debug_console;
14990 if (peer)
14991 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
14992 return CLI_SUCCESS;
14995 /*! \brief Turn on SIP debugging (CLI command) */
14996 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14998 int oldsipdebug = sipdebug & sip_debug_console;
14999 char *what;
15001 if (cmd == CLI_INIT) {
15002 e->command = "sip set debug {on|off|ip|peer}";
15003 e->usage =
15004 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
15005 " Globally disables dumping of SIP packets,\n"
15006 " or enables it either globally or for a (single)\n"
15007 " IP address or registered peer.\n";
15008 return NULL;
15009 } else if (cmd == CLI_GENERATE) {
15010 if (a->pos == 4 && strcasestr(a->line, " peer")) /* XXX should check on argv too */
15011 return complete_sip_peer(a->word, a->n, 0);
15012 return NULL;
15015 what = a->argv[e->args-1]; /* guaranteed to exist */
15016 if (a->argc == e->args) { /* on/off */
15017 if (!strcasecmp(what, "on")) {
15018 sipdebug |= sip_debug_console;
15019 sipdebug_text = 1; /*! \note this can be a special debug command - "sip debug text" or something */
15020 memset(&debugaddr, 0, sizeof(debugaddr));
15021 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
15022 return CLI_SUCCESS;
15023 } else if (!strcasecmp(what, "off")) {
15024 sipdebug &= ~sip_debug_console;
15025 sipdebug_text = 0;
15026 ast_cli(a->fd, "SIP Debugging Disabled\n");
15027 return CLI_SUCCESS;
15029 } else if (a->argc == e->args +1) {/* ip/peer */
15030 if (!strcasecmp(what, "ip"))
15031 return sip_do_debug_ip(a->fd, a->argv[e->args]);
15032 else if (!strcasecmp(what, "peer"))
15033 return sip_do_debug_peer(a->fd, a->argv[e->args]);
15035 return CLI_SHOWUSAGE; /* default, failure */
15038 /*! \brief Cli command to send SIP notify to peer */
15039 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15041 struct ast_variable *varlist;
15042 int i;
15044 switch (cmd) {
15045 case CLI_INIT:
15046 e->command = "sip notify";
15047 e->usage =
15048 "Usage: sip notify <type> <peer> [<peer>...]\n"
15049 " Send a NOTIFY message to a SIP peer or peers\n"
15050 " Message types are defined in sip_notify.conf\n";
15051 return NULL;
15052 case CLI_GENERATE:
15053 return complete_sipnotify(a->line, a->word, a->pos, a->n);
15056 if (a->argc < 4)
15057 return CLI_SHOWUSAGE;
15059 if (!notify_types) {
15060 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
15061 return CLI_FAILURE;
15064 varlist = ast_variable_browse(notify_types, a->argv[2]);
15066 if (!varlist) {
15067 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
15068 return CLI_FAILURE;
15071 for (i = 3; i < a->argc; i++) {
15072 struct sip_pvt *p;
15074 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
15075 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
15076 return CLI_FAILURE;
15079 if (create_addr(p, a->argv[i], NULL)) {
15080 /* Maybe they're not registered, etc. */
15081 dialog_unlink_all(p, TRUE, TRUE);
15082 dialog_unref(p, "unref dialog inside for loop" );
15083 /* sip_destroy(p); */
15084 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
15085 continue;
15088 /* Notify is outgoing call */
15089 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15091 /* Recalculate our side, and recalculate Call ID */
15092 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
15093 build_via(p);
15094 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
15095 build_callid_pvt(p);
15096 ao2_t_link(dialogs, p, "Linking in new name");
15097 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
15098 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
15099 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
15100 transmit_notify_custom(p, varlist);
15103 return CLI_SUCCESS;
15106 /*! \brief Enable/Disable SIP History logging (CLI) - deprecated. use sip_set_history instead */
15107 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15109 switch (cmd) {
15110 case CLI_INIT:
15111 e->command = "sip history [off]";
15112 e->usage =
15113 "Usage: sip history [off]\n"
15114 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
15115 " Use 'sip show history' to view the history of a call number.\n";
15116 return NULL;
15117 case CLI_GENERATE:
15118 return NULL;
15121 if (a->argc < 2 || a->argc > 3) {
15122 return CLI_SHOWUSAGE;
15124 if (a->argc == 2) {
15125 recordhistory = TRUE;
15126 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
15127 } else {
15128 if (strncasecmp(a->argv[2], "off", 3))
15129 return CLI_SHOWUSAGE;
15130 recordhistory = FALSE;
15131 ast_cli(a->fd, "SIP History Recording Disabled\n");
15133 return CLI_SUCCESS;
15136 /*! \brief Enable/Disable SIP History logging (CLI) */
15137 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15139 switch (cmd) {
15140 case CLI_INIT:
15141 e->command = "sip set history {on|off}";
15142 e->usage =
15143 "Usage: sip history {on|off}\n"
15144 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
15145 " Use 'sip show history' to view the history of a call number.\n";
15146 return NULL;
15147 case CLI_GENERATE:
15148 return NULL;
15151 if (a->argc != e->args)
15152 return CLI_SHOWUSAGE;
15154 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
15155 recordhistory = TRUE;
15156 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
15157 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
15158 recordhistory = FALSE;
15159 ast_cli(a->fd, "SIP History Recording Disabled\n");
15160 } else {
15161 return CLI_SHOWUSAGE;
15163 return CLI_SUCCESS;
15166 /*! \brief Authenticate for outbound registration */
15167 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
15169 char *header, *respheader;
15170 char digest[1024];
15172 p->authtries++;
15173 auth_headers(code, &header, &respheader);
15174 memset(digest, 0, sizeof(digest));
15175 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
15176 /* There's nothing to use for authentication */
15177 /* No digest challenge in request */
15178 if (sip_debug_test_pvt(p) && p->registry)
15179 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
15180 /* No old challenge */
15181 return -1;
15183 if (p->do_history)
15184 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
15185 if (sip_debug_test_pvt(p) && p->registry)
15186 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
15187 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
15190 /*! \brief Add authentication on outbound SIP packet */
15191 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
15193 char *header, *respheader;
15194 char digest[1024];
15196 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
15197 return -2;
15199 p->authtries++;
15200 auth_headers(code, &header, &respheader);
15201 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
15202 memset(digest, 0, sizeof(digest));
15203 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
15204 /* No way to authenticate */
15205 return -1;
15207 /* Now we have a reply digest */
15208 p->options->auth = digest;
15209 p->options->authheader = respheader;
15210 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
15213 /*! \brief reply to authentication for outbound registrations
15214 \return Returns -1 if we have no auth
15215 \note This is used for register= servers in sip.conf, SIP proxies we register
15216 with for receiving calls from. */
15217 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
15219 char tmp[512];
15220 char *c;
15221 char oldnonce[256];
15223 /* table of recognised keywords, and places where they should be copied */
15224 const struct x {
15225 const char *key;
15226 const ast_string_field *field;
15227 } *i, keys[] = {
15228 { "realm=", &p->realm },
15229 { "nonce=", &p->nonce },
15230 { "opaque=", &p->opaque },
15231 { "qop=", &p->qop },
15232 { "domain=", &p->domain },
15233 { NULL, 0 },
15236 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
15237 if (ast_strlen_zero(tmp))
15238 return -1;
15239 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
15240 ast_log(LOG_WARNING, "missing Digest.\n");
15241 return -1;
15243 c = tmp + strlen("Digest ");
15244 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
15245 while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
15246 for (i = keys; i->key != NULL; i++) {
15247 char *src, *separator;
15248 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
15249 continue;
15250 /* Found. Skip keyword, take text in quotes or up to the separator. */
15251 c += strlen(i->key);
15252 if (*c == '"') {
15253 src = ++c;
15254 separator = "\"";
15255 } else {
15256 src = c;
15257 separator = ",";
15259 strsep(&c, separator); /* clear separator and move ptr */
15260 ast_string_field_ptr_set(p, i->field, src);
15261 break;
15263 if (i->key == NULL) /* not found, try ',' */
15264 strsep(&c, ",");
15266 /* Reset nonce count */
15267 if (strcmp(p->nonce, oldnonce))
15268 p->noncecount = 0;
15270 /* Save auth data for following registrations */
15271 if (p->registry) {
15272 struct sip_registry *r = p->registry;
15274 if (strcmp(r->nonce, p->nonce)) {
15275 ast_string_field_set(r, realm, p->realm);
15276 ast_string_field_set(r, nonce, p->nonce);
15277 ast_string_field_set(r, domain, p->domain);
15278 ast_string_field_set(r, opaque, p->opaque);
15279 ast_string_field_set(r, qop, p->qop);
15280 r->noncecount = 0;
15283 return build_reply_digest(p, sipmethod, digest, digest_len);
15286 /*! \brief Build reply digest
15287 \return Returns -1 if we have no auth
15288 \note Build digest challenge for authentication of peers (for registration)
15289 and users (for calls). Also used for authentication of CANCEL and BYE
15291 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
15293 char a1[256];
15294 char a2[256];
15295 char a1_hash[256];
15296 char a2_hash[256];
15297 char resp[256];
15298 char resp_hash[256];
15299 char uri[256];
15300 char opaque[256] = "";
15301 char cnonce[80];
15302 const char *username;
15303 const char *secret;
15304 const char *md5secret;
15305 struct sip_auth *auth = NULL; /* Realm authentication */
15307 if (!ast_strlen_zero(p->domain))
15308 ast_copy_string(uri, p->domain, sizeof(uri));
15309 else if (!ast_strlen_zero(p->uri))
15310 ast_copy_string(uri, p->uri, sizeof(uri));
15311 else
15312 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
15314 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
15316 /* Check if we have separate auth credentials */
15317 if ((auth = find_realm_authentication(authl, p->realm))) {
15318 ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
15319 auth->username, p->peername, p->username);
15320 username = auth->username;
15321 secret = auth->secret;
15322 md5secret = auth->md5secret;
15323 if (sipdebug)
15324 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
15325 } else {
15326 /* No authentication, use peer or register= config */
15327 username = p->authname;
15328 secret = p->peersecret;
15329 md5secret = p->peermd5secret;
15331 if (ast_strlen_zero(username)) /* We have no authentication */
15332 return -1;
15334 /* Calculate SIP digest response */
15335 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
15336 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
15337 if (!ast_strlen_zero(md5secret))
15338 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
15339 else
15340 ast_md5_hash(a1_hash, a1);
15341 ast_md5_hash(a2_hash, a2);
15343 p->noncecount++;
15344 if (!ast_strlen_zero(p->qop))
15345 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
15346 else
15347 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
15348 ast_md5_hash(resp_hash, resp);
15350 /* only include the opaque string if it's set */
15351 if (!ast_strlen_zero(p->opaque)) {
15352 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
15355 /* XXX We hard code our qop to "auth" for now. XXX */
15356 if (!ast_strlen_zero(p->qop))
15357 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);
15358 else
15359 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);
15361 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
15363 return 0;
15366 /*! \brief Read SIP header (dialplan function) */
15367 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
15369 struct sip_pvt *p;
15370 const char *content = NULL;
15371 AST_DECLARE_APP_ARGS(args,
15372 AST_APP_ARG(header);
15373 AST_APP_ARG(number);
15375 int i, number, start = 0;
15377 if (ast_strlen_zero(data)) {
15378 ast_log(LOG_WARNING, "This function requires a header name.\n");
15379 return -1;
15382 ast_channel_lock(chan);
15383 if (!IS_SIP_TECH(chan->tech)) {
15384 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
15385 ast_channel_unlock(chan);
15386 return -1;
15389 AST_STANDARD_APP_ARGS(args, data);
15390 if (!args.number) {
15391 number = 1;
15392 } else {
15393 sscanf(args.number, "%d", &number);
15394 if (number < 1)
15395 number = 1;
15398 p = chan->tech_pvt;
15400 /* If there is no private structure, this channel is no longer alive */
15401 if (!p) {
15402 ast_channel_unlock(chan);
15403 return -1;
15406 for (i = 0; i < number; i++)
15407 content = __get_header(&p->initreq, args.header, &start);
15409 if (ast_strlen_zero(content)) {
15410 ast_channel_unlock(chan);
15411 return -1;
15414 ast_copy_string(buf, content, len);
15415 ast_channel_unlock(chan);
15417 return 0;
15420 static struct ast_custom_function sip_header_function = {
15421 .name = "SIP_HEADER",
15422 .synopsis = "Gets the specified SIP header",
15423 .syntax = "SIP_HEADER(<name>[,<number>])",
15424 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
15425 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
15426 "that name to retrieve. Headers start at offset 1.\n",
15427 .read = func_header_read,
15430 /*! \brief Dial plan function to check if domain is local */
15431 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15433 if (ast_strlen_zero(data)) {
15434 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
15435 return -1;
15437 if (check_sip_domain(data, NULL, 0))
15438 ast_copy_string(buf, data, len);
15439 else
15440 buf[0] = '\0';
15441 return 0;
15444 static struct ast_custom_function checksipdomain_function = {
15445 .name = "CHECKSIPDOMAIN",
15446 .synopsis = "Checks if domain is a local domain",
15447 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
15448 .read = func_check_sipdomain,
15449 .desc = "This function checks if the domain in the argument is configured\n"
15450 "as a local SIP domain that this Asterisk server is configured to handle.\n"
15451 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
15452 "Check the domain= configuration in sip.conf\n",
15455 /*! \brief ${SIPPEER()} Dialplan function - reads peer data */
15456 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15458 struct sip_peer *peer;
15459 char *colname;
15461 if ((colname = strchr(data, ':'))) { /*! \todo Will be deprecated after 1.4 */
15462 static int deprecation_warning = 0;
15463 *colname++ = '\0';
15464 if (deprecation_warning++ % 10 == 0)
15465 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
15466 } else if ((colname = strchr(data, ',')))
15467 *colname++ = '\0';
15468 else
15469 colname = "ip";
15471 if (!(peer = find_peer(data, NULL, 1)))
15472 return -1;
15474 if (!strcasecmp(colname, "ip")) {
15475 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
15476 } else if (!strcasecmp(colname, "port")) {
15477 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
15478 } else if (!strcasecmp(colname, "status")) {
15479 peer_status(peer, buf, len);
15480 } else if (!strcasecmp(colname, "language")) {
15481 ast_copy_string(buf, peer->language, len);
15482 } else if (!strcasecmp(colname, "regexten")) {
15483 ast_copy_string(buf, peer->regexten, len);
15484 } else if (!strcasecmp(colname, "limit")) {
15485 snprintf(buf, len, "%d", peer->call_limit);
15486 } else if (!strcasecmp(colname, "busylevel")) {
15487 snprintf(buf, len, "%d", peer->busy_level);
15488 } else if (!strcasecmp(colname, "curcalls")) {
15489 snprintf(buf, len, "%d", peer->inUse);
15490 } else if (!strcasecmp(colname, "accountcode")) {
15491 ast_copy_string(buf, peer->accountcode, len);
15492 } else if (!strcasecmp(colname, "callgroup")) {
15493 ast_print_group(buf, len, peer->callgroup);
15494 } else if (!strcasecmp(colname, "pickupgroup")) {
15495 ast_print_group(buf, len, peer->pickupgroup);
15496 } else if (!strcasecmp(colname, "useragent")) {
15497 ast_copy_string(buf, peer->useragent, len);
15498 } else if (!strcasecmp(colname, "mailbox")) {
15499 struct ast_str *mailbox_str = ast_str_alloca(512);
15500 peer_mailboxes_to_str(&mailbox_str, peer);
15501 ast_copy_string(buf, mailbox_str->str, len);
15502 } else if (!strcasecmp(colname, "context")) {
15503 ast_copy_string(buf, peer->context, len);
15504 } else if (!strcasecmp(colname, "expire")) {
15505 snprintf(buf, len, "%d", peer->expire);
15506 } else if (!strcasecmp(colname, "dynamic")) {
15507 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
15508 } else if (!strcasecmp(colname, "callerid_name")) {
15509 ast_copy_string(buf, peer->cid_name, len);
15510 } else if (!strcasecmp(colname, "callerid_num")) {
15511 ast_copy_string(buf, peer->cid_num, len);
15512 } else if (!strcasecmp(colname, "codecs")) {
15513 ast_getformatname_multiple(buf, len -1, peer->capability);
15514 } else if (!strncasecmp(colname, "chanvar[", 8)) {
15515 char *chanvar=colname + 8;
15516 struct ast_variable *v;
15518 chanvar = strsep(&chanvar, "]");
15519 for (v = peer->chanvars ; v ; v = v->next)
15520 if (strcasecmp(v->name, chanvar) == 0)
15521 ast_copy_string(buf, v->value, sizeof(buf));
15522 } else if (!strncasecmp(colname, "codec[", 6)) {
15523 char *codecnum;
15524 int index = 0, codec = 0;
15526 codecnum = colname + 6; /* move past the '[' */
15527 codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
15528 index = atoi(codecnum);
15529 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
15530 ast_copy_string(buf, ast_getformatname(codec), len);
15534 unref_peer(peer, "unref_peer from function_sippeer, just before return");
15536 return 0;
15539 /*! \brief Structure to declare a dialplan function: SIPPEER */
15540 struct ast_custom_function sippeer_function = {
15541 .name = "SIPPEER",
15542 .synopsis = "Gets SIP peer information",
15543 .syntax = "SIPPEER(<peername>[,item])",
15544 .read = function_sippeer,
15545 .desc = "Valid items are:\n"
15546 "- ip (default) The IP address.\n"
15547 "- port The port number\n"
15548 "- mailbox The configured mailbox.\n"
15549 "- context The configured context.\n"
15550 "- expire The epoch time of the next expire.\n"
15551 "- dynamic Is it dynamic? (yes/no).\n"
15552 "- callerid_name The configured Caller ID name.\n"
15553 "- callerid_num The configured Caller ID number.\n"
15554 "- callgroup The configured Callgroup.\n"
15555 "- pickupgroup The configured Pickupgroup.\n"
15556 "- codecs The configured codecs.\n"
15557 "- status Status (if qualify=yes).\n"
15558 "- regexten Registration extension\n"
15559 "- limit Call limit (call-limit)\n"
15560 "- busylevel Configured call level for signalling busy\n"
15561 "- curcalls Current amount of calls \n"
15562 " Only available if call-limit is set\n"
15563 "- language Default language for peer\n"
15564 "- accountcode Account code for this peer\n"
15565 "- useragent Current user agent id for peer\n"
15566 "- chanvar[name] A channel variable configured with setvar for this peer.\n"
15567 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
15568 "\n"
15571 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
15572 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15574 struct sip_pvt *p;
15575 static int deprecated = 0;
15577 *buf = 0;
15579 if (!data) {
15580 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
15581 return -1;
15584 ast_channel_lock(chan);
15585 if (!IS_SIP_TECH(chan->tech)) {
15586 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
15587 ast_channel_unlock(chan);
15588 return -1;
15591 if (deprecated++ % 20 == 0) {
15592 /* Deprecated in 1.6.1 */
15593 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
15596 p = chan->tech_pvt;
15598 /* If there is no private structure, this channel is no longer alive */
15599 if (!p) {
15600 ast_channel_unlock(chan);
15601 return -1;
15604 if (!strcasecmp(data, "peerip")) {
15605 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
15606 } else if (!strcasecmp(data, "recvip")) {
15607 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
15608 } else if (!strcasecmp(data, "from")) {
15609 ast_copy_string(buf, p->from, len);
15610 } else if (!strcasecmp(data, "uri")) {
15611 ast_copy_string(buf, p->uri, len);
15612 } else if (!strcasecmp(data, "useragent")) {
15613 ast_copy_string(buf, p->useragent, len);
15614 } else if (!strcasecmp(data, "peername")) {
15615 ast_copy_string(buf, p->peername, len);
15616 } else if (!strcasecmp(data, "t38passthrough")) {
15617 if (p->t38.state == T38_DISABLED)
15618 ast_copy_string(buf, "0", sizeof("0"));
15619 else /* T38 is offered or enabled in this call */
15620 ast_copy_string(buf, "1", sizeof("1"));
15621 } else {
15622 ast_channel_unlock(chan);
15623 return -1;
15625 ast_channel_unlock(chan);
15627 return 0;
15630 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
15631 static struct ast_custom_function sipchaninfo_function = {
15632 .name = "SIPCHANINFO",
15633 .synopsis = "Gets the specified SIP parameter from the current channel",
15634 .syntax = "SIPCHANINFO(item)",
15635 .read = function_sipchaninfo_read,
15636 .desc = "Valid items are:\n"
15637 "- peerip The IP address of the peer.\n"
15638 "- recvip The source IP address of the peer.\n"
15639 "- from The URI from the From: header.\n"
15640 "- uri The URI from the Contact: header.\n"
15641 "- useragent The useragent.\n"
15642 "- peername The name of the peer.\n"
15643 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
15646 /*! \brief Parse 302 Moved temporalily response */
15647 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
15649 char tmp[SIPBUFSIZE];
15650 char *s, *e, *t;
15651 char *domain;
15653 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
15654 if ((t = strchr(tmp, ',')))
15655 *t = '\0';
15656 s = remove_uri_parameters(get_in_brackets(tmp));
15657 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
15658 if (!strncasecmp(s, "sip:", 4))
15659 s += 4;
15660 else if (!strncasecmp(s, "sips:", 5))
15661 s += 5;
15662 e = strchr(s, '/');
15663 if (e)
15664 *e = '\0';
15665 ast_debug(2, "Found promiscuous redirection to 'SIP/%s'\n", s);
15666 if (p->owner)
15667 ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
15668 } else {
15669 e = strchr(tmp, '@');
15670 if (e) {
15671 *e++ = '\0';
15672 domain = e;
15673 } else {
15674 /* No username part */
15675 domain = tmp;
15677 e = strchr(tmp, '/'); /* WHEN do we hae a forward slash in the URI? */
15678 if (e)
15679 *e = '\0';
15681 if (!strncasecmp(s, "sip:", 4))
15682 s += 4;
15683 else if (!strncasecmp(s, "sips:", 5))
15684 s += 5;
15685 e = strchr(s, ';'); /* And username ; parameters? */
15686 if (e)
15687 *e = '\0';
15688 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
15689 if (p->owner) {
15690 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
15691 ast_string_field_set(p->owner, call_forward, s);
15696 /*! \brief Check pending actions on SIP call */
15697 static void check_pendings(struct sip_pvt *p)
15699 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
15700 /* if we can't BYE, then this is really a pending CANCEL */
15701 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
15702 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
15703 /* Actually don't destroy us yet, wait for the 487 on our original
15704 INVITE, but do set an autodestruct just in case we never get it. */
15705 else {
15706 /* We have a pending outbound invite, don't send someting
15707 new in-transaction */
15708 if (p->pendinginvite)
15709 return;
15711 /* Perhaps there is an SD change INVITE outstanding */
15712 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
15714 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
15715 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15716 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
15717 /* if we can't REINVITE, hold it for later */
15718 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
15719 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
15720 } else {
15721 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
15722 /* Didn't get to reinvite yet, so do it now */
15723 transmit_reinvite_with_sdp(p, FALSE, FALSE);
15724 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
15729 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
15730 to avoid race conditions between asterisk servers.
15731 Called from the scheduler.
15733 static int sip_reinvite_retry(const void *data)
15735 struct sip_pvt *p = (struct sip_pvt *) data;
15737 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
15738 p->waitid = -1;
15739 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
15740 return 0;
15744 /*! \brief Handle SIP response to INVITE dialogue */
15745 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
15747 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
15748 int res = 0;
15749 int xmitres = 0;
15750 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
15751 struct ast_channel *bridgepeer = NULL;
15752 char *p_hdrval;
15753 int rtn;
15755 if (reinvite)
15756 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
15757 else
15758 ast_debug(4, "SIP response %d to standard invite\n", resp);
15760 if (p->alreadygone) { /* This call is already gone */
15761 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
15762 return;
15765 /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
15766 /* Don't auto congest anymore since we've gotten something useful back */
15767 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"));
15769 /* RFC3261 says we must treat every 1xx response (but not 100)
15770 that we don't recognize as if it was 183.
15772 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
15773 resp = 183;
15775 /* Any response between 100 and 199 is PROCEEDING */
15776 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
15777 p->invitestate = INV_PROCEEDING;
15779 /* Final response, not 200 ? */
15780 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
15781 p->invitestate = INV_COMPLETED;
15784 switch (resp) {
15785 case 100: /* Trying */
15786 case 101: /* Dialog establishment */
15787 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
15788 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15789 check_pendings(p);
15790 break;
15792 case 180: /* 180 Ringing */
15793 case 182: /* 182 Queued */
15794 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
15795 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15796 if (!req->ignore && p->owner) {
15797 ast_queue_control(p->owner, AST_CONTROL_RINGING);
15798 if (p->owner->_state != AST_STATE_UP) {
15799 ast_setstate(p->owner, AST_STATE_RINGING);
15802 if (find_sdp(req)) {
15803 if (p->invitestate != INV_CANCELLED)
15804 p->invitestate = INV_EARLY_MEDIA;
15805 res = process_sdp(p, req, SDP_T38_NONE);
15806 if (!req->ignore && p->owner) {
15807 /* Queue a progress frame only if we have SDP in 180 or 182 */
15808 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
15811 check_pendings(p);
15812 break;
15814 case 183: /* Session progress */
15815 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
15816 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15817 /* Ignore 183 Session progress without SDP */
15818 if (find_sdp(req)) {
15819 if (p->invitestate != INV_CANCELLED)
15820 p->invitestate = INV_EARLY_MEDIA;
15821 res = process_sdp(p, req, SDP_T38_NONE);
15822 if (!req->ignore && p->owner) {
15823 /* Queue a progress frame */
15824 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
15827 check_pendings(p);
15828 break;
15830 case 200: /* 200 OK on invite - someone's answering our call */
15831 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
15832 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15833 p->authtries = 0;
15834 if (find_sdp(req)) {
15835 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
15836 if (!reinvite)
15837 /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
15838 /* For re-invites, we try to recover */
15839 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15842 /* Parse contact header for continued conversation */
15843 /* When we get 200 OK, we know which device (and IP) to contact for this call */
15844 /* This is important when we have a SIP proxy between us and the phone */
15845 if (outgoing) {
15846 update_call_counter(p, DEC_CALL_RINGING);
15847 parse_ok_contact(p, req);
15848 if(set_address_from_contact(p)) {
15849 /* Bad contact - we don't know how to reach this device */
15850 /* We need to ACK, but then send a bye */
15851 /* OEJ: Possible issue that may need a check:
15852 If we have a proxy route between us and the device,
15853 should we care about resolving the contact
15854 or should we just send it?
15856 if (!req->ignore)
15857 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15860 /* Save Record-Route for any later requests we make on this dialogue */
15861 if (!reinvite)
15862 build_route(p, req, 1);
15865 if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
15866 struct sip_pvt *bridgepvt = NULL;
15868 if (!bridgepeer->tech) {
15869 ast_log(LOG_WARNING, "Ooooh.. no tech! That's REALLY bad\n");
15870 break;
15872 if (IS_SIP_TECH(bridgepeer->tech)) {
15873 bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
15874 if (bridgepvt->udptl) {
15875 if (p->t38.state == T38_ENABLED && bridgepvt->t38.state == T38_PEER_REINVITE) {
15876 sip_handle_t38_reinvite(bridgepeer, p, 0);
15877 ast_rtp_set_rtptimers_onhold(p->rtp);
15878 if (p->vrtp)
15879 ast_rtp_set_rtptimers_onhold(p->vrtp); /* Turn off RTP timers while we send fax */
15880 } else if (p->t38.state == T38_DISABLED && bridgepvt->t38.state == T38_ENABLED) {
15881 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
15882 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
15883 /* XXXX Should we really destroy this session here, without any response at all??? */
15884 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15886 } else {
15887 ast_debug(2, "Strange... The other side of the bridge does not have a udptl struct\n");
15888 sip_pvt_lock(bridgepvt);
15889 change_t38_state(bridgepvt, T38_DISABLED);
15890 sip_pvt_unlock(bridgepvt);
15891 change_t38_state(p, T38_DISABLED);
15893 } else {
15894 /* Other side is not a SIP channel */
15895 ast_debug(2, "Strange... The other side of the bridge is not a SIP channel\n");
15896 change_t38_state(p, T38_DISABLED);
15900 if (!req->ignore && p->owner) {
15901 if (!reinvite) {
15902 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
15903 if (global_callevents)
15904 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
15905 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
15906 p->owner->name, p->owner->uniqueid, "SIP", p->callid, p->fullcontact, p->peername);
15907 } else { /* RE-invite */
15908 ast_queue_frame(p->owner, &ast_null_frame);
15910 } else {
15911 /* It's possible we're getting an 200 OK after we've tried to disconnect
15912 by sending CANCEL */
15913 /* First send ACK, then send bye */
15914 if (!req->ignore)
15915 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15918 /* Check for Session-Timers related headers */
15919 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
15920 p_hdrval = (char*)get_header(req, "Session-Expires");
15921 if (!ast_strlen_zero(p_hdrval)) {
15922 /* UAS supports Session-Timers */
15923 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
15924 int tmp_st_interval = 0;
15925 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
15926 if (rtn != 0) {
15927 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15929 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
15930 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
15931 p->stimer->st_ref = tmp_st_ref;
15933 if (tmp_st_interval) {
15934 p->stimer->st_interval = tmp_st_interval;
15936 p->stimer->st_active = TRUE;
15937 p->stimer->st_active_peer_ua = TRUE;
15938 start_session_timer(p);
15939 } else {
15940 /* UAS doesn't support Session-Timers */
15941 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
15942 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
15943 p->stimer->st_active_peer_ua = FALSE;
15944 start_session_timer(p);
15950 /* If I understand this right, the branch is different for a non-200 ACK only */
15951 p->invitestate = INV_TERMINATED;
15952 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
15953 check_pendings(p);
15954 break;
15956 case 407: /* Proxy authentication */
15957 case 401: /* Www auth */
15958 /* First we ACK */
15959 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15960 if (p->options)
15961 p->options->auth_type = resp;
15963 /* Then we AUTH */
15964 ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
15965 if (!req->ignore) {
15966 if (p->authtries < MAX_AUTHTRIES)
15967 p->invitestate = INV_CALLING;
15968 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
15969 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
15970 p->needdestroy = 1;
15971 sip_alreadygone(p);
15972 if (p->owner)
15973 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15976 break;
15978 case 403: /* Forbidden */
15979 /* First we ACK */
15980 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15981 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
15982 if (!req->ignore && p->owner)
15983 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15984 p->needdestroy = 1;
15985 sip_alreadygone(p);
15986 break;
15988 case 404: /* Not found */
15989 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
15990 if (p->owner && !req->ignore)
15991 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
15992 sip_alreadygone(p);
15993 break;
15995 case 408: /* Request timeout */
15996 case 481: /* Call leg does not exist */
15997 /* Could be REFER caused INVITE with replaces */
15998 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
15999 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16000 if (p->owner)
16001 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16002 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16003 break;
16005 case 422: /* Session-Timers: Session interval too small */
16006 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16007 ast_string_field_set(p, theirtag, NULL);
16008 proc_422_rsp(p, req);
16009 break;
16011 case 487: /* Cancelled transaction */
16012 /* We have sent CANCEL on an outbound INVITE
16013 This transaction is already scheduled to be killed by sip_hangup().
16015 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16016 if (p->owner && !req->ignore) {
16017 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
16018 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
16019 } else if (!req->ignore) {
16020 update_call_counter(p, DEC_CALL_LIMIT);
16021 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
16022 p->needdestroy = 1;
16023 sip_alreadygone(p);
16025 break;
16026 case 488: /* Not acceptable here */
16027 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16028 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
16029 change_t38_state(p, T38_DISABLED);
16030 /* Try to reset RTP timers */
16031 ast_rtp_set_rtptimers_onhold(p->rtp);
16033 /* Trigger a reinvite back to audio */
16034 transmit_reinvite_with_sdp(p, FALSE, FALSE);
16035 } else if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
16036 /* We tried to send T.38 out in an initial INVITE and the remote side rejected it,
16037 right now we can't fall back to audio so totally abort.
16039 /* Try to reset RTP timers */
16040 ast_rtp_set_rtptimers_onhold(p->rtp);
16041 ast_log(LOG_ERROR, "Got error on T.38 initial invite. Bailing out.\n");
16043 change_t38_state(p, T38_DISABLED);
16044 /* The dialog is now terminated */
16045 if (p->owner && !req->ignore)
16046 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16047 p->needdestroy = 1;
16048 sip_alreadygone(p);
16049 } else {
16050 /* We can't set up this call, so give up */
16051 if (p->owner && !req->ignore)
16052 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16053 p->needdestroy = 1;
16054 /* If there's no dialog to end, then mark p as already gone */
16055 if (!reinvite)
16056 sip_alreadygone(p);
16058 break;
16059 case 491: /* Pending */
16060 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16061 if (p->owner && !req->ignore) {
16062 if (p->owner->_state != AST_STATE_UP) {
16063 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16064 p->needdestroy = 1;
16065 } else {
16066 /* This is a re-invite that failed. */
16067 /* Reset the flag after a while
16069 int wait = 3 + ast_random() % 5;
16070 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."));
16071 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);
16072 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
16075 break;
16077 case 501: /* Not implemented */
16078 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16079 if (p->owner)
16080 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16081 break;
16083 if (xmitres == XMIT_ERROR)
16084 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
16087 /* \brief Handle SIP response in NOTIFY transaction
16088 We've sent a NOTIFY, now handle responses to it
16090 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16092 switch (resp) {
16093 case 200: /* Notify accepted */
16094 /* They got the notify, this is the end */
16095 if (p->owner) {
16096 if (!p->refer) {
16097 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
16098 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
16099 } else {
16100 ast_debug(4, "Got OK on REFER Notify message\n");
16102 } else {
16103 if (p->subscribed == NONE) {
16104 ast_debug(4, "Got 200 accepted on NOTIFY\n");
16105 p->needdestroy = 1;
16107 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
16108 /* Ready to send the next state we have on queue */
16109 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16110 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
16113 break;
16114 case 401: /* Not www-authorized on SIP method */
16115 case 407: /* Proxy auth */
16116 if (!p->notify_headers) {
16117 break; /* Only device notify can use NOTIFY auth */
16119 ast_string_field_set(p, theirtag, NULL);
16120 if (ast_strlen_zero(p->authname)) {
16121 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));
16122 p->needdestroy = 1;
16124 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
16125 ast_log(LOG_NOTICE, "Failed to authenticate on NOTYFY to '%s'\n", get_header(&p->initreq, "From"));
16126 p->needdestroy = 1;
16128 break;
16132 /* \brief Handle SIP response in REFER transaction
16133 We've sent a REFER, now handle responses to it
16135 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16137 /* If no refer structure exists, then do nothing */
16138 if (!p->refer)
16139 return;
16141 switch (resp) {
16142 case 202: /* Transfer accepted */
16143 /* We need to do something here */
16144 /* The transferee is now sending INVITE to target */
16145 p->refer->status = REFER_ACCEPTED;
16146 /* Now wait for next message */
16147 ast_debug(3, "Got 202 accepted on transfer\n");
16148 /* We should hang along, waiting for NOTIFY's here */
16149 break;
16151 case 401: /* Not www-authorized on SIP method */
16152 case 407: /* Proxy auth */
16153 if (ast_strlen_zero(p->authname)) {
16154 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
16155 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16156 p->needdestroy = 1;
16158 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
16159 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
16160 p->refer->status = REFER_NOAUTH;
16161 p->needdestroy = 1;
16163 break;
16164 case 481: /* Call leg does not exist */
16166 /* A transfer with Replaces did not work */
16167 /* OEJ: We should Set flag, cancel the REFER, go back
16168 to original call - but right now we can't */
16169 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
16170 if (p->owner)
16171 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16172 p->needdestroy = 1;
16173 break;
16175 case 500: /* Server error */
16176 case 501: /* Method not implemented */
16177 /* Return to the current call onhold */
16178 /* Status flag needed to be reset */
16179 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
16180 p->needdestroy = 1;
16181 p->refer->status = REFER_FAILED;
16182 break;
16183 case 603: /* Transfer declined */
16184 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
16185 p->refer->status = REFER_FAILED;
16186 p->needdestroy = 1;
16187 break;
16191 /*! \brief Handle responses on REGISTER to services */
16192 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16194 int expires, expires_ms;
16195 struct sip_registry *r;
16196 r=p->registry;
16198 switch (resp) {
16199 case 401: /* Unauthorized */
16200 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
16201 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
16202 p->needdestroy = 1;
16204 break;
16205 case 403: /* Forbidden */
16206 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
16207 AST_SCHED_DEL(sched, r->timeout);
16208 r->regstate = REG_STATE_NOAUTH;
16209 p->needdestroy = 1;
16210 break;
16211 case 404: /* Not found */
16212 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
16213 p->needdestroy = 1;
16214 if (r->call)
16215 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
16216 r->regstate = REG_STATE_REJECTED;
16217 AST_SCHED_DEL(sched, r->timeout);
16218 break;
16219 case 407: /* Proxy auth */
16220 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
16221 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
16222 p->needdestroy = 1;
16224 break;
16225 case 408: /* Request timeout */
16226 p->needdestroy = 1;
16227 if (r->call)
16228 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 408");
16229 AST_SCHED_DEL(sched, r->timeout);
16230 break;
16231 case 423: /* Interval too brief */
16232 r->expiry = atoi(get_header(req, "Min-Expires"));
16233 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);
16234 AST_SCHED_DEL(sched, r->timeout);
16235 r->timeout = -1;
16236 if (r->call) {
16237 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
16238 p->needdestroy = 1;
16240 if (r->expiry > max_expiry) {
16241 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
16242 r->expiry = default_expiry;
16243 r->regstate = REG_STATE_REJECTED;
16244 } else {
16245 r->regstate = REG_STATE_UNREGISTERED;
16246 transmit_register(r, SIP_REGISTER, NULL, NULL);
16248 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));
16249 break;
16250 case 479: /* SER: Not able to process the URI - address is wrong in register*/
16251 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
16252 p->needdestroy = 1;
16253 if (r->call)
16254 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
16255 r->regstate = REG_STATE_REJECTED;
16256 AST_SCHED_DEL(sched, r->timeout);
16257 break;
16258 case 200: /* 200 OK */
16259 if (!r) {
16260 ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
16261 p->needdestroy = 1;
16262 return 0;
16265 r->regstate = REG_STATE_REGISTERED;
16266 r->regtime = ast_tvnow(); /* Reset time of last succesful registration */
16267 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
16268 r->regattempts = 0;
16269 ast_debug(1, "Registration successful\n");
16270 if (r->timeout > -1) {
16271 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
16273 AST_SCHED_DEL(sched, r->timeout);
16274 if (r->call)
16275 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
16276 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
16277 /* Let this one hang around until we have all the responses */
16278 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16279 /* p->needdestroy = 1; */
16281 /* set us up for re-registering */
16282 /* figure out how long we got registered for */
16283 AST_SCHED_DEL(sched, r->expire);
16285 /* according to section 6.13 of RFC, contact headers override
16286 expires headers, so check those first */
16287 expires = 0;
16289 /* XXX todo: try to save the extra call */
16290 if (!ast_strlen_zero(get_header(req, "Contact"))) {
16291 const char *contact = NULL;
16292 const char *tmptmp = NULL;
16293 int start = 0;
16294 for(;;) {
16295 contact = __get_header(req, "Contact", &start);
16296 /* this loop ensures we get a contact header about our register request */
16297 if(!ast_strlen_zero(contact)) {
16298 if( (tmptmp=strstr(contact, p->our_contact))) {
16299 contact=tmptmp;
16300 break;
16302 } else
16303 break;
16305 tmptmp = strcasestr(contact, "expires=");
16306 if (tmptmp) {
16307 if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
16308 expires = 0;
16312 if (!expires)
16313 expires=atoi(get_header(req, "expires"));
16314 if (!expires)
16315 expires=default_expiry;
16317 expires_ms = expires * 1000;
16318 if (expires <= EXPIRY_GUARD_LIMIT)
16319 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
16320 else
16321 expires_ms -= EXPIRY_GUARD_SECS * 1000;
16322 if (sipdebug)
16323 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
16325 r->refresh= (int) expires_ms / 1000;
16327 /* Schedule re-registration before we expire */
16328 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
16329 registry_unref(_data,"unref in REPLACE del fail"),
16330 registry_unref(r,"unref in REPLACE add fail"),
16331 registry_addref(r,"The Addition side of REPLACE"));
16332 /* it is clear that we would not want to destroy the registry entry if we just
16333 scheduled a callback and recorded it in there! */
16334 /* 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! */
16336 return 1;
16339 /*! \brief Handle qualification responses (OPTIONS) */
16340 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
16342 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! */
16343 int statechanged, is_reachable, was_reachable;
16344 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
16347 * Compute the response time to a ping (goes in peer->lastms.)
16348 * -1 means did not respond, 0 means unknown,
16349 * 1..maxms is a valid response, >maxms means late response.
16351 if (pingtime < 1) /* zero = unknown, so round up to 1 */
16352 pingtime = 1;
16354 /* Now determine new state and whether it has changed.
16355 * Use some helper variables to simplify the writing
16356 * of the expressions.
16358 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
16359 is_reachable = pingtime <= peer->maxms;
16360 statechanged = peer->lastms == 0 /* yes, unknown before */
16361 || was_reachable != is_reachable;
16363 peer->lastms = pingtime;
16364 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
16365 if (statechanged) {
16366 const char *s = is_reachable ? "Reachable" : "Lagged";
16368 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
16369 peer->name, s, pingtime, peer->maxms);
16370 ast_device_state_changed("SIP/%s", peer->name);
16371 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
16372 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
16373 peer->name, s, pingtime);
16374 if (is_reachable && global_regextenonqualify)
16375 register_peer_exten(peer, TRUE);
16378 p->needdestroy = 1;
16380 /* Try again eventually */
16381 AST_SCHED_REPLACE(peer->pokeexpire, sched,
16382 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
16383 sip_poke_peer_s, peer);
16384 /* unref_peer(peer, "unref relatedpeer ptr var at end of handle_response_peerpoke"); */
16387 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
16388 static void stop_media_flows(struct sip_pvt *p)
16390 /* Immediately stop RTP, VRTP and UDPTL as applicable */
16391 if (p->rtp)
16392 ast_rtp_stop(p->rtp);
16393 if (p->vrtp)
16394 ast_rtp_stop(p->vrtp);
16395 if (p->trtp)
16396 ast_rtp_stop(p->trtp);
16397 if (p->udptl)
16398 ast_udptl_stop(p->udptl);
16401 /*! \brief Handle SIP response in dialogue */
16402 /* XXX only called by handle_incoming */
16403 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16405 struct ast_channel *owner;
16406 int sipmethod;
16407 int res = 1;
16408 const char *c = get_header(req, "Cseq");
16409 /* 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 */
16410 char *c_copy = ast_strdupa(c);
16411 /* Skip the Cseq and its subsequent spaces */
16412 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
16414 if (!msg)
16415 msg = "";
16417 sipmethod = find_sip_method(msg);
16419 owner = p->owner;
16420 if (owner)
16421 owner->hangupcause = hangup_sip2cause(resp);
16423 /* Acknowledge whatever it is destined for */
16424 if ((resp >= 100) && (resp <= 199))
16425 __sip_semi_ack(p, seqno, 0, sipmethod);
16426 else
16427 __sip_ack(p, seqno, 0, sipmethod);
16429 /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
16430 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
16431 p->pendinginvite = 0;
16433 /* Get their tag if we haven't already */
16434 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
16435 char tag[128];
16437 gettag(req, "To", tag, sizeof(tag));
16438 ast_string_field_set(p, theirtag, tag);
16440 /* This needs to be configurable on a channel/peer/user level,
16441 not mandatory for all communication. Sadly enough, NAT implementations
16442 are not so stable so we can always rely on these headers.
16443 Temporarily disabled, while waiting for fix.
16444 Fix assigned to Rizzo :-)
16446 /* check_via_response(p, req); */
16447 if (p->relatedpeer && p->method == SIP_OPTIONS) {
16448 /* We don't really care what the response is, just that it replied back.
16449 Well, as long as it's not a 100 response... since we might
16450 need to hang around for something more "definitive" */
16451 if (resp != 100)
16452 handle_response_peerpoke(p, resp, req);
16453 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
16454 switch(resp) {
16455 case 100: /* 100 Trying */
16456 case 101: /* 101 Dialog establishment */
16457 if (sipmethod == SIP_INVITE)
16458 handle_response_invite(p, resp, rest, req, seqno);
16459 break;
16460 case 183: /* 183 Session Progress */
16461 if (sipmethod == SIP_INVITE)
16462 handle_response_invite(p, resp, rest, req, seqno);
16463 break;
16464 case 180: /* 180 Ringing */
16465 if (sipmethod == SIP_INVITE)
16466 handle_response_invite(p, resp, rest, req, seqno);
16467 break;
16468 case 182: /* 182 Queued */
16469 if (sipmethod == SIP_INVITE)
16470 handle_response_invite(p, resp, rest, req, seqno);
16471 break;
16472 case 200: /* 200 OK */
16473 p->authtries = 0; /* Reset authentication counter */
16474 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
16475 /* We successfully transmitted a message
16476 or a video update request in INFO */
16477 /* Nothing happens here - the message is inside a dialog */
16478 } else if (sipmethod == SIP_INVITE) {
16479 handle_response_invite(p, resp, rest, req, seqno);
16480 } else if (sipmethod == SIP_NOTIFY) {
16481 handle_response_notify(p, resp, rest, req, seqno);
16482 } else if (sipmethod == SIP_REGISTER)
16483 res = handle_response_register(p, resp, rest, req, seqno);
16484 else if (sipmethod == SIP_BYE) /* Ok, we're ready to go */
16485 p->needdestroy = 1;
16486 break;
16487 case 202: /* Transfer accepted */
16488 if (sipmethod == SIP_REFER)
16489 handle_response_refer(p, resp, rest, req, seqno);
16490 break;
16491 case 401: /* Not www-authorized on SIP method */
16492 case 407: /* Proxy auth required */
16493 if (sipmethod == SIP_INVITE)
16494 handle_response_invite(p, resp, rest, req, seqno);
16495 else if (sipmethod == SIP_NOTIFY)
16496 handle_response_notify(p, resp, rest, req, seqno);
16497 else if (sipmethod == SIP_REFER)
16498 handle_response_refer(p, resp, rest, req, seqno);
16499 else if (p->registry && sipmethod == SIP_REGISTER)
16500 res = handle_response_register(p, resp, rest, req, seqno);
16501 else if (sipmethod == SIP_BYE) {
16502 if (p->options)
16503 p->options->auth_type = resp;
16504 if (ast_strlen_zero(p->authname)) {
16505 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
16506 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16507 p->needdestroy = 1;
16508 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
16509 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
16510 p->needdestroy = 1;
16512 } else {
16513 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
16514 p->needdestroy = 1;
16516 break;
16517 case 403: /* Forbidden - we failed authentication */
16518 if (sipmethod == SIP_INVITE)
16519 handle_response_invite(p, resp, rest, req, seqno);
16520 else if (p->registry && sipmethod == SIP_REGISTER)
16521 res = handle_response_register(p, resp, rest, req, seqno);
16522 else {
16523 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
16524 p->needdestroy = 1;
16526 break;
16527 case 404: /* Not found */
16528 if (p->registry && sipmethod == SIP_REGISTER)
16529 res = handle_response_register(p, resp, rest, req, seqno);
16530 else if (sipmethod == SIP_INVITE)
16531 handle_response_invite(p, resp, rest, req, seqno);
16532 else if (owner)
16533 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16534 break;
16535 case 423: /* Interval too brief */
16536 if (sipmethod == SIP_REGISTER)
16537 res = handle_response_register(p, resp, rest, req, seqno);
16538 break;
16539 case 408: /* Request timeout - terminate dialog */
16540 if (sipmethod == SIP_INVITE)
16541 handle_response_invite(p, resp, rest, req, seqno);
16542 else if (sipmethod == SIP_REGISTER)
16543 res = handle_response_register(p, resp, rest, req, seqno);
16544 else if (sipmethod == SIP_BYE) {
16545 p->needdestroy = 1;
16546 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
16547 } else {
16548 if (owner)
16549 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16550 p->needdestroy = 1;
16552 break;
16554 case 422: /* Session-Timers: Session Interval Too Small */
16555 if (sipmethod == SIP_INVITE) {
16556 handle_response_invite(p, resp, rest, req, seqno);
16558 break;
16560 case 481: /* Call leg does not exist */
16561 if (sipmethod == SIP_INVITE) {
16562 handle_response_invite(p, resp, rest, req, seqno);
16563 } else if (sipmethod == SIP_REFER) {
16564 handle_response_refer(p, resp, rest, req, seqno);
16565 } else if (sipmethod == SIP_BYE) {
16566 /* The other side has no transaction to bye,
16567 just assume it's all right then */
16568 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
16569 } else if (sipmethod == SIP_CANCEL) {
16570 /* The other side has no transaction to cancel,
16571 just assume it's all right then */
16572 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
16573 } else {
16574 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
16575 /* Guessing that this is not an important request */
16577 break;
16578 case 487:
16579 if (sipmethod == SIP_INVITE)
16580 handle_response_invite(p, resp, rest, req, seqno);
16581 break;
16582 case 488: /* Not acceptable here - codec error */
16583 if (sipmethod == SIP_INVITE)
16584 handle_response_invite(p, resp, rest, req, seqno);
16585 break;
16586 case 491: /* Pending */
16587 if (sipmethod == SIP_INVITE)
16588 handle_response_invite(p, resp, rest, req, seqno);
16589 else {
16590 ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
16591 p->needdestroy = 1;
16593 break;
16594 case 501: /* Not Implemented */
16595 if (sipmethod == SIP_INVITE)
16596 handle_response_invite(p, resp, rest, req, seqno);
16597 else if (sipmethod == SIP_REFER)
16598 handle_response_refer(p, resp, rest, req, seqno);
16599 else
16600 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
16601 break;
16602 case 603: /* Declined transfer */
16603 if (sipmethod == SIP_REFER) {
16604 handle_response_refer(p, resp, rest, req, seqno);
16605 break;
16607 /* Fallthrough */
16608 default:
16609 if ((resp >= 300) && (resp < 700)) {
16610 /* Fatal response */
16611 if ((resp != 487))
16612 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
16614 if (sipmethod == SIP_INVITE)
16615 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
16617 /* XXX Locking issues?? XXX */
16618 switch(resp) {
16619 case 300: /* Multiple Choices */
16620 case 301: /* Moved permanently */
16621 case 302: /* Moved temporarily */
16622 case 305: /* Use Proxy */
16623 parse_moved_contact(p, req);
16624 /* Fall through */
16625 case 486: /* Busy here */
16626 case 600: /* Busy everywhere */
16627 case 603: /* Decline */
16628 if (p->owner)
16629 ast_queue_control(p->owner, AST_CONTROL_BUSY);
16630 break;
16631 case 482: /*!
16632 \note SIP is incapable of performing a hairpin call, which
16633 is yet another failure of not having a layer 2 (again, YAY
16634 IETF for thinking ahead). So we treat this as a call
16635 forward and hope we end up at the right place... */
16636 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
16637 if (p->owner)
16638 ast_string_field_build(p->owner, call_forward,
16639 "Local/%s@%s", p->username, p->context);
16640 /* Fall through */
16641 case 480: /* Temporarily Unavailable */
16642 case 404: /* Not Found */
16643 case 410: /* Gone */
16644 case 400: /* Bad Request */
16645 case 500: /* Server error */
16646 if (sipmethod == SIP_REFER) {
16647 handle_response_refer(p, resp, rest, req, seqno);
16648 break;
16650 /* Fall through */
16651 case 502: /* Bad gateway */
16652 case 503: /* Service Unavailable */
16653 case 504: /* Server Timeout */
16654 if (owner)
16655 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16656 break;
16657 default:
16658 /* Send hangup */
16659 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
16660 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
16661 break;
16663 /* ACK on invite */
16664 if (sipmethod == SIP_INVITE)
16665 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16666 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
16667 sip_alreadygone(p);
16668 if (!p->owner)
16669 p->needdestroy = 1;
16670 } else if ((resp >= 100) && (resp < 200)) {
16671 if (sipmethod == SIP_INVITE) {
16672 if (!req->ignore && sip_cancel_destroy(p))
16673 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16674 if (find_sdp(req))
16675 process_sdp(p, req, SDP_T38_NONE);
16676 if (p->owner) {
16677 /* Queue a progress frame */
16678 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16681 } else
16682 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));
16684 } else {
16685 /* Responses to OUTGOING SIP requests on INCOMING calls
16686 get handled here. As well as out-of-call message responses */
16687 if (req->debug)
16688 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
16690 if (sipmethod == SIP_INVITE && resp == 200) {
16691 /* Tags in early session is replaced by the tag in 200 OK, which is
16692 the final reply to our INVITE */
16693 char tag[128];
16695 gettag(req, "To", tag, sizeof(tag));
16696 ast_string_field_set(p, theirtag, tag);
16699 switch(resp) {
16700 case 200:
16701 if (sipmethod == SIP_INVITE) {
16702 handle_response_invite(p, resp, rest, req, seqno);
16703 } else if (sipmethod == SIP_CANCEL) {
16704 ast_debug(1, "Got 200 OK on CANCEL\n");
16706 /* Wait for 487, then destroy */
16707 } else if (sipmethod == SIP_NOTIFY) {
16708 /* They got the notify, this is the end */
16709 if (p->owner) {
16710 if (p->refer) {
16711 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
16712 } else
16713 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
16714 /* ast_queue_hangup(p->owner); Disabled */
16715 } else {
16716 if (!p->subscribed && !p->refer)
16717 p->needdestroy = 1;
16718 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
16719 /* Ready to send the next state we have on queue */
16720 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16721 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
16724 } else if (sipmethod == SIP_BYE)
16725 p->needdestroy = 1;
16726 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
16727 /* We successfully transmitted a message or
16728 a video update request in INFO */
16730 else if (sipmethod == SIP_BYE)
16731 /* Ok, we're ready to go */
16732 p->needdestroy = 1;
16733 break;
16734 case 202: /* Transfer accepted */
16735 if (sipmethod == SIP_REFER)
16736 handle_response_refer(p, resp, rest, req, seqno);
16737 break;
16738 case 401: /* www-auth */
16739 case 407:
16740 if (sipmethod == SIP_REFER)
16741 handle_response_refer(p, resp, rest, req, seqno);
16742 else if (sipmethod == SIP_INVITE)
16743 handle_response_invite(p, resp, rest, req, seqno);
16744 else if (sipmethod == SIP_BYE) {
16745 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
16746 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
16747 p->needdestroy = 1;
16750 break;
16751 case 481: /* Call leg does not exist */
16752 if (sipmethod == SIP_INVITE) {
16753 /* Re-invite failed */
16754 handle_response_invite(p, resp, rest, req, seqno);
16755 } else if (sipmethod == SIP_BYE) {
16756 p->needdestroy = 1;
16757 } else if (sipdebug) {
16758 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
16760 break;
16761 case 501: /* Not Implemented */
16762 if (sipmethod == SIP_INVITE)
16763 handle_response_invite(p, resp, rest, req, seqno);
16764 else if (sipmethod == SIP_REFER)
16765 handle_response_refer(p, resp, rest, req, seqno);
16766 break;
16767 case 603: /* Declined transfer */
16768 if (sipmethod == SIP_REFER) {
16769 handle_response_refer(p, resp, rest, req, seqno);
16770 break;
16772 /* Fallthrough */
16773 default: /* Errors without handlers */
16774 if ((resp >= 100) && (resp < 200)) {
16775 if (sipmethod == SIP_INVITE) { /* re-invite */
16776 if (!req->ignore && sip_cancel_destroy(p))
16777 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16780 if ((resp >= 300) && (resp < 700)) {
16781 if ((resp != 487))
16782 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
16783 switch(resp) {
16784 case 488: /* Not acceptable here - codec error */
16785 case 603: /* Decline */
16786 case 500: /* Server error */
16787 case 502: /* Bad gateway */
16788 case 503: /* Service Unavailable */
16789 case 504: /* Server timeout */
16791 /* re-invite failed */
16792 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
16793 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16794 break;
16797 break;
16803 /*! \brief Park SIP call support function
16804 Starts in a new thread, then parks the call
16805 XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
16806 audio can't be heard before hangup
16808 static void *sip_park_thread(void *stuff)
16810 struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
16811 struct sip_dual *d;
16812 struct sip_request req;
16813 int ext;
16814 int res;
16816 d = stuff;
16817 transferee = d->chan1;
16818 transferer = d->chan2;
16819 copy_request(&req, &d->req);
16820 if (d->req.data)
16821 ast_free(d->req.data);
16822 ast_free(d);
16824 if (!transferee || !transferer) {
16825 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
16826 return NULL;
16828 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
16830 ast_channel_lock(transferee);
16831 if (ast_do_masquerade(transferee)) {
16832 ast_log(LOG_WARNING, "Masquerade failed.\n");
16833 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
16834 ast_channel_unlock(transferee);
16835 return NULL;
16837 ast_channel_unlock(transferee);
16839 res = ast_park_call(transferee, transferer, 0, &ext);
16842 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
16843 if (!res) {
16844 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
16845 } else {
16846 /* Then tell the transferer what happened */
16847 sprintf(buf, "Call parked on extension '%d'", ext);
16848 transmit_message_with_text(transferer->tech_pvt, buf);
16850 #endif
16852 /* Any way back to the current call??? */
16853 /* Transmit response to the REFER request */
16854 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
16855 if (!res) {
16856 /* Transfer succeeded */
16857 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
16858 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
16859 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
16860 ast_hangup(transferer); /* This will cause a BYE */
16861 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
16862 } else {
16863 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
16864 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
16865 ast_debug(1, "SIP Call parked failed \n");
16866 /* Do not hangup call */
16868 return NULL;
16871 /*! \brief Park a call using the subsystem in res_features.c
16872 This is executed in a separate thread
16874 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
16876 struct sip_dual *d;
16877 struct ast_channel *transferee, *transferer;
16878 /* Chan2m: The transferer, chan1m: The transferee */
16879 pthread_t th;
16881 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
16882 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
16883 if ((!transferer) || (!transferee)) {
16884 if (transferee) {
16885 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16886 ast_hangup(transferee);
16888 if (transferer) {
16889 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16890 ast_hangup(transferer);
16892 return -1;
16895 /* Make formats okay */
16896 transferee->readformat = chan1->readformat;
16897 transferee->writeformat = chan1->writeformat;
16899 /* Prepare for taking over the channel */
16900 ast_channel_masquerade(transferee, chan1);
16902 /* Setup the extensions and such */
16903 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
16904 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
16905 transferee->priority = chan1->priority;
16907 /* We make a clone of the peer channel too, so we can play
16908 back the announcement */
16910 /* Make formats okay */
16911 transferer->readformat = chan2->readformat;
16912 transferer->writeformat = chan2->writeformat;
16914 /* Prepare for taking over the channel. Go ahead and grab this channel
16915 * lock here to avoid a deadlock with callbacks into the channel driver
16916 * that hold the channel lock and want the pvt lock. */
16917 while (ast_channel_trylock(chan2)) {
16918 struct sip_pvt *pvt = chan2->tech_pvt;
16919 sip_pvt_unlock(pvt);
16920 usleep(1);
16921 sip_pvt_lock(pvt);
16923 ast_channel_masquerade(transferer, chan2);
16924 ast_channel_unlock(chan2);
16926 /* Setup the extensions and such */
16927 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
16928 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
16929 transferer->priority = chan2->priority;
16931 ast_channel_lock(transferer);
16932 if (ast_do_masquerade(transferer)) {
16933 ast_log(LOG_WARNING, "Masquerade failed :(\n");
16934 ast_channel_unlock(transferer);
16935 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
16936 ast_hangup(transferer);
16937 return -1;
16939 ast_channel_unlock(transferer);
16940 if (!transferer || !transferee) {
16941 if (!transferer) {
16942 ast_debug(1, "No transferer channel, giving up parking\n");
16944 if (!transferee) {
16945 ast_debug(1, "No transferee channel, giving up parking\n");
16947 return -1;
16949 if ((d = ast_calloc(1, sizeof(*d)))) {
16951 /* Save original request for followup */
16952 copy_request(&d->req, req);
16953 d->chan1 = transferee; /* Transferee */
16954 d->chan2 = transferer; /* Transferer */
16955 d->seqno = seqno;
16956 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
16957 /* Could not start thread */
16958 if (d->req.data)
16959 ast_free(d->req.data);
16960 ast_free(d); /* We don't need it anymore. If thread is created, d will be free'd
16961 by sip_park_thread() */
16962 return 0;
16965 return -1;
16968 /*! \brief Turn off generator data
16969 XXX Does this function belong in the SIP channel?
16971 static void ast_quiet_chan(struct ast_channel *chan)
16973 if (chan && chan->_state == AST_STATE_UP) {
16974 if (ast_test_flag(chan, AST_FLAG_MOH))
16975 ast_moh_stop(chan);
16976 else if (chan->generatordata)
16977 ast_deactivate_generator(chan);
16981 /*! \brief Attempt transfer of SIP call
16982 This fix for attended transfers on a local PBX */
16983 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
16985 int res = 0;
16986 struct ast_channel *peera = NULL,
16987 *peerb = NULL,
16988 *peerc = NULL,
16989 *peerd = NULL;
16992 /* We will try to connect the transferee with the target and hangup
16993 all channels to the transferer */
16994 ast_debug(4, "Sip transfer:--------------------\n");
16995 if (transferer->chan1)
16996 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
16997 else
16998 ast_debug(4, "-- No transferer first channel - odd??? \n");
16999 if (target->chan1)
17000 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
17001 else
17002 ast_debug(4, "-- No target first channel ---\n");
17003 if (transferer->chan2)
17004 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
17005 else
17006 ast_debug(4, "-- No bridged call to transferee\n");
17007 if (target->chan2)
17008 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)");
17009 else
17010 ast_debug(4, "-- No target second channel ---\n");
17011 ast_debug(4, "-- END Sip transfer:--------------------\n");
17012 if (transferer->chan2) { /* We have a bridge on the transferer's channel */
17013 peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
17014 peerb = target->chan1; /* Transferer - PBX -> target channel - This will get lost in masq */
17015 peerc = transferer->chan2; /* Asterisk to Transferee */
17016 peerd = target->chan2; /* Asterisk to Target */
17017 ast_debug(3, "SIP transfer: Four channels to handle\n");
17018 } else if (target->chan2) { /* Transferer has no bridge (IVR), but transferee */
17019 peera = target->chan1; /* Transferer to PBX -> target channel */
17020 peerb = transferer->chan1; /* Transferer to IVR*/
17021 peerc = target->chan2; /* Asterisk to Target */
17022 peerd = transferer->chan2; /* Nothing */
17023 ast_debug(3, "SIP transfer: Three channels to handle\n");
17026 if (peera && peerb && peerc && (peerb != peerc)) {
17027 ast_quiet_chan(peera); /* Stop generators */
17028 ast_quiet_chan(peerb);
17029 ast_quiet_chan(peerc);
17030 if (peerd)
17031 ast_quiet_chan(peerd);
17033 /* Fix CDRs so they're attached to the remaining channel */
17034 if (peera->cdr && peerb->cdr)
17035 peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
17036 else if (peera->cdr)
17037 peerb->cdr = peera->cdr;
17038 peera->cdr = NULL;
17040 if (peerb->cdr && peerc->cdr)
17041 peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
17042 else if (peerc->cdr)
17043 peerb->cdr = peerc->cdr;
17044 peerc->cdr = NULL;
17046 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
17047 if (ast_channel_masquerade(peerb, peerc)) {
17048 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
17049 res = -1;
17050 } else
17051 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
17052 return res;
17053 } else {
17054 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
17055 if (transferer->chan1)
17056 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
17057 if (target->chan1)
17058 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
17059 return -1;
17061 return 0;
17064 /*! \brief Get tag from packet
17066 * \return Returns the pointer to the provided tag buffer,
17067 * or NULL if the tag was not found.
17069 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
17071 const char *thetag;
17073 if (!tagbuf)
17074 return NULL;
17075 tagbuf[0] = '\0'; /* reset the buffer */
17076 thetag = get_header(req, header);
17077 thetag = strcasestr(thetag, ";tag=");
17078 if (thetag) {
17079 thetag += 5;
17080 ast_copy_string(tagbuf, thetag, tagbufsize);
17081 return strsep(&tagbuf, ";");
17083 return NULL;
17086 /*! \brief Handle incoming notifications */
17087 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
17089 /* This is mostly a skeleton for future improvements */
17090 /* Mostly created to return proper answers on notifications on outbound REFER's */
17091 int res = 0;
17092 const char *event = get_header(req, "Event");
17093 char *eventid = NULL;
17094 char *sep;
17096 if( (sep = strchr(event, ';')) ) { /* XXX bug here - overwriting string ? */
17097 *sep++ = '\0';
17098 eventid = sep;
17101 if (sipdebug)
17102 ast_debug(2, "Got NOTIFY Event: %s\n", event);
17104 if (strcmp(event, "refer")) {
17105 /* We don't understand this event. */
17106 /* Here's room to implement incoming voicemail notifications :-) */
17107 transmit_response(p, "489 Bad event", req);
17108 res = -1;
17109 } else {
17110 /* Save nesting depth for now, since there might be other events we will
17111 support in the future */
17113 /* Handle REFER notifications */
17115 char buf[1024];
17116 char *cmd, *code;
17117 int respcode;
17118 int success = TRUE;
17120 /* EventID for each transfer... EventID is basically the REFER cseq
17122 We are getting notifications on a call that we transfered
17123 We should hangup when we are getting a 200 OK in a sipfrag
17124 Check if we have an owner of this event */
17126 /* Check the content type */
17127 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
17128 /* We need a sipfrag */
17129 transmit_response(p, "400 Bad request", req);
17130 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17131 return -1;
17134 /* Get the text of the attachment */
17135 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
17136 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
17137 transmit_response(p, "400 Bad request", req);
17138 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17139 return -1;
17143 From the RFC...
17144 A minimal, but complete, implementation can respond with a single
17145 NOTIFY containing either the body:
17146 SIP/2.0 100 Trying
17148 if the subscription is pending, the body:
17149 SIP/2.0 200 OK
17150 if the reference was successful, the body:
17151 SIP/2.0 503 Service Unavailable
17152 if the reference failed, or the body:
17153 SIP/2.0 603 Declined
17155 if the REFER request was accepted before approval to follow the
17156 reference could be obtained and that approval was subsequently denied
17157 (see Section 2.4.7).
17159 If there are several REFERs in the same dialog, we need to
17160 match the ID of the event header...
17162 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
17163 cmd = ast_skip_blanks(buf);
17164 code = cmd;
17165 /* We are at SIP/2.0 */
17166 while(*code && (*code > 32)) { /* Search white space */
17167 code++;
17169 *code++ = '\0';
17170 code = ast_skip_blanks(code);
17171 sep = code;
17172 sep++;
17173 while(*sep && (*sep > 32)) { /* Search white space */
17174 sep++;
17176 *sep++ = '\0'; /* Response string */
17177 respcode = atoi(code);
17178 switch (respcode) {
17179 case 100: /* Trying: */
17180 case 101: /* dialog establishment */
17181 /* Don't do anything yet */
17182 break;
17183 case 183: /* Ringing: */
17184 /* Don't do anything yet */
17185 break;
17186 case 200: /* OK: The new call is up, hangup this call */
17187 /* Hangup the call that we are replacing */
17188 break;
17189 case 301: /* Moved permenantly */
17190 case 302: /* Moved temporarily */
17191 /* Do we get the header in the packet in this case? */
17192 success = FALSE;
17193 break;
17194 case 503: /* Service Unavailable: The new call failed */
17195 /* Cancel transfer, continue the call */
17196 success = FALSE;
17197 break;
17198 case 603: /* Declined: Not accepted */
17199 /* Cancel transfer, continue the current call */
17200 success = FALSE;
17201 break;
17203 if (!success) {
17204 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
17207 /* Confirm that we received this packet */
17208 transmit_response(p, "200 OK", req);
17211 if (!p->lastinvite)
17212 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17214 return res;
17217 /*! \brief Handle incoming OPTIONS request
17218 An OPTIONS request should be answered like an INVITE from the same UA, including SDP
17220 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
17222 int res;
17224 /*! XXX get_destination assumes we're already authenticated. This means that a request from
17225 a known device (peer/user) will end up in the wrong context if this is out-of-dialog.
17226 However, we want to handle OPTIONS as light as possible, so we might want to have
17227 a configuration option whether we care or not. Some devices use this for testing
17228 capabilities, which means that we need to match device to answer with proper
17229 capabilities (including SDP).
17230 \todo Fix handle_request_options device handling with optional authentication
17231 (this needs to be fixed in 1.4 as well)
17233 res = get_destination(p, req);
17234 build_contact(p);
17236 if (ast_strlen_zero(p->context))
17237 ast_string_field_set(p, context, default_context);
17239 if (ast_shutting_down())
17240 transmit_response_with_allow(p, "503 Unavailable", req, 0);
17241 else if (res < 0)
17242 transmit_response_with_allow(p, "404 Not Found", req, 0);
17243 else
17244 transmit_response_with_allow(p, "200 OK", req, 0);
17246 /* Destroy if this OPTIONS was the opening request, but not if
17247 it's in the middle of a normal call flow. */
17248 if (!p->lastinvite)
17249 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17251 return res;
17254 /*! \brief Handle the transfer part of INVITE with a replaces: header,
17255 meaning a target pickup or an attended transfer.
17256 Used only once.
17257 XXX 'ignore' is unused.
17259 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin)
17261 struct ast_frame *f;
17262 int earlyreplace = 0;
17263 int oneleggedreplace = 0; /* Call with no bridge, propably IVR or voice message */
17264 struct ast_channel *c = p->owner; /* Our incoming call */
17265 struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
17266 struct ast_channel *targetcall; /* The bridge to the take-over target */
17268 struct ast_channel *test;
17270 /* Check if we're in ring state */
17271 if (replacecall->_state == AST_STATE_RING)
17272 earlyreplace = 1;
17274 /* Check if we have a bridge */
17275 if (!(targetcall = ast_bridged_channel(replacecall))) {
17276 /* We have no bridge */
17277 if (!earlyreplace) {
17278 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
17279 oneleggedreplace = 1;
17282 if (targetcall && targetcall->_state == AST_STATE_RINGING)
17283 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
17285 if (targetcall)
17286 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
17287 else
17288 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
17290 if (req->ignore) {
17291 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
17292 /* We should answer something here. If we are here, the
17293 call we are replacing exists, so an accepted
17294 can't harm */
17295 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
17296 /* Do something more clever here */
17297 ast_channel_unlock(c);
17298 sip_pvt_unlock(p->refer->refer_call);
17299 return 1;
17301 if (!c) {
17302 /* What to do if no channel ??? */
17303 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
17304 transmit_response_reliable(p, "503 Service Unavailable", req);
17305 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
17306 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17307 sip_pvt_unlock(p->refer->refer_call);
17308 return 1;
17310 append_history(p, "Xfer", "INVITE/Replace received");
17311 /* We have three channels to play with
17312 channel c: New incoming call
17313 targetcall: Call from PBX to target
17314 p->refer->refer_call: SIP pvt dialog from transferer to pbx.
17315 replacecall: The owner of the previous
17316 We need to masq C into refer_call to connect to
17317 targetcall;
17318 If we are talking to internal audio stream, target call is null.
17321 /* Fake call progress */
17322 transmit_response(p, "100 Trying", req);
17323 ast_setstate(c, AST_STATE_RING);
17325 /* Masquerade the new call into the referred call to connect to target call
17326 Targetcall is not touched by the masq */
17328 /* Answer the incoming call and set channel to UP state */
17329 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
17331 ast_setstate(c, AST_STATE_UP);
17333 /* Stop music on hold and other generators */
17334 ast_quiet_chan(replacecall);
17335 ast_quiet_chan(targetcall);
17336 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
17337 /* Unlock clone, but not original (replacecall) */
17338 if (!oneleggedreplace)
17339 ast_channel_unlock(c);
17341 /* Unlock PVT */
17342 sip_pvt_unlock(p->refer->refer_call);
17344 /* Make sure that the masq does not free our PVT for the old call */
17345 if (! earlyreplace && ! oneleggedreplace )
17346 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
17348 /* Prepare the masquerade - if this does not happen, we will be gone */
17349 if(ast_channel_masquerade(replacecall, c))
17350 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
17351 else
17352 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
17354 /* The masquerade will happen as soon as someone reads a frame from the channel */
17356 /* C should now be in place of replacecall */
17357 /* ast_read needs to lock channel */
17358 ast_channel_unlock(c);
17360 if (earlyreplace || oneleggedreplace ) {
17361 /* Force the masq to happen */
17362 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
17363 ast_frfree(f);
17364 f = NULL;
17365 ast_debug(4, "Invite/Replace: Could successfully read frame from RING channel!\n");
17366 } else {
17367 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
17369 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17370 if (!oneleggedreplace)
17371 ast_channel_unlock(replacecall);
17372 } else { /* Bridged call, UP channel */
17373 if ((f = ast_read(replacecall))) { /* Force the masq to happen */
17374 /* Masq ok */
17375 ast_frfree(f);
17376 f = NULL;
17377 ast_debug(3, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
17378 } else {
17379 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
17381 ast_channel_unlock(replacecall);
17383 sip_pvt_unlock(p->refer->refer_call);
17385 ast_setstate(c, AST_STATE_DOWN);
17386 ast_debug(4, "After transfer:----------------------------\n");
17387 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
17388 if (replacecall)
17389 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
17390 if (p->owner) {
17391 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
17392 test = ast_bridged_channel(p->owner);
17393 if (test)
17394 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
17395 else
17396 ast_debug(4, " -- No call bridged to C->owner \n");
17397 } else
17398 ast_debug(4, " -- No channel yet \n");
17399 ast_debug(4, "End After transfer:----------------------------\n");
17401 ast_channel_unlock(p->owner); /* Unlock new owner */
17402 if (!oneleggedreplace)
17403 sip_pvt_unlock(p); /* Unlock SIP structure */
17405 /* The call should be down with no ast_channel, so hang it up */
17406 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
17407 ast_hangup(c);
17408 return 0;
17412 /*! \brief Handle incoming INVITE request
17413 \note If the INVITE has a Replaces header, it is part of an
17414 * attended transfer. If so, we do not go through the dial
17415 * plan but tries to find the active call and masquerade
17416 * into it
17418 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)
17420 int res = 1;
17421 int gotdest;
17422 const char *p_replaces;
17423 char *replace_id = NULL;
17424 const char *required;
17425 unsigned int required_profile = 0;
17426 struct ast_channel *c = NULL; /* New channel */
17427 int reinvite = 0;
17428 int rtn;
17430 const char *p_uac_se_hdr; /* UAC's Session-Expires header string */
17431 const char *p_uac_min_se; /* UAC's requested Min-SE interval (char string) */
17432 int uac_max_se = -1; /* UAC's Session-Expires in integer format */
17433 int uac_min_se = -1; /* UAC's Min-SE in integer format */
17434 int st_active = FALSE; /* Session-Timer on/off boolean */
17435 int st_interval = 0; /* Session-Timer negotiated refresh interval */
17436 enum st_refresher st_ref; /* Session-Timer session refresher */
17437 int dlg_min_se = -1;
17438 st_ref = SESSION_TIMER_REFRESHER_AUTO;
17440 /* Find out what they support */
17441 if (!p->sipoptions) {
17442 const char *supported = get_header(req, "Supported");
17443 if (!ast_strlen_zero(supported))
17444 parse_sip_options(p, supported);
17447 /* Find out what they require */
17448 required = get_header(req, "Require");
17449 if (!ast_strlen_zero(required)) {
17450 required_profile = parse_sip_options(NULL, required);
17451 if (required_profile && required_profile != SIP_OPT_REPLACES && required_profile != SIP_OPT_TIMER) {
17452 /* At this point we only support REPLACES and Session-Timer */
17453 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
17454 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
17455 p->invitestate = INV_COMPLETED;
17456 if (!p->lastinvite)
17457 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17458 return -1;
17462 /* The option tags may be present in Supported: or Require: headers.
17463 Include the Require: option tags for further processing as well */
17464 p->sipoptions |= required_profile;
17465 p->reqsipoptions = required_profile;
17467 /* Check if this is a loop */
17468 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
17469 /* This is a call to ourself. Send ourselves an error code and stop
17470 processing immediately, as SIP really has no good mechanism for
17471 being able to call yourself */
17472 /* If pedantic is on, we need to check the tags. If they're different, this is
17473 in fact a forked call through a SIP proxy somewhere. */
17474 transmit_response(p, "482 Loop Detected", req);
17475 p->invitestate = INV_COMPLETED;
17476 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17477 return 0;
17480 if (!req->ignore && p->pendinginvite) {
17481 /* We already have a pending invite. Sorry. You are on hold. */
17482 transmit_response(p, "491 Request Pending", req);
17483 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
17484 /* Don't destroy dialog here */
17485 return 0;
17488 p_replaces = get_header(req, "Replaces");
17489 if (!ast_strlen_zero(p_replaces)) {
17490 /* We have a replaces header */
17491 char *ptr;
17492 char *fromtag = NULL;
17493 char *totag = NULL;
17494 char *start, *to;
17495 int error = 0;
17497 if (p->owner) {
17498 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
17499 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
17500 /* Do not destroy existing call */
17501 return -1;
17504 if (sipdebug)
17505 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
17506 /* Create a buffer we can manipulate */
17507 replace_id = ast_strdupa(p_replaces);
17508 ast_uri_decode(replace_id);
17510 if (!p->refer && !sip_refer_allocate(p)) {
17511 transmit_response(p, "500 Server Internal Error", req);
17512 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
17513 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17514 p->invitestate = INV_COMPLETED;
17515 return -1;
17518 /* Todo: (When we find phones that support this)
17519 if the replaces header contains ";early-only"
17520 we can only replace the call in early
17521 stage, not after it's up.
17523 If it's not in early mode, 486 Busy.
17526 /* Skip leading whitespace */
17527 replace_id = ast_skip_blanks(replace_id);
17529 start = replace_id;
17530 while ( (ptr = strsep(&start, ";")) ) {
17531 ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
17532 if ( (to = strcasestr(ptr, "to-tag=") ) )
17533 totag = to + 7; /* skip the keyword */
17534 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
17535 fromtag = to + 9; /* skip the keyword */
17536 fromtag = strsep(&fromtag, "&"); /* trim what ? */
17540 if (sipdebug)
17541 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>");
17544 /* Try to find call that we are replacing
17545 If we have a Replaces header, we need to cancel that call if we succeed with this call
17547 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
17548 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
17549 transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
17550 error = 1;
17553 /* At this point, bot the pvt and the owner of the call to be replaced is locked */
17555 /* The matched call is the call from the transferer to Asterisk .
17556 We want to bridge the bridged part of the call to the
17557 incoming invite, thus taking over the refered call */
17559 if (p->refer->refer_call == p) {
17560 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
17561 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
17562 transmit_response(p, "400 Bad request", req); /* The best way to not not accept the transfer */
17563 error = 1;
17566 if (!error && !p->refer->refer_call->owner) {
17567 /* Oops, someting wrong anyway, no owner, no call */
17568 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
17569 /* Check for better return code */
17570 transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
17571 error = 1;
17574 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 ) {
17575 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
17576 transmit_response(p, "603 Declined (Replaces)", req);
17577 error = 1;
17580 if (error) { /* Give up this dialog */
17581 append_history(p, "Xfer", "INVITE/Replace Failed.");
17582 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17583 sip_pvt_unlock(p);
17584 if (p->refer->refer_call) {
17585 sip_pvt_unlock(p->refer->refer_call);
17586 ast_channel_unlock(p->refer->refer_call->owner);
17588 p->invitestate = INV_COMPLETED;
17589 return -1;
17593 /* Check if this is an INVITE that sets up a new dialog or
17594 a re-invite in an existing dialog */
17596 if (!req->ignore) {
17597 int newcall = (p->initreq.headers ? TRUE : FALSE);
17599 if (sip_cancel_destroy(p))
17600 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17601 /* This also counts as a pending invite */
17602 p->pendinginvite = seqno;
17603 check_via(p, req);
17605 copy_request(&p->initreq, req); /* Save this INVITE as the transaction basis */
17606 if (sipdebug)
17607 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
17608 if (!p->owner) { /* Not a re-invite */
17609 if (debug)
17610 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
17611 if (newcall)
17612 append_history(p, "Invite", "New call: %s", p->callid);
17613 parse_ok_contact(p, req);
17614 } else { /* Re-invite on existing call */
17615 ast_clear_flag(&p->flags[0], SIP_OUTGOING); /* This is now an inbound dialog */
17616 /* Handle SDP here if we already have an owner */
17617 if (find_sdp(req)) {
17618 if (process_sdp(p, req, SDP_T38_INITIATE)) {
17619 transmit_response(p, "488 Not acceptable here", req);
17620 if (!p->lastinvite)
17621 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17622 return -1;
17624 } else {
17625 p->jointcapability = p->capability;
17626 ast_debug(1, "Hm.... No sdp for the moment\n");
17628 if (p->do_history) /* This is a response, note what it was for */
17629 append_history(p, "ReInv", "Re-invite received");
17631 } else if (debug)
17632 ast_verbose("Ignoring this INVITE request\n");
17635 if (!p->lastinvite && !req->ignore && !p->owner) {
17636 /* This is a new invite */
17637 /* Handle authentication if this is our first invite */
17638 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
17639 if (res == AUTH_CHALLENGE_SENT) {
17640 p->invitestate = INV_COMPLETED; /* Needs to restart in another INVITE transaction */
17641 return 0;
17643 if (res < 0) { /* Something failed in authentication */
17644 if (res == AUTH_FAKE_AUTH) {
17645 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
17646 transmit_fake_auth_response(p, req, 1);
17647 } else {
17648 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
17649 transmit_response_reliable(p, "403 Forbidden", req);
17651 p->invitestate = INV_COMPLETED;
17652 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17653 ast_string_field_set(p, theirtag, NULL);
17654 return 0;
17657 /* We have a succesful authentication, process the SDP portion if there is one */
17658 if (find_sdp(req)) {
17659 if (process_sdp(p, req, SDP_T38_INITIATE)) {
17660 /* Unacceptable codecs */
17661 transmit_response_reliable(p, "488 Not acceptable here", req);
17662 p->invitestate = INV_COMPLETED;
17663 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17664 ast_debug(1, "No compatible codecs for this SIP call.\n");
17665 return -1;
17667 } else { /* No SDP in invite, call control session */
17668 p->jointcapability = p->capability;
17669 ast_debug(2, "No SDP in Invite, third party call control\n");
17672 /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
17673 /* This seems redundant ... see !p-owner above */
17674 if (p->owner)
17675 ast_queue_frame(p->owner, &ast_null_frame);
17678 /* Initialize the context if it hasn't been already */
17679 if (ast_strlen_zero(p->context))
17680 ast_string_field_set(p, context, default_context);
17683 /* Check number of concurrent calls -vs- incoming limit HERE */
17684 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
17685 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
17686 if (res < 0) {
17687 ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
17688 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
17689 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17690 p->invitestate = INV_COMPLETED;
17692 return 0;
17694 gotdest = get_destination(p, NULL); /* Get destination right away */
17695 get_rdnis(p, NULL); /* Get redirect information */
17696 extract_uri(p, req); /* Get the Contact URI */
17697 build_contact(p); /* Build our contact header */
17699 if (p->rtp) {
17700 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
17701 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
17704 if (!replace_id && gotdest) { /* No matching extension found */
17705 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
17706 transmit_response_reliable(p, "484 Address Incomplete", req);
17707 else {
17708 transmit_response_reliable(p, "404 Not Found", req);
17709 ast_log(LOG_NOTICE, "Call from '%s' to extension"
17710 " '%s' rejected because extension not found.\n",
17711 S_OR(p->username, p->peername), p->exten);
17713 p->invitestate = INV_COMPLETED;
17714 update_call_counter(p, DEC_CALL_LIMIT);
17715 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17716 return 0;
17717 } else {
17719 /* If no extension was specified, use the s one */
17720 /* Basically for calling to IP/Host name only */
17721 if (ast_strlen_zero(p->exten))
17722 ast_string_field_set(p, exten, "s");
17723 /* Initialize our tag */
17725 make_our_tag(p->tag, sizeof(p->tag));
17726 /* First invitation - create the channel */
17727 c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
17728 *recount = 1;
17730 /* Save Record-Route for any later requests we make on this dialogue */
17731 build_route(p, req, 0);
17733 if (c) {
17734 /* Pre-lock the call */
17735 ast_channel_lock(c);
17738 } else {
17739 if (sipdebug) {
17740 if (!req->ignore)
17741 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
17742 else
17743 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
17746 reinvite = 1;
17747 c = p->owner;
17750 /* Session-Timers */
17751 if (p->sipoptions == SIP_OPT_TIMER) {
17752 /* The UAC has requested session-timers for this session. Negotiate
17753 the session refresh interval and who will be the refresher */
17754 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
17756 /* Allocate Session-Timers struct w/in the dialog */
17757 if (!p->stimer)
17758 sip_st_alloc(p);
17760 /* Parse the Session-Expires header */
17761 p_uac_se_hdr = get_header(req, "Session-Expires");
17762 if (!ast_strlen_zero(p_uac_se_hdr)) {
17763 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
17764 if (rtn != 0) {
17765 transmit_response(p, "400 Session-Expires Invalid Syntax", req);
17766 p->invitestate = INV_COMPLETED;
17767 if (!p->lastinvite) {
17768 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17770 return -1;
17774 /* Parse the Min-SE header */
17775 p_uac_min_se = get_header(req, "Min-SE");
17776 if (!ast_strlen_zero(p_uac_min_se)) {
17777 rtn = parse_minse(p_uac_min_se, &uac_min_se);
17778 if (rtn != 0) {
17779 transmit_response(p, "400 Min-SE Invalid Syntax", req);
17780 p->invitestate = INV_COMPLETED;
17781 if (!p->lastinvite) {
17782 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17784 return -1;
17788 dlg_min_se = st_get_se(p, FALSE);
17789 switch (st_get_mode(p)) {
17790 case SESSION_TIMER_MODE_ACCEPT:
17791 case SESSION_TIMER_MODE_ORIGINATE:
17792 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
17793 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
17794 p->invitestate = INV_COMPLETED;
17795 if (!p->lastinvite) {
17796 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17798 return -1;
17801 p->stimer->st_active_peer_ua = TRUE;
17802 st_active = TRUE;
17803 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
17804 st_ref = st_get_refresher(p);
17807 if (uac_max_se > 0) {
17808 int dlg_max_se = st_get_se(p, TRUE);
17809 if (dlg_max_se >= uac_min_se) {
17810 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
17811 } else {
17812 st_interval = uac_max_se;
17814 } else {
17815 st_interval = uac_min_se;
17817 break;
17819 case SESSION_TIMER_MODE_REFUSE:
17820 if (p->reqsipoptions == SIP_OPT_TIMER) {
17821 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
17822 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
17823 p->invitestate = INV_COMPLETED;
17824 if (!p->lastinvite) {
17825 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17827 return -1;
17829 break;
17831 default:
17832 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
17833 break;
17835 } else {
17836 /* The UAC did not request session-timers. Asterisk (UAS), will now decide
17837 (based on session-timer-mode in sip.conf) whether to run session-timers for
17838 this session or not. */
17839 switch (st_get_mode(p)) {
17840 case SESSION_TIMER_MODE_ORIGINATE:
17841 st_active = TRUE;
17842 st_interval = st_get_se(p, TRUE);
17843 st_ref = SESSION_TIMER_REFRESHER_UAS;
17844 p->stimer->st_active_peer_ua = FALSE;
17845 break;
17847 default:
17848 break;
17852 if (reinvite == 0) {
17853 /* Session-Timers: Start session refresh timer based on negotiation/config */
17854 if (st_active == TRUE) {
17855 p->stimer->st_active = TRUE;
17856 p->stimer->st_interval = st_interval;
17857 p->stimer->st_ref = st_ref;
17858 start_session_timer(p);
17860 } else {
17861 if (p->stimer->st_active == TRUE) {
17862 /* Session-Timers: A re-invite request sent within a dialog will serve as
17863 a refresh request, no matter whether the re-invite was sent for refreshing
17864 the session or modifying it.*/
17865 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
17867 /* The UAC may be adjusting the session-timers mid-session */
17868 if (st_interval > 0) {
17869 p->stimer->st_interval = st_interval;
17870 p->stimer->st_ref = st_ref;
17873 restart_session_timer(p);
17874 if (p->stimer->st_expirys > 0) {
17875 p->stimer->st_expirys--;
17880 if (!req->ignore && p)
17881 p->lastinvite = seqno;
17883 if (replace_id) { /* Attended transfer or call pickup - we're the target */
17884 /* Go and take over the target call */
17885 if (sipdebug)
17886 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
17887 return handle_invite_replaces(p, req, debug, seqno, sin);
17891 if (c) { /* We have a call -either a new call or an old one (RE-INVITE) */
17892 switch(c->_state) {
17893 case AST_STATE_DOWN:
17894 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
17895 transmit_response(p, "100 Trying", req);
17896 p->invitestate = INV_PROCEEDING;
17897 ast_setstate(c, AST_STATE_RING);
17898 if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
17899 enum ast_pbx_result res;
17901 res = ast_pbx_start(c);
17903 switch(res) {
17904 case AST_PBX_FAILED:
17905 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
17906 p->invitestate = INV_COMPLETED;
17907 if (req->ignore)
17908 transmit_response(p, "503 Unavailable", req);
17909 else
17910 transmit_response_reliable(p, "503 Unavailable", req);
17911 break;
17912 case AST_PBX_CALL_LIMIT:
17913 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
17914 p->invitestate = INV_COMPLETED;
17915 if (req->ignore)
17916 transmit_response(p, "480 Temporarily Unavailable", req);
17917 else
17918 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
17919 break;
17920 case AST_PBX_SUCCESS:
17921 /* nothing to do */
17922 break;
17925 if (res) {
17927 /* Unlock locks so ast_hangup can do its magic */
17928 ast_channel_unlock(c);
17929 sip_pvt_unlock(p);
17930 ast_hangup(c);
17931 sip_pvt_lock(p);
17932 c = NULL;
17934 } else { /* Pickup call in call group */
17935 ast_channel_unlock(c);
17936 *nounlock = 1;
17937 if (ast_pickup_call(c)) {
17938 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
17939 if (req->ignore)
17940 transmit_response(p, "503 Unavailable", req); /* OEJ - Right answer? */
17941 else
17942 transmit_response_reliable(p, "503 Unavailable", req);
17943 sip_alreadygone(p);
17944 /* Unlock locks so ast_hangup can do its magic */
17945 sip_pvt_unlock(p);
17946 c->hangupcause = AST_CAUSE_CALL_REJECTED;
17947 } else {
17948 sip_pvt_unlock(p);
17949 ast_setstate(c, AST_STATE_DOWN);
17950 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17952 p->invitestate = INV_COMPLETED;
17953 ast_hangup(c);
17954 sip_pvt_lock(p);
17955 c = NULL;
17957 break;
17958 case AST_STATE_RING:
17959 transmit_response(p, "100 Trying", req);
17960 p->invitestate = INV_PROCEEDING;
17961 break;
17962 case AST_STATE_RINGING:
17963 transmit_response(p, "180 Ringing", req);
17964 p->invitestate = INV_PROCEEDING;
17965 break;
17966 case AST_STATE_UP:
17967 ast_debug(2, "%s: This call is UP.... \n", c->name);
17969 transmit_response(p, "100 Trying", req);
17971 if (p->t38.state == T38_PEER_REINVITE) {
17972 struct ast_channel *bridgepeer = NULL;
17973 struct sip_pvt *bridgepvt = NULL;
17975 if ((bridgepeer = ast_bridged_channel(p->owner))) {
17976 /* 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*/
17977 /*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
17978 if (IS_SIP_TECH(bridgepeer->tech)) {
17979 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
17980 if (bridgepvt->t38.state == T38_DISABLED) {
17981 if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
17982 /* Send re-invite to the bridged channel */
17983 sip_handle_t38_reinvite(bridgepeer, p, 1);
17984 } else { /* Something is wrong with peers udptl struct */
17985 ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
17986 sip_pvt_lock(bridgepvt);
17987 change_t38_state(bridgepvt, T38_DISABLED);
17988 sip_pvt_unlock(bridgepvt);
17989 if (req->ignore)
17990 transmit_response(p, "488 Not acceptable here", req);
17991 else
17992 transmit_response_reliable(p, "488 Not acceptable here", req);
17995 } else {
17996 /* The other side is already setup for T.38 most likely so we need to acknowledge this too */
17997 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
17998 change_t38_state(p, T38_ENABLED);
18000 } else {
18001 /* Other side is not a SIP channel */
18002 if (req->ignore)
18003 transmit_response(p, "488 Not acceptable here", req);
18004 else
18005 transmit_response_reliable(p, "488 Not acceptable here", req);
18006 change_t38_state(p, T38_DISABLED);
18008 if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
18009 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18011 } else {
18012 /* we are not bridged in a call */
18013 transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
18014 change_t38_state(p, T38_ENABLED);
18016 } else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
18017 int sendok = TRUE;
18019 /* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
18020 /* so handle it here (re-invite other party to RTP) */
18021 struct ast_channel *bridgepeer = NULL;
18022 struct sip_pvt *bridgepvt = NULL;
18023 if ((bridgepeer = ast_bridged_channel(p->owner))) {
18024 if (IS_SIP_TECH(bridgepeer->tech) && !ast_check_hangup(bridgepeer)) {
18025 bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
18026 /* Does the bridged peer have T38 ? */
18027 if (bridgepvt->t38.state == T38_ENABLED) {
18028 ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
18029 /* Insted of this we should somehow re-invite the other side of the bridge to RTP */
18030 if (req->ignore)
18031 transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
18032 else
18033 transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
18034 sendok = FALSE;
18036 /* No bridged peer with T38 enabled*/
18039 /* Respond to normal re-invite */
18040 if (sendok) {
18041 /* If this is not a re-invite or something to ignore - it's critical */
18042 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
18045 p->invitestate = INV_TERMINATED;
18046 break;
18047 default:
18048 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
18049 transmit_response(p, "100 Trying", req);
18050 break;
18052 } else {
18053 if (p && (p->autokillid == -1)) {
18054 const char *msg;
18056 if (!p->jointcapability)
18057 msg = "488 Not Acceptable Here (codec error)";
18058 else {
18059 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
18060 msg = "503 Unavailable";
18062 if (req->ignore)
18063 transmit_response(p, msg, req);
18064 else
18065 transmit_response_reliable(p, msg, req);
18066 p->invitestate = INV_COMPLETED;
18067 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18070 return res;
18073 /*! \brief Find all call legs and bridge transferee with target
18074 * called from handle_request_refer */
18075 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
18077 struct sip_dual target; /* Chan 1: Call from tranferer to Asterisk */
18078 /* Chan 2: Call from Asterisk to target */
18079 int res = 0;
18080 struct sip_pvt *targetcall_pvt;
18082 /* Check if the call ID of the replaces header does exist locally */
18083 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
18084 transferer->refer->replaces_callid_fromtag))) {
18085 if (transferer->refer->localtransfer) {
18086 /* We did not find the refered call. Sorry, can't accept then */
18087 transmit_response(transferer, "202 Accepted", req);
18088 /* Let's fake a response from someone else in order
18089 to follow the standard */
18090 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
18091 append_history(transferer, "Xfer", "Refer failed");
18092 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
18093 transferer->refer->status = REFER_FAILED;
18094 return -1;
18096 /* Fall through for remote transfers that we did not find locally */
18097 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
18098 return 0;
18101 /* Ok, we can accept this transfer */
18102 transmit_response(transferer, "202 Accepted", req);
18103 append_history(transferer, "Xfer", "Refer accepted");
18104 if (!targetcall_pvt->owner) { /* No active channel */
18105 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
18106 /* Cancel transfer */
18107 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
18108 append_history(transferer, "Xfer", "Refer failed");
18109 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
18110 transferer->refer->status = REFER_FAILED;
18111 sip_pvt_unlock(targetcall_pvt);
18112 ast_channel_unlock(current->chan1);
18113 if (targetcall_pvt)
18114 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
18115 return -1;
18118 /* We have a channel, find the bridge */
18119 target.chan1 = targetcall_pvt->owner; /* Transferer to Asterisk */
18120 target.chan2 = ast_bridged_channel(targetcall_pvt->owner); /* Asterisk to target */
18122 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
18123 /* Wrong state of new channel */
18124 if (target.chan2)
18125 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
18126 else if (target.chan1->_state != AST_STATE_RING)
18127 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
18128 else
18129 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
18132 /* Transfer */
18133 if (sipdebug) {
18134 if (current->chan2) /* We have two bridges */
18135 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
18136 else /* One bridge, propably transfer of IVR/voicemail etc */
18137 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
18140 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
18142 /* If we are performing an attended transfer and we have two channels involved then copy sound file information to play upon attended transfer completion */
18143 if (target.chan2) {
18144 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");
18145 if (!ast_strlen_zero(chan1_attended_sound)) {
18146 pbx_builtin_setvar_helper(target.chan1, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
18148 if (!ast_strlen_zero(chan2_attended_sound)) {
18149 pbx_builtin_setvar_helper(target.chan2, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
18153 /* Perform the transfer */
18154 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",
18155 transferer->owner->name,
18156 transferer->owner->uniqueid,
18157 transferer->callid,
18158 target.chan1->name,
18159 target.chan1->uniqueid);
18160 res = attempt_transfer(current, &target);
18161 sip_pvt_unlock(targetcall_pvt);
18162 if (res) {
18163 /* Failed transfer */
18164 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
18165 append_history(transferer, "Xfer", "Refer failed");
18166 if (targetcall_pvt->owner)
18167 ast_channel_unlock(targetcall_pvt->owner);
18168 /* Right now, we have to hangup, sorry. Bridge is destroyed */
18169 if (res != -2)
18170 ast_hangup(transferer->owner);
18171 else
18172 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
18173 } else {
18174 /* Transfer succeeded! */
18176 /* Tell transferer that we're done. */
18177 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
18178 append_history(transferer, "Xfer", "Refer succeeded");
18179 transferer->refer->status = REFER_200OK;
18180 if (targetcall_pvt->owner) {
18181 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
18182 ast_channel_unlock(targetcall_pvt->owner);
18185 if (targetcall_pvt)
18186 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
18187 return 1;
18191 /*! \brief Handle incoming REFER request */
18192 /*! \page SIP_REFER SIP transfer Support (REFER)
18194 REFER is used for call transfer in SIP. We get a REFER
18195 to place a new call with an INVITE somwhere and then
18196 keep the transferor up-to-date of the transfer. If the
18197 transfer fails, get back on line with the orginal call.
18199 - REFER can be sent outside or inside of a dialog.
18200 Asterisk only accepts REFER inside of a dialog.
18202 - If we get a replaces header, it is an attended transfer
18204 \par Blind transfers
18205 The transferor provides the transferee
18206 with the transfer targets contact. The signalling between
18207 transferer or transferee should not be cancelled, so the
18208 call is recoverable if the transfer target can not be reached
18209 by the transferee.
18211 In this case, Asterisk receives a TRANSFER from
18212 the transferor, thus is the transferee. We should
18213 try to set up a call to the contact provided
18214 and if that fails, re-connect the current session.
18215 If the new call is set up, we issue a hangup.
18216 In this scenario, we are following section 5.2
18217 in the SIP CC Transfer draft. (Transfer without
18218 a GRUU)
18220 \par Transfer with consultation hold
18221 In this case, the transferor
18222 talks to the transfer target before the transfer takes place.
18223 This is implemented with SIP hold and transfer.
18224 Note: The invite From: string could indicate a transfer.
18225 (Section 6. Transfer with consultation hold)
18226 The transferor places the transferee on hold, starts a call
18227 with the transfer target to alert them to the impending
18228 transfer, terminates the connection with the target, then
18229 proceeds with the transfer (as in Blind transfer above)
18231 \par Attended transfer
18232 The transferor places the transferee
18233 on hold, calls the transfer target to alert them,
18234 places the target on hold, then proceeds with the transfer
18235 using a Replaces header field in the Refer-to header. This
18236 will force the transfee to send an Invite to the target,
18237 with a replaces header that instructs the target to
18238 hangup the call between the transferor and the target.
18239 In this case, the Refer/to: uses the AOR address. (The same
18240 URI that the transferee used to establish the session with
18241 the transfer target (To: ). The Require: replaces header should
18242 be in the INVITE to avoid the wrong UA in a forked SIP proxy
18243 scenario to answer and have no call to replace with.
18245 The referred-by header is *NOT* required, but if we get it,
18246 can be copied into the INVITE to the transfer target to
18247 inform the target about the transferor
18249 "Any REFER request has to be appropriately authenticated.".
18251 We can't destroy dialogs, since we want the call to continue.
18254 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
18256 struct sip_dual current; /* Chan1: Call between asterisk and transferer */
18257 /* Chan2: Call between asterisk and transferee */
18259 int res = 0;
18261 if (req->debug)
18262 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");
18264 if (!p->owner) {
18265 /* This is a REFER outside of an existing SIP dialog */
18266 /* We can't handle that, so decline it */
18267 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
18268 transmit_response(p, "603 Declined (No dialog)", req);
18269 if (!req->ignore) {
18270 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
18271 sip_alreadygone(p);
18272 p->needdestroy = 1;
18274 return 0;
18278 /* Check if transfer is allowed from this device */
18279 if (p->allowtransfer == TRANSFER_CLOSED ) {
18280 /* Transfer not allowed, decline */
18281 transmit_response(p, "603 Declined (policy)", req);
18282 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
18283 /* Do not destroy SIP session */
18284 return 0;
18287 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
18288 /* Already have a pending REFER */
18289 transmit_response(p, "491 Request pending", req);
18290 append_history(p, "Xfer", "Refer failed. Request pending.");
18291 return 0;
18294 /* Allocate memory for call transfer data */
18295 if (!p->refer && !sip_refer_allocate(p)) {
18296 transmit_response(p, "500 Internal Server Error", req);
18297 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
18298 return -3;
18301 res = get_refer_info(p, req); /* Extract headers */
18303 p->refer->status = REFER_SENT;
18305 if (res != 0) {
18306 switch (res) {
18307 case -2: /* Syntax error */
18308 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
18309 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
18310 if (req->debug)
18311 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
18312 break;
18313 case -3:
18314 transmit_response(p, "603 Declined (Non sip: uri)", req);
18315 append_history(p, "Xfer", "Refer failed. Non SIP uri");
18316 if (req->debug)
18317 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
18318 break;
18319 default:
18320 /* Refer-to extension not found, fake a failed transfer */
18321 transmit_response(p, "202 Accepted", req);
18322 append_history(p, "Xfer", "Refer failed. Bad extension.");
18323 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
18324 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
18325 if (req->debug)
18326 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
18327 break;
18329 return 0;
18331 if (ast_strlen_zero(p->context))
18332 ast_string_field_set(p, context, default_context);
18334 /* If we do not support SIP domains, all transfers are local */
18335 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
18336 p->refer->localtransfer = 1;
18337 if (sipdebug)
18338 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
18339 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
18340 /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
18341 p->refer->localtransfer = 1;
18342 } else if (sipdebug)
18343 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
18345 /* Is this a repeat of a current request? Ignore it */
18346 /* Don't know what else to do right now. */
18347 if (req->ignore)
18348 return res;
18350 /* If this is a blind transfer, we have the following
18351 channels to work with:
18352 - chan1, chan2: The current call between transferer and transferee (2 channels)
18353 - target_channel: A new call from the transferee to the target (1 channel)
18354 We need to stay tuned to what happens in order to be able
18355 to bring back the call to the transferer */
18357 /* If this is a attended transfer, we should have all call legs within reach:
18358 - chan1, chan2: The call between the transferer and transferee (2 channels)
18359 - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
18360 We want to bridge chan2 with targetcall_pvt!
18362 The replaces call id in the refer message points
18363 to the call leg between Asterisk and the transferer.
18364 So we need to connect the target and the transferee channel
18365 and hangup the two other channels silently
18367 If the target is non-local, the call ID could be on a remote
18368 machine and we need to send an INVITE with replaces to the
18369 target. We basically handle this as a blind transfer
18370 and let the sip_call function catch that we need replaces
18371 header in the INVITE.
18375 /* Get the transferer's channel */
18376 current.chan1 = p->owner;
18378 /* Find the other part of the bridge (2) - transferee */
18379 current.chan2 = ast_bridged_channel(current.chan1);
18381 if (sipdebug)
18382 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>");
18384 if (!current.chan2 && !p->refer->attendedtransfer) {
18385 /* No bridged channel, propably IVR or echo or similar... */
18386 /* Guess we should masquerade or something here */
18387 /* Until we figure it out, refuse transfer of such calls */
18388 if (sipdebug)
18389 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
18390 p->refer->status = REFER_FAILED;
18391 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
18392 transmit_response(p, "603 Declined", req);
18393 return -1;
18396 if (current.chan2) {
18397 if (sipdebug)
18398 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
18400 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
18403 ast_set_flag(&p->flags[0], SIP_GOTREFER);
18405 /* Attended transfer: Find all call legs and bridge transferee with target*/
18406 if (p->refer->attendedtransfer) {
18407 if ((res = local_attended_transfer(p, &current, req, seqno)))
18408 return res; /* We're done with the transfer */
18409 /* Fall through for remote transfers that we did not find locally */
18410 if (sipdebug)
18411 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
18412 /* Fallthrough if we can't find the call leg internally */
18416 /* Parking a call */
18417 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
18418 /* Must release c's lock now, because it will not longer be accessible after the transfer! */
18419 *nounlock = 1;
18420 ast_channel_unlock(current.chan1);
18421 copy_request(&current.req, req);
18422 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
18423 p->refer->status = REFER_200OK;
18424 append_history(p, "Xfer", "REFER to call parking.");
18425 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",
18426 current.chan1->name,
18427 current.chan1->uniqueid,
18428 p->callid,
18429 current.chan2->name,
18430 current.chan2->uniqueid,
18431 p->refer->refer_to);
18432 if (sipdebug)
18433 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
18434 sip_park(current.chan2, current.chan1, req, seqno);
18435 return res;
18438 /* Blind transfers and remote attended xfers */
18439 transmit_response(p, "202 Accepted", req);
18441 if (current.chan1 && current.chan2) {
18442 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
18443 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
18445 if (current.chan2) {
18446 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
18447 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
18448 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
18449 /* One for the new channel */
18450 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
18451 /* Attended transfer to remote host, prepare headers for the INVITE */
18452 if (p->refer->referred_by)
18453 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
18455 /* Generate a Replaces string to be used in the INVITE during attended transfer */
18456 if (!ast_strlen_zero(p->refer->replaces_callid)) {
18457 char tempheader[SIPBUFSIZE];
18458 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
18459 p->refer->replaces_callid_totag ? ";to-tag=" : "",
18460 p->refer->replaces_callid_totag,
18461 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
18462 p->refer->replaces_callid_fromtag);
18463 if (current.chan2)
18464 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
18466 /* Must release lock now, because it will not longer
18467 be accessible after the transfer! */
18468 *nounlock = 1;
18469 ast_channel_unlock(current.chan1);
18471 /* Connect the call */
18473 /* FAKE ringing if not attended transfer */
18474 if (!p->refer->attendedtransfer)
18475 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
18477 /* For blind transfer, this will lead to a new call */
18478 /* For attended transfer to remote host, this will lead to
18479 a new SIP call with a replaces header, if the dial plan allows it
18481 if (!current.chan2) {
18482 /* We have no bridge, so we're talking with Asterisk somehow */
18483 /* We need to masquerade this call */
18484 /* What to do to fix this situation:
18485 * Set up the new call in a new channel
18486 * Let the new channel masq into this channel
18487 Please add that code here :-)
18489 p->refer->status = REFER_FAILED;
18490 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
18491 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
18492 append_history(p, "Xfer", "Refer failed (only bridged calls).");
18493 return -1;
18495 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Delay hangup */
18498 /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
18499 servers - generate an INVITE with Replaces. Either way, let the dial plan decided */
18500 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
18502 if (!res) {
18503 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",
18504 current.chan1->name,
18505 current.chan1->uniqueid,
18506 p->callid,
18507 current.chan2->name,
18508 current.chan2->uniqueid,
18509 p->refer->refer_to, p->refer->refer_to_context);
18510 /* Success - we have a new channel */
18511 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
18512 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
18513 if (p->refer->localtransfer)
18514 p->refer->status = REFER_200OK;
18515 if (p->owner)
18516 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18517 append_history(p, "Xfer", "Refer succeeded.");
18518 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
18519 /* Do not hangup call, the other side do that when we say 200 OK */
18520 /* We could possibly implement a timer here, auto congestion */
18521 res = 0;
18522 } else {
18523 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
18524 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
18525 append_history(p, "Xfer", "Refer failed.");
18526 /* Failure of some kind */
18527 p->refer->status = REFER_FAILED;
18528 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
18529 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
18530 res = -1;
18532 return res;
18535 /*! \brief Handle incoming CANCEL request */
18536 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
18539 check_via(p, req);
18540 sip_alreadygone(p);
18542 /* At this point, we could have cancelled the invite at the same time
18543 as the other side sends a CANCEL. Our final reply with error code
18544 might not have been received by the other side before the CANCEL
18545 was sent, so let's just give up retransmissions and waiting for
18546 ACK on our error code. The call is hanging up any way. */
18547 if (p->invitestate == INV_TERMINATED)
18548 __sip_pretend_ack(p);
18549 else
18550 p->invitestate = INV_CANCELLED;
18552 if (p->owner && p->owner->_state == AST_STATE_UP) {
18553 /* This call is up, cancel is ignored, we need a bye */
18554 transmit_response(p, "200 OK", req);
18555 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
18556 return 0;
18559 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
18560 update_call_counter(p, DEC_CALL_LIMIT);
18562 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18563 if (p->owner)
18564 ast_queue_hangup(p->owner);
18565 else
18566 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18567 if (p->initreq.len > 0) {
18568 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
18569 transmit_response(p, "200 OK", req);
18570 return 1;
18571 } else {
18572 transmit_response(p, "481 Call Leg Does Not Exist", req);
18573 return 0;
18577 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
18579 struct sip_pvt *p = chan->tech_pvt;
18580 char *all = "", *parse = ast_strdupa(preparse);
18581 int res = 0;
18582 AST_DECLARE_APP_ARGS(args,
18583 AST_APP_ARG(param);
18584 AST_APP_ARG(type);
18585 AST_APP_ARG(field);
18587 AST_STANDARD_APP_ARGS(args, parse);
18589 /* Sanity check */
18590 if (!IS_SIP_TECH(chan->tech)) {
18591 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
18592 return 0;
18595 memset(buf, 0, buflen);
18597 if (!strcasecmp(args.param, "peerip")) {
18598 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
18599 } else if (!strcasecmp(args.param, "recvip")) {
18600 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
18601 } else if (!strcasecmp(args.param, "from")) {
18602 ast_copy_string(buf, p->from, buflen);
18603 } else if (!strcasecmp(args.param, "uri")) {
18604 ast_copy_string(buf, p->uri, buflen);
18605 } else if (!strcasecmp(args.param, "useragent")) {
18606 ast_copy_string(buf, p->useragent, buflen);
18607 } else if (!strcasecmp(args.param, "peername")) {
18608 ast_copy_string(buf, p->peername, buflen);
18609 } else if (!strcasecmp(args.param, "t38passthrough")) {
18610 if (p->t38.state == T38_DISABLED) {
18611 ast_copy_string(buf, "0", sizeof("0"));
18612 } else { /* T38 is offered or enabled in this call */
18613 ast_copy_string(buf, "1", sizeof("1"));
18615 } else if (!strcasecmp(args.param, "rtpdest")) {
18616 struct sockaddr_in sin;
18618 if (ast_strlen_zero(args.type))
18619 args.type = "audio";
18621 if (!strcasecmp(args.type, "audio"))
18622 ast_rtp_get_peer(p->rtp, &sin);
18623 else if (!strcasecmp(args.type, "video"))
18624 ast_rtp_get_peer(p->vrtp, &sin);
18625 else if (!strcasecmp(args.type, "text"))
18626 ast_rtp_get_peer(p->trtp, &sin);
18627 else
18628 return -1;
18630 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
18631 } else if (!strcasecmp(args.param, "rtpqos")) {
18632 struct ast_rtp_quality qos;
18633 struct ast_rtp *rtp = p->rtp;
18635 memset(&qos, 0, sizeof(qos));
18637 if (ast_strlen_zero(args.type))
18638 args.type = "audio";
18639 if (ast_strlen_zero(args.field))
18640 args.field = "all";
18642 if (strcasecmp(args.type, "AUDIO") == 0) {
18643 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
18644 } else if (strcasecmp(args.type, "VIDEO") == 0) {
18645 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
18646 } else if (strcasecmp(args.type, "TEXT") == 0) {
18647 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
18648 } else {
18649 return -1;
18652 if (strcasecmp(args.field, "local_ssrc") == 0)
18653 snprintf(buf, buflen, "%u", qos.local_ssrc);
18654 else if (strcasecmp(args.field, "local_lostpackets") == 0)
18655 snprintf(buf, buflen, "%u", qos.local_lostpackets);
18656 else if (strcasecmp(args.field, "local_jitter") == 0)
18657 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
18658 else if (strcasecmp(args.field, "local_count") == 0)
18659 snprintf(buf, buflen, "%u", qos.local_count);
18660 else if (strcasecmp(args.field, "remote_ssrc") == 0)
18661 snprintf(buf, buflen, "%u", qos.remote_ssrc);
18662 else if (strcasecmp(args.field, "remote_lostpackets") == 0)
18663 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
18664 else if (strcasecmp(args.field, "remote_jitter") == 0)
18665 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
18666 else if (strcasecmp(args.field, "remote_count") == 0)
18667 snprintf(buf, buflen, "%u", qos.remote_count);
18668 else if (strcasecmp(args.field, "rtt") == 0)
18669 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
18670 else if (strcasecmp(args.field, "all") == 0)
18671 ast_copy_string(buf, all, buflen);
18672 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
18674 else {
18675 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
18676 return -1;
18678 } else {
18679 res = -1;
18681 return res;
18684 /*! \brief Handle incoming BYE request */
18685 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
18687 struct ast_channel *c=NULL;
18688 int res;
18689 struct ast_channel *bridged_to;
18691 /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
18692 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore && !p->owner) {
18693 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
18696 p->invitestate = INV_TERMINATED;
18698 copy_request(&p->initreq, req);
18699 if (sipdebug)
18700 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18701 check_via(p, req);
18702 sip_alreadygone(p);
18704 /* Get RTCP quality before end of call */
18705 if (p->do_history || p->owner) {
18706 struct ast_channel *bridge = ast_bridged_channel(p->owner);
18707 char *videoqos, *textqos;
18709 if (p->rtp) {
18710 if (p->do_history) {
18711 char *audioqos,
18712 *audioqos_jitter,
18713 *audioqos_loss,
18714 *audioqos_rtt;
18716 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
18717 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
18718 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
18719 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
18721 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
18722 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
18723 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
18724 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
18727 ast_rtp_set_vars(p->owner, p->rtp);
18730 if (bridge) {
18731 struct sip_pvt *q = bridge->tech_pvt;
18733 if (IS_SIP_TECH(bridge->tech) && q->rtp)
18734 ast_rtp_set_vars(bridge, q->rtp);
18737 if (p->vrtp) {
18738 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
18739 if (p->do_history)
18740 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
18741 if (p->owner)
18742 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
18745 if (p->trtp) {
18746 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
18747 if (p->do_history)
18748 append_history(p, "RTCPtext", "Quality:%s", textqos);
18749 if (p->owner)
18750 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
18754 stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18755 stop_session_timer(p); /* Stop Session-Timer */
18757 if (!ast_strlen_zero(get_header(req, "Also"))) {
18758 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
18759 ast_inet_ntoa(p->recv.sin_addr));
18760 if (ast_strlen_zero(p->context))
18761 ast_string_field_set(p, context, default_context);
18762 res = get_also_info(p, req);
18763 if (!res) {
18764 c = p->owner;
18765 if (c) {
18766 bridged_to = ast_bridged_channel(c);
18767 if (bridged_to) {
18768 /* Don't actually hangup here... */
18769 ast_queue_control(c, AST_CONTROL_UNHOLD);
18770 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
18771 } else
18772 ast_queue_hangup(p->owner);
18774 } else {
18775 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
18776 if (p->owner)
18777 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18779 } else if (p->owner) {
18780 ast_queue_hangup(p->owner);
18781 ast_debug(3, "Received bye, issuing owner hangup\n");
18782 } else {
18783 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18784 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
18786 transmit_response(p, "200 OK", req);
18788 return 1;
18791 /*! \brief Handle incoming MESSAGE request */
18792 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
18794 if (!req->ignore) {
18795 if (req->debug)
18796 ast_verbose("Receiving message!\n");
18797 receive_message(p, req);
18798 } else
18799 transmit_response(p, "202 Accepted", req);
18800 return 1;
18803 static void add_peer_mwi_subs(struct sip_peer *peer)
18805 struct sip_mailbox *mailbox;
18807 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
18808 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
18809 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
18810 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
18811 AST_EVENT_IE_END);
18815 /*! \brief Handle incoming SUBSCRIBE request */
18816 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
18818 int gotdest;
18819 int res = 0;
18820 int firststate = AST_EXTENSION_REMOVED;
18821 struct sip_peer *authpeer = NULL;
18822 const char *eventheader = get_header(req, "Event"); /* Get Event package name */
18823 const char *accept = get_header(req, "Accept");
18824 int resubscribe = (p->subscribed != NONE);
18825 char *temp, *event;
18826 struct ao2_iterator i;
18828 if (p->initreq.headers) {
18829 /* We already have a dialog */
18830 if (p->initreq.method != SIP_SUBSCRIBE) {
18831 /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
18832 /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
18833 transmit_response(p, "403 Forbidden (within dialog)", req);
18834 /* Do not destroy session, since we will break the call if we do */
18835 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);
18836 return 0;
18837 } else if (req->debug) {
18838 if (resubscribe)
18839 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
18840 else
18841 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
18845 /* Check if we have a global disallow setting on subscriptions.
18846 if so, we don't have to check peer/user settings after auth, which saves a lot of processing
18848 if (!global_allowsubscribe) {
18849 transmit_response(p, "403 Forbidden (policy)", req);
18850 p->needdestroy = 1;
18851 return 0;
18854 if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
18855 const char *to = get_header(req, "To");
18856 char totag[128];
18858 /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
18859 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
18860 if (req->debug)
18861 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
18862 transmit_response(p, "481 Subscription does not exist", req);
18863 p->needdestroy = 1;
18864 return 0;
18867 /* Use this as the basis */
18868 if (req->debug)
18869 ast_verbose("Creating new subscription\n");
18871 copy_request(&p->initreq, req);
18872 if (sipdebug)
18873 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18874 check_via(p, req);
18875 } else if (req->debug && req->ignore)
18876 ast_verbose("Ignoring this SUBSCRIBE request\n");
18878 /* Find parameters to Event: header value and remove them for now */
18879 if (ast_strlen_zero(eventheader)) {
18880 transmit_response(p, "489 Bad Event", req);
18881 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
18882 p->needdestroy = 1;
18883 return 0;
18886 if ( (strchr(eventheader, ';'))) {
18887 event = ast_strdupa(eventheader); /* Since eventheader is a const, we can't change it */
18888 temp = strchr(event, ';');
18889 *temp = '\0'; /* Remove any options for now */
18890 /* We might need to use them later :-) */
18891 } else
18892 event = (char *) eventheader; /* XXX is this legal ? */
18894 /* Handle authentication */
18895 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
18896 /* if an authentication response was sent, we are done here */
18897 if (res == AUTH_CHALLENGE_SENT) /* authpeer = NULL here */
18898 return 0;
18899 if (res < 0) {
18900 if (res == AUTH_FAKE_AUTH) {
18901 ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
18902 transmit_fake_auth_response(p, req, 1);
18903 } else {
18904 ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
18905 transmit_response_reliable(p, "403 Forbidden", req);
18907 p->needdestroy = 1;
18908 return 0;
18911 /* At this point, authpeer cannot be NULL. Remember we hold a reference,
18912 * so we must release it when done.
18913 * XXX must remove all the checks for authpeer == NULL.
18916 /* Check if this user/peer is allowed to subscribe at all */
18917 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
18918 transmit_response(p, "403 Forbidden (policy)", req);
18919 p->needdestroy = 1;
18920 if (authpeer)
18921 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
18922 return 0;
18925 /* Get destination right away */
18926 gotdest = get_destination(p, NULL);
18928 /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
18929 parse_ok_contact(p, req);
18931 build_contact(p);
18932 if (strcmp(event, "message-summary") && gotdest) {
18933 transmit_response(p, "404 Not Found", req);
18934 p->needdestroy = 1;
18935 if (authpeer)
18936 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
18937 return 0;
18940 /* Initialize tag for new subscriptions */
18941 if (ast_strlen_zero(p->tag))
18942 make_our_tag(p->tag, sizeof(p->tag));
18944 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
18945 if (authpeer) /* We do not need the authpeer any more */
18946 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
18948 /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
18949 /* Polycom phones only handle xpidf+xml, even if they say they can
18950 handle pidf+xml as well
18952 if (strstr(p->useragent, "Polycom")) {
18953 p->subscribed = XPIDF_XML;
18954 } else if (strstr(accept, "application/pidf+xml")) {
18955 p->subscribed = PIDF_XML; /* RFC 3863 format */
18956 } else if (strstr(accept, "application/dialog-info+xml")) {
18957 p->subscribed = DIALOG_INFO_XML;
18958 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
18959 } else if (strstr(accept, "application/cpim-pidf+xml")) {
18960 p->subscribed = CPIM_PIDF_XML; /* RFC 3863 format */
18961 } else if (strstr(accept, "application/xpidf+xml")) {
18962 p->subscribed = XPIDF_XML; /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
18963 } else if (ast_strlen_zero(accept)) {
18964 if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
18965 transmit_response(p, "489 Bad Event", req);
18967 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
18968 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
18969 p->needdestroy = 1;
18970 return 0;
18972 /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
18973 so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
18974 } else {
18975 /* Can't find a format for events that we know about */
18976 char mybuf[200];
18977 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", accept);
18978 transmit_response(p, mybuf, req);
18980 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
18981 accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
18982 p->needdestroy = 1;
18983 return 0;
18985 } else if (!strcmp(event, "message-summary")) {
18986 if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
18987 /* Format requested that we do not support */
18988 transmit_response(p, "406 Not Acceptable", req);
18989 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
18990 p->needdestroy = 1;
18991 if (authpeer)
18992 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
18993 return 0;
18995 /* Looks like they actually want a mailbox status
18996 This version of Asterisk supports mailbox subscriptions
18997 The subscribed URI needs to exist in the dial plan
18998 In most devices, this is configurable to the voicemailmain extension you use
19000 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
19001 transmit_response(p, "404 Not found (no mailbox)", req);
19002 p->needdestroy = 1;
19003 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
19004 if (authpeer)
19005 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
19006 return 0;
19009 p->subscribed = MWI_NOTIFICATION;
19010 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
19011 add_peer_mwi_subs(authpeer);
19013 if (authpeer->mwipvt && authpeer->mwipvt != p) { /* Destroy old PVT if this is a new one */
19014 /* We only allow one subscription per peer */
19015 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
19016 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
19017 /* sip_destroy(authpeer->mwipvt); */
19019 if (authpeer->mwipvt)
19020 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
19021 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p"); /* Link from peer to pvt UH- should this be dialog_ref()? */
19022 if (p->relatedpeer)
19023 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
19024 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer"); /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
19025 /* Do not release authpeer here */
19026 } else { /* At this point, Asterisk does not understand the specified event */
19027 transmit_response(p, "489 Bad Event", req);
19028 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
19029 p->needdestroy = 1;
19030 if (authpeer)
19031 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
19032 return 0;
19035 /* Add subscription for extension state from the PBX core */
19036 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
19037 if (p->stateid > -1) {
19038 ast_extension_state_del(p->stateid, cb_extensionstate);
19039 /* we need to dec the refcount, now that the extensionstate is removed */
19040 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
19042 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
19045 if (!req->ignore && p)
19046 p->lastinvite = seqno;
19047 if (p && !p->needdestroy) {
19048 p->expiry = atoi(get_header(req, "Expires"));
19050 /* check if the requested expiry-time is within the approved limits from sip.conf */
19051 if (p->expiry > max_expiry)
19052 p->expiry = max_expiry;
19053 if (p->expiry < min_expiry && p->expiry > 0)
19054 p->expiry = min_expiry;
19056 if (sipdebug) {
19057 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
19058 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
19059 else
19060 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
19062 if (p->autokillid > -1 && sip_cancel_destroy(p)) /* Remove subscription expiry for renewals */
19063 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19064 if (p->expiry > 0)
19065 sip_scheddestroy(p, (p->expiry + 10) * 1000); /* Set timer for destruction of call at expiration */
19067 if (p->subscribed == MWI_NOTIFICATION) {
19068 transmit_response(p, "200 OK", req);
19069 if (p->relatedpeer) { /* Send first notification */
19070 ao2_lock(p->relatedpeer); /* was WRLOCK */
19071 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
19072 ao2_unlock(p->relatedpeer);
19074 } else {
19075 struct sip_pvt *p_old;
19077 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
19079 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));
19080 transmit_response(p, "404 Not found", req);
19081 p->needdestroy = 1;
19082 return 0;
19085 transmit_response(p, "200 OK", req);
19086 transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
19087 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
19088 /* hide the 'complete' exten/context in the refer_to field for later display */
19089 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
19091 /* remove any old subscription from this peer for the same exten/context,
19092 as the peer has obviously forgotten about it and it's wasteful to wait
19093 for it to expire and send NOTIFY messages to the peer only to have them
19094 ignored (or generate errors)
19096 i = ao2_iterator_init(dialogs, 0);
19098 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19099 if (p_old == p) {
19100 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19101 continue;
19103 if (p_old->initreq.method != SIP_SUBSCRIBE) {
19104 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19105 continue;
19107 if (p_old->subscribed == NONE) {
19108 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19109 continue;
19111 sip_pvt_lock(p_old);
19112 if (!strcmp(p_old->username, p->username)) {
19113 if (!strcmp(p_old->exten, p->exten) &&
19114 !strcmp(p_old->context, p->context)) {
19115 p_old->needdestroy = 1;
19116 sip_pvt_unlock(p_old);
19117 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
19118 break;
19121 sip_pvt_unlock(p_old);
19122 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
19125 if (!p->expiry)
19126 p->needdestroy = 1;
19128 return 1;
19131 /*! \brief Handle incoming REGISTER request */
19132 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
19134 enum check_auth_result res;
19136 /* Use this as the basis */
19137 copy_request(&p->initreq, req);
19138 if (sipdebug)
19139 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19140 check_via(p, req);
19141 if ((res = register_verify(p, sin, req, e)) < 0) {
19142 const char *reason;
19144 switch (res) {
19145 case AUTH_SECRET_FAILED:
19146 reason = "Wrong password";
19147 break;
19148 case AUTH_USERNAME_MISMATCH:
19149 reason = "Username/auth name mismatch";
19150 break;
19151 case AUTH_NOT_FOUND:
19152 reason = "No matching peer found";
19153 break;
19154 case AUTH_UNKNOWN_DOMAIN:
19155 reason = "Not a local domain";
19156 break;
19157 case AUTH_PEER_NOT_DYNAMIC:
19158 reason = "Peer is not supposed to register";
19159 break;
19160 case AUTH_ACL_FAILED:
19161 reason = "Device does not match ACL";
19162 break;
19163 default:
19164 reason = "Unknown failure";
19165 break;
19167 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
19168 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
19169 reason);
19170 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
19171 } else
19172 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
19174 if (res < 1) {
19175 /* Destroy the session, but keep us around for just a bit in case they don't
19176 get our 200 OK */
19177 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19179 return res;
19182 /*! \brief Handle incoming SIP requests (methods)
19183 \note This is where all incoming requests go first */
19184 /* called with p and p->owner locked */
19185 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
19187 /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
19188 relatively static */
19189 const char *cmd;
19190 const char *cseq;
19191 const char *useragent;
19192 int seqno;
19193 int len;
19194 int respid;
19195 int res = 0;
19196 int debug = sip_debug_test_pvt(p);
19197 char *e;
19198 int error = 0;
19200 /* Get Method and Cseq */
19201 cseq = get_header(req, "Cseq");
19202 cmd = req->header[0];
19204 /* Must have Cseq */
19205 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
19206 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
19207 error = 1;
19209 if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
19210 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
19211 error = 1;
19213 if (error) {
19214 if (!p->initreq.headers) /* New call */
19215 p->needdestroy = 1; /* Make sure we destroy this dialog */
19216 return -1;
19218 /* Get the command XXX */
19220 cmd = req->rlPart1;
19221 e = req->rlPart2;
19223 /* Save useragent of the client */
19224 useragent = get_header(req, "User-Agent");
19225 if (!ast_strlen_zero(useragent))
19226 ast_string_field_set(p, useragent, useragent);
19228 /* Find out SIP method for incoming request */
19229 if (req->method == SIP_RESPONSE) { /* Response to our request */
19230 /* When we get here, we know this is a SIP dialog where we've sent
19231 * a request and have a response, or at least get a response
19232 * within an existing dialog. Do some sanity checks, then
19233 * possibly process the request. In all cases, there function
19234 * terminates at the end of this block
19236 int ret = 0;
19238 if (p->ocseq < seqno && seqno != p->lastnoninvite) {
19239 ast_debug(1, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
19240 ret = -1;
19241 } else if (p->ocseq != seqno && seqno != p->lastnoninvite) {
19242 /* ignore means "don't do anything with it" but still have to
19243 * respond appropriately.
19244 * But in this case this is a response already, so we really
19245 * have nothing to do with this message, and even setting the
19246 * ignore flag is pointless.
19248 req->ignore = 1;
19249 append_history(p, "Ignore", "Ignoring this retransmit\n");
19250 } else if (e) {
19251 e = ast_skip_blanks(e);
19252 if (sscanf(e, "%d %n", &respid, &len) != 1) {
19253 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
19254 /* XXX maybe should do ret = -1; */
19255 } else if (respid <= 0) {
19256 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
19257 /* XXX maybe should do ret = -1; */
19258 } else { /* finally, something worth processing */
19259 /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
19260 if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
19261 extract_uri(p, req);
19262 handle_response(p, respid, e + len, req, seqno);
19265 return 0;
19268 /* New SIP request coming in
19269 (could be new request in existing SIP dialog as well...)
19272 p->method = req->method; /* Find out which SIP method they are using */
19273 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
19275 if (p->icseq && (p->icseq > seqno) ) {
19276 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
19277 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
19278 } else {
19279 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
19280 if (req->method != SIP_ACK)
19281 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
19282 return -1;
19284 } else if (p->icseq &&
19285 p->icseq == seqno &&
19286 req->method != SIP_ACK &&
19287 (p->method != SIP_CANCEL || p->alreadygone)) {
19288 /* ignore means "don't do anything with it" but still have to
19289 respond appropriately. We do this if we receive a repeat of
19290 the last sequence number */
19291 req->ignore = 1;
19292 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
19295 if (seqno >= p->icseq)
19296 /* Next should follow monotonically (but not necessarily
19297 incrementally -- thanks again to the genius authors of SIP --
19298 increasing */
19299 p->icseq = seqno;
19301 /* Find their tag if we haven't got it */
19302 if (ast_strlen_zero(p->theirtag)) {
19303 char tag[128];
19305 gettag(req, "From", tag, sizeof(tag));
19306 ast_string_field_set(p, theirtag, tag);
19308 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
19310 if (pedanticsipchecking) {
19311 /* If this is a request packet without a from tag, it's not
19312 correct according to RFC 3261 */
19313 /* Check if this a new request in a new dialog with a totag already attached to it,
19314 RFC 3261 - section 12.2 - and we don't want to mess with recovery */
19315 if (!p->initreq.headers && req->has_to_tag) {
19316 /* If this is a first request and it got a to-tag, it is not for us */
19317 if (!req->ignore && req->method == SIP_INVITE) {
19318 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
19319 /* Will cease to exist after ACK */
19320 } else if (req->method != SIP_ACK) {
19321 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
19322 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19323 } else {
19324 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
19326 return res;
19330 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
19331 transmit_response(p, "400 Bad request", req);
19332 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19333 return -1;
19336 /* Handle various incoming SIP methods in requests */
19337 switch (p->method) {
19338 case SIP_OPTIONS:
19339 res = handle_request_options(p, req);
19340 break;
19341 case SIP_INVITE:
19342 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
19343 break;
19344 case SIP_REFER:
19345 res = handle_request_refer(p, req, debug, seqno, nounlock);
19346 break;
19347 case SIP_CANCEL:
19348 res = handle_request_cancel(p, req);
19349 break;
19350 case SIP_BYE:
19351 res = handle_request_bye(p, req);
19352 break;
19353 case SIP_MESSAGE:
19354 res = handle_request_message(p, req);
19355 break;
19356 case SIP_SUBSCRIBE:
19357 res = handle_request_subscribe(p, req, sin, seqno, e);
19358 break;
19359 case SIP_REGISTER:
19360 res = handle_request_register(p, req, sin, e);
19361 break;
19362 case SIP_INFO:
19363 if (req->debug)
19364 ast_verbose("Receiving INFO!\n");
19365 if (!req->ignore)
19366 handle_request_info(p, req);
19367 else /* if ignoring, transmit response */
19368 transmit_response(p, "200 OK", req);
19369 break;
19370 case SIP_NOTIFY:
19371 res = handle_request_notify(p, req, sin, seqno, e);
19372 break;
19373 case SIP_ACK:
19374 /* Make sure we don't ignore this */
19375 if (seqno == p->pendinginvite) {
19376 p->invitestate = INV_TERMINATED;
19377 p->pendinginvite = 0;
19378 __sip_ack(p, seqno, 1 /* response */, 0);
19379 if (find_sdp(req)) {
19380 if (process_sdp(p, req, SDP_T38_NONE))
19381 return -1;
19383 check_pendings(p);
19385 /* Got an ACK that we did not match. Ignore silently */
19386 if (!p->lastinvite && ast_strlen_zero(p->randdata))
19387 p->needdestroy = 1;
19388 break;
19389 default:
19390 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
19391 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
19392 cmd, ast_inet_ntoa(p->sa.sin_addr));
19393 /* If this is some new method, and we don't have a call, destroy it now */
19394 if (!p->initreq.headers)
19395 p->needdestroy = 1;
19396 break;
19398 return res;
19401 /*! \brief Read data from SIP socket
19402 \note sipsock_read locks the owner channel while we are processing the SIP message
19403 \return 1 on error, 0 on success
19404 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
19406 static int sipsock_read(int *id, int fd, short events, void *ignore)
19408 struct sip_request req;
19409 struct sockaddr_in sin = { 0, };
19410 int res;
19411 socklen_t len = sizeof(sin);
19412 static char readbuf[65535];
19414 memset(&req, 0, sizeof(req));
19415 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
19416 if (res < 0) {
19417 #if !defined(__FreeBSD__)
19418 if (errno == EAGAIN)
19419 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
19420 else
19421 #endif
19422 if (errno != ECONNREFUSED)
19423 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
19424 return 1;
19426 readbuf[res] = '\0';
19427 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
19428 return 1;
19429 ast_str_set(&req.data, 0, "%s", readbuf);
19430 if (res == sizeof(req.data) - 1) {
19431 ast_debug(1, "Received packet exceeds buffer. Data is possibly lost\n");
19432 req.data->str[sizeof(req.data) - 1] = '\0';
19433 } else
19434 req.data->str[res] = '\0';
19435 req.len = res;
19437 req.socket.fd = sipsock;
19438 req.socket.type = SIP_TRANSPORT_UDP;
19439 req.socket.ser = NULL;
19440 req.socket.port = bindaddr.sin_port;
19442 handle_request_do(&req, &sin);
19443 if (req.data) {
19444 ast_free(req.data);
19445 req.data = NULL;
19448 return 1;
19451 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
19453 struct sip_pvt *p;
19454 int recount = 0;
19455 int nounlock = 0;
19456 int lockretry;
19458 if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
19459 req->debug = 1;
19460 if (pedanticsipchecking)
19461 req->len = lws2sws(req->data->str, req->len); /* Fix multiline headers */
19462 if (req->debug) {
19463 ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n",
19464 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
19465 ntohs(sin->sin_port), req->data->str);
19468 if(parse_request(req) == -1) { /* Bad packet, can't parse */
19469 ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
19470 return 1;
19473 req->method = find_sip_method(req->rlPart1);
19475 if (req->debug)
19476 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
19478 if (req->headers < 2) { /* Must have at least two headers */
19479 ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
19480 return 1;
19483 /* Process request, with netlock held, and with usual deadlock avoidance */
19484 for (lockretry = 100; lockretry > 0; lockretry--) {
19485 ast_mutex_lock(&netlock);
19487 /* Find the active SIP dialog or create a new one */
19488 p = find_call(req, sin, req->method); /* returns p locked */
19489 if (p == NULL) {
19490 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
19491 ast_mutex_unlock(&netlock);
19492 return 1;
19495 copy_socket_data(&p->socket, &req->socket);
19497 /* Go ahead and lock the owner if it has one -- we may need it */
19498 /* becaues this is deadlock-prone, we need to try and unlock if failed */
19499 if (!p->owner || !ast_channel_trylock(p->owner))
19500 break; /* locking succeeded */
19501 ast_debug(1, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
19502 sip_pvt_unlock(p);
19503 if (lockretry != 1)
19504 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
19505 ast_mutex_unlock(&netlock);
19506 /* Sleep for a very short amount of time */
19507 usleep(1);
19509 p->recv = *sin;
19511 if (p->do_history) /* This is a request or response, note what it was for */
19512 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), req->rlPart2);
19514 if (!lockretry) {
19515 if (p->owner)
19516 ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
19517 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
19518 if (req->method != SIP_ACK)
19519 transmit_response(p, "503 Server error", req); /* We must respond according to RFC 3261 sec 12.2 */
19520 /* XXX We could add retry-after to make sure they come back */
19521 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
19522 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
19523 return 1;
19526 nounlock = 0;
19527 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
19528 /* Request failed */
19529 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
19532 if (recount)
19533 ast_update_use_count();
19535 if (p->owner && !nounlock)
19536 ast_channel_unlock(p->owner);
19537 sip_pvt_unlock(p);
19538 ast_mutex_unlock(&netlock);
19539 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
19540 return 1;
19543 /*! \brief Returns the port to use for this socket */
19544 static int sip_standard_port(struct sip_socket s)
19546 if (s.type & SIP_TRANSPORT_TLS)
19547 return s.port == htons(STANDARD_TLS_PORT);
19548 else
19549 return s.port == htons(STANDARD_SIP_PORT);
19552 /*! \todo document this function. */
19553 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
19555 struct sip_threadinfo *th;
19557 AST_LIST_LOCK(&threadl);
19558 AST_LIST_TRAVERSE(&threadl, th, list) {
19559 if ((s->sin_family == th->ser->requestor.sin_family) &&
19560 (s->sin_addr.s_addr == th->ser->requestor.sin_addr.s_addr) &&
19561 (s->sin_port == th->ser->requestor.sin_port)) {
19562 AST_LIST_UNLOCK(&threadl);
19563 return th->ser;
19566 AST_LIST_UNLOCK(&threadl);
19567 return NULL;
19570 /*! \todo document this function. */
19571 static int sip_prepare_socket(struct sip_pvt *p)
19573 struct sip_socket *s = &p->socket;
19574 static const char name[] = "SIP socket";
19575 struct ast_tcptls_session_instance *ser;
19576 struct server_args ca = {
19577 .name = name,
19578 .accept_fd = -1,
19581 if (s->fd != -1)
19582 return s->fd;
19584 if (s->type & SIP_TRANSPORT_UDP) {
19585 s->fd = sipsock;
19586 return s->fd;
19589 ca.sin = *(sip_real_dst(p));
19591 if ((ser = sip_tcp_locate(&ca.sin))) {
19592 s->fd = ser->fd;
19593 if (s->ser) {
19594 ao2_ref(s->ser, -1);
19595 s->ser = NULL;
19597 ao2_ref(ser, +1);
19598 s->ser = ser;
19599 return s->fd;
19602 if (s->ser && s->ser->parent->tls_cfg) {
19603 ca.tls_cfg = s->ser->parent->tls_cfg;
19604 } else {
19605 if (s->type & SIP_TRANSPORT_TLS) {
19606 ca.tls_cfg = ast_calloc(1, sizeof(*ca.tls_cfg));
19607 if (!ca.tls_cfg)
19608 return -1;
19609 memcpy(ca.tls_cfg, &default_tls_cfg, sizeof(*ca.tls_cfg));
19610 if (!ast_strlen_zero(p->tohost))
19611 ast_copy_string(ca.hostname, p->tohost, sizeof(ca.hostname));
19615 if (s->ser) {
19616 /* the pvt socket already has a server instance ... */
19617 } else {
19618 s->ser = ast_tcptls_client_start(&ca);
19621 if (!s->ser) {
19622 if (ca.tls_cfg)
19623 ast_free(ca.tls_cfg);
19624 return -1;
19627 s->fd = ca.accept_fd;
19629 /* Give the new thread a reference */
19630 ao2_ref(s->ser, +1);
19632 if (ast_pthread_create_background(&ca.master, NULL, sip_tcp_worker_fn, s->ser)) {
19633 ast_debug(1, "Unable to launch '%s'.", ca.name);
19634 ao2_ref(s->ser, -1);
19635 close(ca.accept_fd);
19636 s->fd = ca.accept_fd = -1;
19639 return s->fd;
19643 * \brief Get cached MWI info
19644 * \retval 0 At least one message is waiting
19645 * \retval 1 no messages waiting
19647 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
19649 struct sip_mailbox *mailbox;
19651 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
19652 struct ast_event *event;
19653 event = ast_event_get_cached(AST_EVENT_MWI,
19654 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
19655 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
19656 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
19657 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
19658 AST_EVENT_IE_END);
19659 if (!event)
19660 continue;
19661 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
19662 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
19663 ast_event_destroy(event);
19666 return (*new || *old) ? 0 : 1;
19669 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
19670 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
19672 /* Called with peerl lock, but releases it */
19673 struct sip_pvt *p;
19674 int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;
19676 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
19677 return 0;
19679 /* Do we have an IP address? If not, skip this peer */
19680 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
19681 return 0;
19683 if (event) {
19684 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
19685 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
19686 } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
19687 /* got it! Don't keep looking. */
19688 } else if (cache_only) {
19689 return 0;
19690 } else { /* Fall back to manually checking the mailbox */
19691 struct ast_str *mailbox_str = ast_str_alloca(512);
19692 peer_mailboxes_to_str(&mailbox_str, peer);
19693 ast_app_inboxcount(mailbox_str->str, &urgentmsgs, &newmsgs, &oldmsgs);
19696 if (peer->mwipvt) {
19697 /* Base message on subscription */
19698 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
19699 } else {
19700 /* Build temporary dialog for this message */
19701 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY)))
19702 return -1;
19703 if (create_addr_from_peer(p, peer)) {
19704 /* Maybe they're not registered, etc. */
19705 dialog_unlink_all(p, TRUE, TRUE);
19706 dialog_unref(p, "unref dialog p just created via sip_alloc");
19707 /* sip_destroy(p); */
19708 return 0;
19710 /* Recalculate our side, and recalculate Call ID */
19711 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
19712 build_via(p);
19713 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
19714 build_callid_pvt(p);
19715 ao2_t_link(dialogs, p, "Linking in under new name");
19716 /* Destroy this session after 32 secs */
19717 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19720 /* Send MWI */
19721 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19722 /* the following will decrement the refcount on p as it finishes */
19723 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
19724 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
19725 return 0;
19728 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
19729 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
19731 /* If we have no RTP or no active owner, no need to check timers */
19732 if (!dialog->rtp || !dialog->owner)
19733 return;
19734 /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
19736 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
19737 return;
19739 /* If the call is involved in a T38 fax session do not check RTP timeout */
19740 if (dialog->t38.state == T38_ENABLED)
19741 return;
19743 /* If we have no timers set, return now */
19744 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
19745 return;
19747 /* Check AUDIO RTP keepalives */
19748 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
19749 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
19750 /* Need to send an empty RTP packet */
19751 dialog->lastrtptx = time(NULL);
19752 ast_rtp_sendcng(dialog->rtp, 0);
19755 /*! \todo Check video RTP keepalives
19757 Do we need to move the lastrtptx to the RTP structure to have one for audio and one
19758 for video? It really does belong to the RTP structure.
19761 /* Check AUDIO RTP timers */
19762 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
19763 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
19765 /* Might be a timeout now -- see if we're on hold */
19766 struct sockaddr_in sin;
19767 ast_rtp_get_peer(dialog->rtp, &sin);
19768 if (sin.sin_addr.s_addr || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
19769 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
19770 /* Needs a hangup */
19771 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
19772 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
19773 sip_pvt_unlock(dialog);
19774 usleep(1);
19775 sip_pvt_lock(dialog);
19777 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
19778 dialog->owner->name, (long) (t - dialog->lastrtprx));
19779 /* Issue a softhangup */
19780 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
19781 ast_channel_unlock(dialog->owner);
19782 /* forget the timeouts for this call, since a hangup
19783 has already been requested and we don't want to
19784 repeatedly request hangups
19786 ast_rtp_set_rtptimeout(dialog->rtp, 0);
19787 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
19788 if (dialog->vrtp) {
19789 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
19790 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
19797 /*! \brief The SIP monitoring thread
19798 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
19799 (and thus do not have a separate thread) indefinitely
19801 static void *do_monitor(void *data)
19803 int res;
19804 time_t t;
19805 int reloading;
19807 /* Add an I/O event to our SIP UDP socket */
19808 if (sipsock > -1)
19809 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
19811 /* From here on out, we die whenever asked */
19812 for(;;) {
19813 /* Check for a reload request */
19814 ast_mutex_lock(&sip_reload_lock);
19815 reloading = sip_reloading;
19816 sip_reloading = FALSE;
19817 ast_mutex_unlock(&sip_reload_lock);
19818 if (reloading) {
19819 ast_verb(1, "Reloading SIP\n");
19820 sip_do_reload(sip_reloadreason);
19822 /* Change the I/O fd of our UDP socket */
19823 if (sipsock > -1) {
19824 if (sipsock_read_id)
19825 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
19826 else
19827 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
19828 } else if (sipsock_read_id) {
19829 ast_io_remove(io, sipsock_read_id);
19830 sipsock_read_id = NULL;
19834 /* Check for dialogs needing to be killed */
19835 t = time(NULL);
19836 /* don't scan the dialogs list if it hasn't been a reasonable period
19837 of time since the last time we did it (when MWI is being sent, we can
19838 get back to this point every millisecond or less)
19840 ao2_t_callback(dialogs, OBJ_UNLINK|OBJ_NODATA, dialog_needdestroy, &t, "callback to remove dialogs w/needdestroy");
19842 /* the old methodology would be to restart the search for dialogs to delete with every
19843 dialog that was found and destroyed, probably because the list contents would change,
19844 so we'd need to restart. This isn't the best thing to do with callbacks. */
19846 pthread_testcancel();
19847 /* Wait for sched or io */
19848 res = ast_sched_wait(sched);
19849 if ((res < 0) || (res > 1000))
19850 res = 1000;
19851 res = ast_io_wait(io, res);
19852 if (res > 20)
19853 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
19854 ast_mutex_lock(&monlock);
19855 if (res >= 0) {
19856 res = ast_sched_runq(sched);
19857 if (res >= 20)
19858 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
19860 ast_mutex_unlock(&monlock);
19863 /* Never reached */
19864 return NULL;
19867 /*! \brief Start the channel monitor thread */
19868 static int restart_monitor(void)
19870 /* If we're supposed to be stopped -- stay stopped */
19871 if (monitor_thread == AST_PTHREADT_STOP)
19872 return 0;
19873 ast_mutex_lock(&monlock);
19874 if (monitor_thread == pthread_self()) {
19875 ast_mutex_unlock(&monlock);
19876 ast_log(LOG_WARNING, "Cannot kill myself\n");
19877 return -1;
19879 if (monitor_thread != AST_PTHREADT_NULL) {
19880 /* Wake up the thread */
19881 pthread_kill(monitor_thread, SIGURG);
19882 } else {
19883 /* Start a new monitor */
19884 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
19885 ast_mutex_unlock(&monlock);
19886 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
19887 return -1;
19890 ast_mutex_unlock(&monlock);
19891 return 0;
19895 /*! \brief Session-Timers: Restart session timer */
19896 static void restart_session_timer(struct sip_pvt *p)
19898 if (!p->stimer) {
19899 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
19900 return;
19903 if (p->stimer->st_active == TRUE) {
19904 AST_SCHED_DEL(sched, p->stimer->st_schedid);
19905 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
19906 start_session_timer(p);
19911 /*! \brief Session-Timers: Stop session timer */
19912 static void stop_session_timer(struct sip_pvt *p)
19914 if (!p->stimer) {
19915 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
19916 return;
19919 if (p->stimer->st_active == TRUE) {
19920 p->stimer->st_active = FALSE;
19921 AST_SCHED_DEL(sched, p->stimer->st_schedid);
19922 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
19927 /*! \brief Session-Timers: Start session timer */
19928 static void start_session_timer(struct sip_pvt *p)
19930 if (!p->stimer) {
19931 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
19932 return;
19935 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, p);
19936 if (p->stimer->st_schedid < 0) {
19937 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
19939 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
19943 /*! \brief Session-Timers: Process session refresh timeout event */
19944 static int proc_session_timer(const void *vp)
19946 struct sip_pvt *p = (struct sip_pvt *) vp;
19947 int sendreinv = FALSE;
19949 if (!p->stimer) {
19950 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
19951 return 0;
19954 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
19956 if (!p->owner) {
19957 if (p->stimer->st_active == TRUE) {
19958 stop_session_timer(p);
19960 return 0;
19963 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
19964 return 0;
19967 switch (p->stimer->st_ref) {
19968 case SESSION_TIMER_REFRESHER_UAC:
19969 if (p->outgoing_call == TRUE) {
19970 sendreinv = TRUE;
19972 break;
19973 case SESSION_TIMER_REFRESHER_UAS:
19974 if (p->outgoing_call != TRUE) {
19975 sendreinv = TRUE;
19977 break;
19978 default:
19979 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
19980 return -1;
19983 if (sendreinv == TRUE) {
19984 transmit_reinvite_with_sdp(p, FALSE, TRUE);
19985 } else {
19986 p->stimer->st_expirys++;
19987 if (p->stimer->st_expirys >= 2) {
19988 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
19989 stop_session_timer(p);
19991 while (p->owner && ast_channel_trylock(p->owner)) {
19992 sip_pvt_unlock(p);
19993 usleep(1);
19994 sip_pvt_lock(p);
19997 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
19998 ast_channel_unlock(p->owner);
20001 return 1;
20005 /*! \brief Session-Timers: Function for parsing Min-SE header */
20006 int parse_minse (const char *p_hdrval, int *const p_interval)
20008 if (ast_strlen_zero(p_hdrval)) {
20009 ast_log(LOG_WARNING, "Null Min-SE header\n");
20010 return -1;
20013 *p_interval = 0;
20014 p_hdrval = ast_skip_blanks(p_hdrval);
20015 if (!sscanf(p_hdrval, "%d", p_interval)) {
20016 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
20017 return -1;
20020 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
20021 return 0;
20025 /*! \brief Session-Timers: Function for parsing Session-Expires header */
20026 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
20028 char *p_token;
20029 int ref_idx;
20030 char *p_se_hdr;
20032 if (ast_strlen_zero(p_hdrval)) {
20033 ast_log(LOG_WARNING, "Null Session-Expires header\n");
20034 return -1;
20037 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
20038 *p_interval = 0;
20040 p_se_hdr = ast_strdupa(p_hdrval);
20041 p_se_hdr = ast_skip_blanks(p_se_hdr);
20043 while ((p_token = strsep(&p_se_hdr, ";"))) {
20044 p_token = ast_skip_blanks(p_token);
20045 if (!sscanf(p_token, "%d", p_interval)) {
20046 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
20047 return -1;
20050 ast_debug(2, "Session-Expires: %d\n", *p_interval);
20052 if (!p_se_hdr)
20053 continue;
20055 ref_idx = strlen("refresher=");
20056 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
20057 p_se_hdr += ref_idx;
20058 p_se_hdr = ast_skip_blanks(p_se_hdr);
20060 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
20061 *p_ref = SESSION_TIMER_REFRESHER_UAC;
20062 ast_debug(2, "Refresher: UAC\n");
20063 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
20064 *p_ref = SESSION_TIMER_REFRESHER_UAS;
20065 ast_debug(2, "Refresher: UAS\n");
20066 } else {
20067 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
20068 return -1;
20070 break;
20073 return 0;
20077 /*! \brief Handle 422 response to INVITE with session-timer requested
20079 Session-Timers: An INVITE originated by Asterisk that asks for session-timers support
20080 from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
20081 server tells Asterisk that the session refresh interval offered by Asterisk is too low
20082 for them. The proc_422_rsp() function handles a 422 response. It extracts the Min-SE
20083 header that comes back in 422 and sends a new INVITE accordingly. */
20084 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
20086 int rtn;
20087 const char *p_hdrval;
20088 int minse;
20090 p_hdrval = get_header(rsp, "Min-SE");
20091 if (ast_strlen_zero(p_hdrval)) {
20092 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
20093 return;
20095 rtn = parse_minse(p_hdrval, &minse);
20096 if (rtn != 0) {
20097 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
20098 return;
20100 p->stimer->st_interval = minse;
20101 transmit_invite(p, SIP_INVITE, 1, 2);
20105 /*! \brief Get Max or Min SE (session timer expiry)
20106 * \param p pointer to the SIP dialog
20107 * \param max if true, get max se, otherwise min se
20109 int st_get_se(struct sip_pvt *p, int max)
20111 if (max == TRUE) {
20112 if (p->stimer->st_cached_max_se) {
20113 return p->stimer->st_cached_max_se;
20114 } else {
20115 if (p->username) {
20116 struct sip_user *up = find_user(p->username, 1);
20117 if (up) {
20118 p->stimer->st_cached_max_se = up->stimer.st_max_se;
20119 unref_user(up, "unref user pointer from find_user call in st_get_se");
20120 return (p->stimer->st_cached_max_se);
20123 if (p->peername) {
20124 struct sip_peer *pp = find_peer(p->peername, NULL, 1);
20125 if (pp) {
20126 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
20127 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
20128 return (p->stimer->st_cached_max_se);
20132 p->stimer->st_cached_max_se = global_max_se;
20133 return (p->stimer->st_cached_max_se);
20134 } else {
20135 if (p->stimer->st_cached_min_se) {
20136 return p->stimer->st_cached_min_se;
20137 } else {
20138 if (p->username) {
20139 struct sip_user *up = find_user(p->username, 1);
20140 if (up) {
20141 p->stimer->st_cached_min_se = up->stimer.st_min_se;
20142 unref_user(up, "unref user pointer from find_user call in st_get_se (2)");
20143 return (p->stimer->st_cached_min_se);
20146 if (p->peername) {
20147 struct sip_peer *pp = find_peer(p->peername, NULL, 1);
20148 if (pp) {
20149 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
20150 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
20151 return (p->stimer->st_cached_min_se);
20155 p->stimer->st_cached_min_se = global_min_se;
20156 return (p->stimer->st_cached_min_se);
20161 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
20162 * \param p pointer to the SIP dialog
20164 enum st_refresher st_get_refresher(struct sip_pvt *p)
20166 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
20167 return p->stimer->st_cached_ref;
20169 if (p->username) {
20170 struct sip_user *up = find_user(p->username, 1);
20171 if (up) {
20172 p->stimer->st_cached_ref = up->stimer.st_ref;
20173 unref_user(up, "unref user pointer from find_user call in st_get_refresher");
20174 return up->stimer.st_ref;
20178 if (p->peername) {
20179 struct sip_peer *pp = find_peer(p->peername, NULL, 1);
20180 if (pp) {
20181 p->stimer->st_cached_ref = pp->stimer.st_ref;
20182 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
20183 return pp->stimer.st_ref;
20187 p->stimer->st_cached_ref = global_st_refresher;
20188 return global_st_refresher;
20192 /*! \brief Get the session-timer mode
20193 * \param p pointer to the SIP dialog
20195 enum st_mode st_get_mode(struct sip_pvt *p)
20197 if (!p->stimer)
20198 sip_st_alloc(p);
20200 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
20201 return p->stimer->st_cached_mode;
20203 if (p->username) {
20204 struct sip_user *up = find_user(p->username, 1);
20205 if (up) {
20206 p->stimer->st_cached_mode = up->stimer.st_mode_oper;
20207 unref_user(up, "unref user pointer from find_user call in st_get_mode");
20208 return up->stimer.st_mode_oper;
20211 if (p->peername) {
20212 struct sip_peer *pp = find_peer(p->peername, NULL, 1);
20213 if (pp) {
20214 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
20215 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
20216 return pp->stimer.st_mode_oper;
20220 p->stimer->st_cached_mode = global_st_mode;
20221 return global_st_mode;
20225 /*! \brief React to lack of answer to Qualify poke */
20226 static int sip_poke_noanswer(const void *data)
20228 struct sip_peer *peer = (struct sip_peer *)data;
20230 peer->pokeexpire = -1;
20231 if (peer->lastms > -1) {
20232 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
20233 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
20234 if (global_regextenonqualify)
20235 register_peer_exten(peer, FALSE);
20237 if (peer->call) {
20238 dialog_unlink_all(peer->call, TRUE, TRUE);
20239 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
20240 /* peer->call = sip_destroy(peer->call);*/
20243 peer->lastms = -1;
20244 ast_device_state_changed("SIP/%s", peer->name);
20245 /* Try again quickly */
20246 AST_SCHED_REPLACE(peer->pokeexpire, sched,
20247 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
20248 return 0;
20251 /*! \brief Check availability of peer, also keep NAT open
20252 \note This is done with the interval in qualify= configuration option
20253 Default is 2 seconds */
20254 static int sip_poke_peer(struct sip_peer *peer, int force)
20256 struct sip_pvt *p;
20257 int xmitres = 0;
20259 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
20260 /* IF we have no IP, or this isn't to be monitored, return
20261 immediately after clearing things out */
20262 AST_SCHED_DEL(sched, peer->pokeexpire);
20264 peer->lastms = 0;
20265 if (peer->call)
20266 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
20267 return 0;
20269 if (peer->call) {
20270 if (sipdebug)
20271 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
20272 dialog_unlink_all(peer->call, TRUE, TRUE);
20273 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
20274 /* peer->call = sip_destroy(peer->call); */
20276 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
20277 return -1;
20278 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
20280 p->sa = peer->addr;
20281 p->recv = peer->addr;
20282 p->socket = peer->socket;
20283 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
20284 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
20286 /* Send OPTIONs to peer's fullcontact */
20287 if (!ast_strlen_zero(peer->fullcontact))
20288 ast_string_field_set(p, fullcontact, peer->fullcontact);
20290 if (!ast_strlen_zero(peer->tohost))
20291 ast_string_field_set(p, tohost, peer->tohost);
20292 else
20293 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
20295 /* Recalculate our side, and recalculate Call ID */
20296 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
20297 build_via(p);
20298 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
20299 build_callid_pvt(p);
20300 ao2_t_link(dialogs, p, "Linking in under new name");
20302 AST_SCHED_DEL(sched, peer->pokeexpire);
20304 if (p->relatedpeer)
20305 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
20306 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
20307 ast_set_flag(&p->flags[0], SIP_OUTGOING);
20308 #ifdef VOCAL_DATA_HACK
20309 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
20310 xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
20311 #else
20312 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
20313 #endif
20314 peer->ps = ast_tvnow();
20315 if (xmitres == XMIT_ERROR) {
20316 sip_poke_noanswer(peer); /* Immediately unreachable, network problems */
20317 } else if (!force) {
20318 AST_SCHED_REPLACE(peer->pokeexpire, sched,
20319 peer->maxms * 2, sip_poke_noanswer, peer);
20321 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
20322 return 0;
20325 /*! \brief Part of PBX channel interface
20326 \note
20327 \par Return values:---
20329 If we have qualify on and the device is not reachable, regardless of registration
20330 state we return AST_DEVICE_UNAVAILABLE
20332 For peers with call limit:
20333 - not registered AST_DEVICE_UNAVAILABLE
20334 - registered, no call AST_DEVICE_NOT_INUSE
20335 - registered, active calls AST_DEVICE_INUSE
20336 - registered, call limit reached AST_DEVICE_BUSY
20337 - registered, onhold AST_DEVICE_ONHOLD
20338 - registered, ringing AST_DEVICE_RINGING
20340 For peers without call limit:
20341 - not registered AST_DEVICE_UNAVAILABLE
20342 - registered AST_DEVICE_NOT_INUSE
20343 - fixed IP (!dynamic) AST_DEVICE_NOT_INUSE
20345 Peers that does not have a known call and can't be reached by OPTIONS
20346 - unreachable AST_DEVICE_UNAVAILABLE
20348 If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
20349 out a state by walking the channel list.
20351 The queue system (\ref app_queue.c) treats a member as "active"
20352 if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
20354 When placing a call to the queue member, queue system sets a member to busy if
20355 != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
20358 static int sip_devicestate(void *data)
20360 char *host;
20361 char *tmp;
20362 struct sip_peer *p;
20364 int res = AST_DEVICE_INVALID;
20366 /* make sure data is not null. Maybe unnecessary, but better be safe */
20367 host = ast_strdupa(data ? data : "");
20368 if ((tmp = strchr(host, '@')))
20369 host = tmp + 1;
20371 ast_debug(3, "Checking device state for peer %s\n", host);
20373 if ((p = find_peer(host, NULL, 1))) {
20374 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
20375 /* we have an address for the peer */
20377 /* Check status in this order
20378 - Hold
20379 - Ringing
20380 - Busy (enforced only by call limit)
20381 - Inuse (we have a call)
20382 - Unreachable (qualify)
20383 If we don't find any of these state, report AST_DEVICE_NOT_INUSE
20384 for registered devices */
20386 if (p->onHold)
20387 /* First check for hold or ring states */
20388 res = AST_DEVICE_ONHOLD;
20389 else if (p->inRinging) {
20390 if (p->inRinging == p->inUse)
20391 res = AST_DEVICE_RINGING;
20392 else
20393 res = AST_DEVICE_RINGINUSE;
20394 } else if (p->call_limit && (p->inUse == p->call_limit))
20395 /* check call limit */
20396 res = AST_DEVICE_BUSY;
20397 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
20398 /* We're forcing busy before we've reached the call limit */
20399 res = AST_DEVICE_BUSY;
20400 else if (p->call_limit && p->inUse)
20401 /* Not busy, but we do have a call */
20402 res = AST_DEVICE_INUSE;
20403 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
20404 /* We don't have a call. Are we reachable at all? Requires qualify= */
20405 res = AST_DEVICE_UNAVAILABLE;
20406 else /* Default reply if we're registered and have no other data */
20407 res = AST_DEVICE_NOT_INUSE;
20408 } else {
20409 /* there is no address, it's unavailable */
20410 res = AST_DEVICE_UNAVAILABLE;
20412 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
20413 } else {
20414 res = AST_DEVICE_UNKNOWN;
20417 return res;
20420 /*! \brief PBX interface function -build SIP pvt structure
20421 * SIP calls initiated by the PBX arrive here.
20423 * \verbatim
20424 * SIP Dial string syntax
20425 * SIP/exten@host!dnid
20426 * or SIP/host/exten!dnid
20427 * or SIP/host!dnid
20428 * \endverbatim
20430 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
20432 struct sip_pvt *p;
20433 struct ast_channel *tmpc = NULL;
20434 char *ext, *host;
20435 char tmp[256];
20436 char *dest = data;
20437 char *dnid;
20438 char *secret = NULL;
20439 char *md5secret = NULL;
20440 char *authname = NULL;
20441 int oldformat = format;
20443 /* mask request with some set of allowed formats.
20444 * XXX this needs to be fixed.
20445 * The original code uses AST_FORMAT_AUDIO_MASK, but it is
20446 * unclear what to use here. We have global_capabilities, which is
20447 * configured from sip.conf, and sip_tech.capabilities, which is
20448 * hardwired to all audio formats.
20450 format &= AST_FORMAT_AUDIO_MASK;
20451 if (!format) {
20452 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));
20453 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; /* Can't find codec to connect to host */
20454 return NULL;
20456 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
20458 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
20459 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
20460 *cause = AST_CAUSE_SWITCH_CONGESTION;
20461 return NULL;
20464 p->outgoing_call = TRUE;
20466 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
20467 dialog_unlink_all(p, TRUE, TRUE);
20468 dialog_unref(p, "unref dialog p from mem fail");
20469 /* sip_destroy(p); */
20470 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
20471 *cause = AST_CAUSE_SWITCH_CONGESTION;
20472 return NULL;
20475 /* Save the destination, the SIP dial string */
20476 ast_copy_string(tmp, dest, sizeof(tmp));
20479 /* Find DNID and take it away */
20480 dnid = strchr(tmp, '!');
20481 if (dnid != NULL) {
20482 *dnid++ = '\0';
20483 ast_string_field_set(p, todnid, dnid);
20486 /* Find at sign - @ */
20487 host = strchr(tmp, '@');
20488 if (host) {
20489 *host++ = '\0';
20490 ext = tmp;
20491 secret = strchr(ext, ':');
20492 if (secret) {
20493 *secret++ = '\0';
20494 md5secret = strchr(secret, ':');
20495 if (md5secret) {
20496 *md5secret++ = '\0';
20497 authname = strchr(md5secret, ':');
20498 if (authname)
20499 *authname++ = '\0';
20502 } else {
20503 ext = strchr(tmp, '/');
20504 if (ext)
20505 *ext++ = '\0';
20506 host = tmp;
20509 /* We now have
20510 host = peer name, DNS host name or DNS domain (for SRV)
20511 ext = extension (user part of URI)
20512 dnid = destination of the call (applies to the To: header)
20514 if (create_addr(p, host, NULL)) {
20515 *cause = AST_CAUSE_UNREGISTERED;
20516 ast_debug(3, "Cant create SIP call - target device not registred\n");
20517 dialog_unlink_all(p, TRUE, TRUE);
20518 dialog_unref(p, "unref dialog p UNREGISTERED");
20519 /* sip_destroy(p); */
20520 return NULL;
20522 if (ast_strlen_zero(p->peername) && ext)
20523 ast_string_field_set(p, peername, ext);
20524 /* Recalculate our side, and recalculate Call ID */
20525 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip);
20526 build_via(p);
20527 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
20528 build_callid_pvt(p);
20529 ao2_t_link(dialogs, p, "Linking in under new name");
20531 /* We have an extension to call, don't use the full contact here */
20532 /* This to enable dialing registered peers with extension dialling,
20533 like SIP/peername/extension
20534 SIP/peername will still use the full contact
20536 if (ext) {
20537 ast_string_field_set(p, username, ext);
20538 ast_string_field_set(p, fullcontact, NULL);
20540 if (secret && !ast_strlen_zero(secret))
20541 ast_string_field_set(p, peersecret, secret);
20543 if (md5secret && !ast_strlen_zero(md5secret))
20544 ast_string_field_set(p, peermd5secret, md5secret);
20546 if (authname && !ast_strlen_zero(authname))
20547 ast_string_field_set(p, authname, authname);
20548 #if 0
20549 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
20550 #endif
20551 p->prefcodec = oldformat; /* Format for this call */
20552 p->jointcapability = oldformat;
20553 sip_pvt_lock(p);
20554 tmpc = sip_new(p, AST_STATE_DOWN, host); /* Place the call */
20555 if (global_callevents)
20556 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
20557 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
20558 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
20559 sip_pvt_unlock(p);
20560 if (!tmpc) {
20561 dialog_unlink_all(p, TRUE, TRUE);
20562 /* sip_destroy(p); */
20564 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
20565 ast_update_use_count();
20566 restart_monitor();
20567 return tmpc;
20570 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
20571 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
20573 if (ast_strlen_zero(value))
20574 return;
20576 if (!ast_false(value)) {
20577 char buf[64];
20578 char *word, *next;
20580 ast_copy_string(buf, value, sizeof(buf));
20581 next = buf;
20582 while ((word = strsep(&next, ","))) {
20583 if (!strcasecmp(word, "port"))
20584 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
20585 else if (!strcasecmp(word, "invite"))
20586 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
20587 else
20588 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
20594 \brief Handle flag-type options common to configuration of devices - users and peers
20595 \param flags array of two struct ast_flags
20596 \param mask array of two struct ast_flags
20597 \param v linked list of config variables to process
20598 \returns non-zero if any config options were handled, zero otherwise
20600 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
20602 int res = 1;
20604 if (!strcasecmp(v->name, "trustrpid")) {
20605 ast_set_flag(&mask[0], SIP_TRUSTRPID);
20606 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
20607 } else if (!strcasecmp(v->name, "sendrpid")) {
20608 ast_set_flag(&mask[0], SIP_SENDRPID);
20609 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
20610 } else if (!strcasecmp(v->name, "g726nonstandard")) {
20611 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
20612 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
20613 } else if (!strcasecmp(v->name, "useclientcode")) {
20614 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
20615 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
20616 } else if (!strcasecmp(v->name, "dtmfmode")) {
20617 ast_set_flag(&mask[0], SIP_DTMF);
20618 ast_clear_flag(&flags[0], SIP_DTMF);
20619 if (!strcasecmp(v->value, "inband"))
20620 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
20621 else if (!strcasecmp(v->value, "rfc2833"))
20622 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
20623 else if (!strcasecmp(v->value, "info"))
20624 ast_set_flag(&flags[0], SIP_DTMF_INFO);
20625 else if (!strcasecmp(v->value, "shortinfo"))
20626 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
20627 else if (!strcasecmp(v->value, "auto"))
20628 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
20629 else {
20630 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
20631 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
20633 } else if (!strcasecmp(v->name, "nat")) {
20634 ast_set_flag(&mask[0], SIP_NAT);
20635 ast_clear_flag(&flags[0], SIP_NAT);
20636 if (!strcasecmp(v->value, "never"))
20637 ast_set_flag(&flags[0], SIP_NAT_NEVER);
20638 else if (!strcasecmp(v->value, "route"))
20639 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
20640 else if (ast_true(v->value))
20641 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
20642 else
20643 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
20644 } else if (!strcasecmp(v->name, "canreinvite")) {
20645 ast_set_flag(&mask[0], SIP_REINVITE);
20646 ast_clear_flag(&flags[0], SIP_REINVITE);
20647 if (ast_true(v->value)) {
20648 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
20649 } else if (!ast_false(v->value)) {
20650 char buf[64];
20651 char *word, *next = buf;
20653 ast_copy_string(buf, v->value, sizeof(buf));
20654 while ((word = strsep(&next, ","))) {
20655 if (!strcasecmp(word, "update")) {
20656 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
20657 } else if (!strcasecmp(word, "nonat")) {
20658 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
20659 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
20660 } else {
20661 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
20665 } else if (!strcasecmp(v->name, "insecure")) {
20666 ast_set_flag(&mask[0], SIP_INSECURE);
20667 ast_clear_flag(&flags[0], SIP_INSECURE);
20668 set_insecure_flags(&flags[0], v->value, v->lineno);
20669 } else if (!strcasecmp(v->name, "progressinband")) {
20670 ast_set_flag(&mask[0], SIP_PROG_INBAND);
20671 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
20672 if (ast_true(v->value))
20673 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
20674 else if (strcasecmp(v->value, "never"))
20675 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
20676 } else if (!strcasecmp(v->name, "promiscredir")) {
20677 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
20678 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
20679 } else if (!strcasecmp(v->name, "videosupport")) {
20680 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
20681 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
20682 } else if (!strcasecmp(v->name, "textsupport")) {
20683 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
20684 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
20685 res = 1;
20686 } else if (!strcasecmp(v->name, "allowoverlap")) {
20687 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
20688 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
20689 } else if (!strcasecmp(v->name, "allowsubscribe")) {
20690 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
20691 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
20692 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
20693 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
20694 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
20695 #ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
20696 } else if (!strcasecmp(v->name, "t38pt_rtp")) {
20697 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
20698 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
20699 } else if (!strcasecmp(v->name, "t38pt_tcp")) {
20700 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
20701 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
20702 #endif
20703 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
20704 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
20705 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
20706 } else if (!strcasecmp(v->name, "buggymwi")) {
20707 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
20708 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
20709 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
20710 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
20711 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
20712 } else
20713 res = 0;
20715 return res;
20718 /*! \brief Add SIP domain to list of domains we are responsible for */
20719 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
20721 struct domain *d;
20723 if (ast_strlen_zero(domain)) {
20724 ast_log(LOG_WARNING, "Zero length domain.\n");
20725 return 1;
20728 if (!(d = ast_calloc(1, sizeof(*d))))
20729 return 0;
20731 ast_copy_string(d->domain, domain, sizeof(d->domain));
20733 if (!ast_strlen_zero(context))
20734 ast_copy_string(d->context, context, sizeof(d->context));
20736 d->mode = mode;
20738 AST_LIST_LOCK(&domain_list);
20739 AST_LIST_INSERT_TAIL(&domain_list, d, list);
20740 AST_LIST_UNLOCK(&domain_list);
20742 if (sipdebug)
20743 ast_debug(1, "Added local SIP domain '%s'\n", domain);
20745 return 1;
20748 /*! \brief check_sip_domain: Check if domain part of uri is local to our server */
20749 static int check_sip_domain(const char *domain, char *context, size_t len)
20751 struct domain *d;
20752 int result = 0;
20754 AST_LIST_LOCK(&domain_list);
20755 AST_LIST_TRAVERSE(&domain_list, d, list) {
20756 if (strcasecmp(d->domain, domain))
20757 continue;
20759 if (len && !ast_strlen_zero(d->context))
20760 ast_copy_string(context, d->context, len);
20762 result = 1;
20763 break;
20765 AST_LIST_UNLOCK(&domain_list);
20767 return result;
20770 /*! \brief Clear our domain list (at reload) */
20771 static void clear_sip_domains(void)
20773 struct domain *d;
20775 AST_LIST_LOCK(&domain_list);
20776 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
20777 ast_free(d);
20778 AST_LIST_UNLOCK(&domain_list);
20782 /*! \brief Add realm authentication in list */
20783 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
20785 char authcopy[256];
20786 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
20787 char *stringp;
20788 struct sip_auth *a, *b, *auth;
20790 if (ast_strlen_zero(configuration))
20791 return authlist;
20793 ast_debug(1, "Auth config :: %s\n", configuration);
20795 ast_copy_string(authcopy, configuration, sizeof(authcopy));
20796 stringp = authcopy;
20798 username = stringp;
20799 realm = strrchr(stringp, '@');
20800 if (realm)
20801 *realm++ = '\0';
20802 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
20803 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
20804 return authlist;
20806 stringp = username;
20807 username = strsep(&stringp, ":");
20808 if (username) {
20809 secret = strsep(&stringp, ":");
20810 if (!secret) {
20811 stringp = username;
20812 md5secret = strsep(&stringp, "#");
20815 if (!(auth = ast_calloc(1, sizeof(*auth))))
20816 return authlist;
20818 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
20819 ast_copy_string(auth->username, username, sizeof(auth->username));
20820 if (secret)
20821 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
20822 if (md5secret)
20823 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
20825 /* find the end of the list */
20826 for (b = NULL, a = authlist; a ; b = a, a = a->next)
20828 if (b)
20829 b->next = auth; /* Add structure add end of list */
20830 else
20831 authlist = auth;
20833 ast_verb(3, "Added authentication for realm %s\n", realm);
20835 return authlist;
20839 /*! \brief Clear realm authentication list (at reload) */
20840 static int clear_realm_authentication(struct sip_auth *authlist)
20842 struct sip_auth *a = authlist;
20843 struct sip_auth *b;
20845 while (a) {
20846 b = a;
20847 a = a->next;
20848 ast_free(b);
20851 return 1;
20854 /*! \brief Find authentication for a specific realm */
20855 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
20857 struct sip_auth *a;
20859 for (a = authlist; a; a = a->next) {
20860 if (!strcasecmp(a->realm, realm))
20861 break;
20864 return a;
20867 /*! \brief
20868 * implement the setvar config line
20870 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
20872 struct ast_variable *tmpvar = NULL;
20873 char *varname = ast_strdupa(buf), *varval = NULL;
20875 if ((varval = strchr(varname, '='))) {
20876 *varval++ = '\0';
20877 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
20878 tmpvar->next = list;
20879 list = tmpvar;
20882 return list;
20885 /*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
20886 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
20888 struct sip_user *user;
20889 int format;
20890 struct ast_flags userflags[2] = {{(0)}};
20891 struct ast_flags mask[2] = {{(0)}};
20893 if (!(user = ao2_t_alloc(sizeof(*user), sip_destroy_user_fn, "allocate a user struct")))
20894 return NULL;
20896 ast_atomic_fetchadd_int(&suserobjs, 1);
20897 ast_copy_string(user->name, name, sizeof(user->name));
20898 user->ha = NULL;
20899 ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
20900 ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
20901 user->capability = global_capability;
20902 user->allowtransfer = global_allowtransfer;
20903 user->maxcallbitrate = default_maxcallbitrate;
20904 user->autoframing = global_autoframing;
20905 if (global_callcounter)
20906 user->call_limit=999;
20907 user->prefs = default_prefs;
20908 user->stimer.st_mode_oper = global_st_mode; /* Session-Timers */
20909 user->stimer.st_ref = global_st_refresher;
20910 user->stimer.st_min_se = global_min_se;
20911 user->stimer.st_max_se = global_max_se;
20913 /* set default context */
20914 strcpy(user->context, default_context);
20915 strcpy(user->language, default_language);
20916 strcpy(user->mohinterpret, default_mohinterpret);
20917 strcpy(user->mohsuggest, default_mohsuggest);
20918 /* First we walk through the v parameters list and then the alt parameters list */
20919 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
20920 if (handle_common_options(&userflags[0], &mask[0], v))
20921 continue;
20922 if (!strcasecmp(v->name, "context")) {
20923 ast_copy_string(user->context, v->value, sizeof(user->context));
20924 } else if (!strcasecmp(v->name, "subscribecontext")) {
20925 ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
20926 } else if (!strcasecmp(v->name, "setvar")) {
20927 user->chanvars = add_var(v->value, user->chanvars);
20928 } else if (!strcasecmp(v->name, "permit") ||
20929 !strcasecmp(v->name, "deny")) {
20930 int ha_error = 0;
20932 user->ha = ast_append_ha(v->name, v->value, user->ha, &ha_error);
20933 if (ha_error)
20934 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
20935 } else if (!strcasecmp(v->name, "allowtransfer")) {
20936 user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
20937 } else if (!strcasecmp(v->name, "secret")) {
20938 ast_copy_string(user->secret, v->value, sizeof(user->secret));
20939 } else if (!strcasecmp(v->name, "md5secret")) {
20940 ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
20941 } else if (!strcasecmp(v->name, "callerid")) {
20942 ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
20943 } else if (!strcasecmp(v->name, "fullname")) {
20944 ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
20945 } else if (!strcasecmp(v->name, "cid_number")) {
20946 ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
20947 } else if (!strcasecmp(v->name, "callgroup")) {
20948 user->callgroup = ast_get_group(v->value);
20949 } else if (!strcasecmp(v->name, "pickupgroup")) {
20950 user->pickupgroup = ast_get_group(v->value);
20951 } else if (!strcasecmp(v->name, "parkinglot")) {
20952 ast_copy_string(user->parkinglot, v->value, sizeof(user->parkinglot));
20953 } else if (!strcasecmp(v->name, "language")) {
20954 ast_copy_string(user->language, v->value, sizeof(user->language));
20955 } else if (!strcasecmp(v->name, "mohinterpret")) {
20956 ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
20957 } else if (!strcasecmp(v->name, "mohsuggest")) {
20958 ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
20959 } else if (!strcasecmp(v->name, "accountcode")) {
20960 ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
20961 } else if (!strcasecmp(v->name, "callcounter")) {
20962 user->call_limit = ast_true(v->value) ? 999 : 0;
20963 } else if (!strcasecmp(v->name, "call-limit")) {
20964 user->call_limit = atoi(v->value);
20965 if (user->call_limit < 0)
20966 user->call_limit = 0;
20967 } else if (!strcasecmp(v->name, "amaflags")) {
20968 format = ast_cdr_amaflags2int(v->value);
20969 if (format < 0) {
20970 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
20971 } else {
20972 user->amaflags = format;
20974 } else if (!strcasecmp(v->name, "allow")) {
20975 int error = ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, TRUE);
20976 if (error)
20977 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
20978 } else if (!strcasecmp(v->name, "disallow")) {
20979 int error = ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, FALSE);
20980 if (error)
20981 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
20982 } else if (!strcasecmp(v->name, "autoframing")) {
20983 user->autoframing = ast_true(v->value);
20984 } else if (!strcasecmp(v->name, "callingpres")) {
20985 user->callingpres = ast_parse_caller_presentation(v->value);
20986 if (user->callingpres == -1)
20987 user->callingpres = atoi(v->value);
20988 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
20989 user->maxcallbitrate = atoi(v->value);
20990 if (user->maxcallbitrate < 0)
20991 user->maxcallbitrate = default_maxcallbitrate;
20992 } else if (!strcasecmp(v->name, "session-timers")) {
20993 int i = (int) str2stmode(v->value);
20994 if (i < 0) {
20995 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
20996 user->stimer.st_mode_oper = global_st_mode;
20997 } else {
20998 user->stimer.st_mode_oper = i;
21000 } else if (!strcasecmp(v->name, "session-expires")) {
21001 if (sscanf(v->value, "%d", &user->stimer.st_max_se) != 1) {
21002 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
21003 user->stimer.st_max_se = global_max_se;
21005 } else if (!strcasecmp(v->name, "session-minse")) {
21006 if (sscanf(v->value, "%d", &user->stimer.st_min_se) != 1) {
21007 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
21008 user->stimer.st_min_se = global_min_se;
21010 if (user->stimer.st_min_se < 90) {
21011 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);
21012 user->stimer.st_min_se = global_min_se;
21014 } else if (!strcasecmp(v->name, "session-refresher")) {
21015 int i = (int) str2strefresher(v->value);
21016 if (i < 0) {
21017 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
21018 user->stimer.st_ref = global_st_refresher;
21019 } else {
21020 user->stimer.st_ref = i;
21024 /* We can't just report unknown options here because this may be a
21025 * type=friend entry. All user options are valid for a peer, but not
21026 * the other way around. */
21028 ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
21029 ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
21030 if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
21031 global_allowsubscribe = TRUE; /* No global ban any more */
21032 return user;
21035 /*! \brief Set peer defaults before configuring specific configurations */
21036 static void set_peer_defaults(struct sip_peer *peer)
21038 if (peer->expire == 0) {
21039 /* Don't reset expire or port time during reload
21040 if we have an active registration
21042 peer->expire = -1;
21043 peer->pokeexpire = -1;
21044 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
21045 peer->socket.type = SIP_TRANSPORT_UDP;
21046 peer->socket.fd = -1;
21048 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
21049 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21050 strcpy(peer->context, default_context);
21051 strcpy(peer->subscribecontext, default_subscribecontext);
21052 strcpy(peer->language, default_language);
21053 strcpy(peer->mohinterpret, default_mohinterpret);
21054 strcpy(peer->mohsuggest, default_mohsuggest);
21055 peer->addr.sin_family = AF_INET;
21056 peer->defaddr.sin_family = AF_INET;
21057 peer->capability = global_capability;
21058 peer->maxcallbitrate = default_maxcallbitrate;
21059 peer->rtptimeout = global_rtptimeout;
21060 peer->rtpholdtimeout = global_rtpholdtimeout;
21061 peer->rtpkeepalive = global_rtpkeepalive;
21062 peer->allowtransfer = global_allowtransfer;
21063 peer->autoframing = global_autoframing;
21064 peer->qualifyfreq = global_qualifyfreq;
21065 if (global_callcounter)
21066 peer->call_limit=999;
21067 strcpy(peer->vmexten, default_vmexten);
21068 peer->secret[0] = '\0';
21069 peer->md5secret[0] = '\0';
21070 peer->cid_num[0] = '\0';
21071 peer->cid_name[0] = '\0';
21072 peer->fromdomain[0] = '\0';
21073 peer->fromuser[0] = '\0';
21074 peer->regexten[0] = '\0';
21075 peer->callgroup = 0;
21076 peer->pickupgroup = 0;
21077 peer->maxms = default_qualify;
21078 peer->prefs = default_prefs;
21079 peer->stimer.st_mode_oper = global_st_mode; /* Session-Timers */
21080 peer->stimer.st_ref = global_st_refresher;
21081 peer->stimer.st_min_se = global_min_se;
21082 peer->stimer.st_max_se = global_max_se;
21083 peer->timer_t1 = global_t1;
21084 peer->timer_b = global_timer_b;
21085 clear_peer_mailboxes(peer);
21088 /*! \brief Create temporary peer (used in autocreatepeer mode) */
21089 static struct sip_peer *temp_peer(const char *name)
21091 struct sip_peer *peer;
21093 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
21094 return NULL;
21096 ast_atomic_fetchadd_int(&apeerobjs, 1);
21097 set_peer_defaults(peer);
21099 ast_copy_string(peer->name, name, sizeof(peer->name));
21101 peer->selfdestruct = TRUE;
21102 peer->host_dynamic = TRUE;
21103 peer->prefs = default_prefs;
21104 reg_source_db(peer);
21106 return peer;
21109 /*! \todo document this function */
21110 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
21112 char *next, *mbox, *context;
21114 next = ast_strdupa(value);
21116 while ((mbox = context = strsep(&next, ","))) {
21117 struct sip_mailbox *mailbox;
21119 if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
21120 continue;
21122 strsep(&context, "@");
21123 if (ast_strlen_zero(mbox)) {
21124 ast_free(mailbox);
21125 continue;
21127 mailbox->mailbox = ast_strdup(mbox);
21128 mailbox->context = ast_strdup(context);
21130 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
21134 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
21135 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
21137 struct sip_peer *peer = NULL;
21138 struct ast_ha *oldha = NULL;
21139 int found=0;
21140 int firstpass=1;
21141 int format=0; /* Ama flags */
21142 time_t regseconds = 0;
21143 struct ast_flags peerflags[2] = {{(0)}};
21144 struct ast_flags mask[2] = {{(0)}};
21145 char callback[256] = "";
21146 struct sip_peer tmp_peer;
21147 const char *srvlookup = NULL;
21148 static int deprecation_warning = 1;
21149 struct ast_str *fullcontact = ast_str_alloca(sizeof(peer->fullcontact));
21151 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
21152 /* Note we do NOT use find_peer here, to avoid realtime recursion */
21153 /* We also use a case-sensitive comparison (unlike find_peer) so
21154 that case changes made to the peer name will be properly handled
21155 during reload
21157 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
21158 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER|OBJ_UNLINK, "find and unlink peer from peers table");
21161 if (peer) {
21162 /* Already in the list, remove it and it will be added back (or FREE'd) */
21163 found++;
21164 if (!(peer->the_mark))
21165 firstpass = 0;
21166 } else {
21167 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
21168 return NULL;
21170 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
21171 ast_atomic_fetchadd_int(&rpeerobjs, 1);
21172 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
21173 } else
21174 ast_atomic_fetchadd_int(&speerobjs, 1);
21176 /* Note that our peer HAS had its reference count increased */
21177 if (firstpass) {
21178 peer->lastmsgssent = -1;
21179 oldha = peer->ha;
21180 peer->ha = NULL;
21181 set_peer_defaults(peer); /* Set peer defaults */
21183 if (!found && name)
21184 ast_copy_string(peer->name, name, sizeof(peer->name));
21186 /* If we have channel variables, remove them (reload) */
21187 if (peer->chanvars) {
21188 ast_variables_destroy(peer->chanvars);
21189 peer->chanvars = NULL;
21190 /* XXX should unregister ? */
21193 /* If we have realm authentication information, remove them (reload) */
21194 clear_realm_authentication(peer->auth);
21195 peer->auth = NULL;
21197 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
21198 if (handle_common_options(&peerflags[0], &mask[0], v))
21199 continue;
21200 if (!strcasecmp(v->name, "transport")) {
21201 if (!strcasecmp(v->value, "udp"))
21202 peer->socket.type = SIP_TRANSPORT_UDP;
21203 else if (!strcasecmp(v->value, "tcp"))
21204 peer->socket.type = SIP_TRANSPORT_TCP;
21205 else if (!strcasecmp(v->value, "tls"))
21206 peer->socket.type = SIP_TRANSPORT_TLS;
21207 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
21208 ast_get_time_t(v->value, &regseconds, 0, NULL);
21209 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
21210 inet_aton(v->value, &(peer->addr.sin_addr));
21211 } else if (realtime && !strcasecmp(v->name, "name"))
21212 ast_copy_string(peer->name, v->value, sizeof(peer->name));
21213 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
21214 /* Reconstruct field, because realtime separates our value at the ';' */
21215 if (fullcontact->used > 0) {
21216 ast_str_append(&fullcontact, 0, ";%s", v->value);
21217 } else {
21218 ast_str_set(&fullcontact, 0, "%s", v->value);
21220 } else if (!strcasecmp(v->name, "secret"))
21221 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
21222 else if (!strcasecmp(v->name, "md5secret"))
21223 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
21224 else if (!strcasecmp(v->name, "auth"))
21225 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
21226 else if (!strcasecmp(v->name, "callerid")) {
21227 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
21228 } else if (!strcasecmp(v->name, "fullname")) {
21229 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
21230 } else if (!strcasecmp(v->name, "cid_number")) {
21231 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
21232 } else if (!strcasecmp(v->name, "context")) {
21233 ast_copy_string(peer->context, v->value, sizeof(peer->context));
21234 } else if (!strcasecmp(v->name, "subscribecontext")) {
21235 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
21236 } else if (!strcasecmp(v->name, "fromdomain")) {
21237 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
21238 } else if (!strcasecmp(v->name, "usereqphone")) {
21239 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
21240 } else if (!strcasecmp(v->name, "fromuser")) {
21241 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
21242 } else if (!strcasecmp(v->name, "outboundproxy")) {
21243 char *port, *next, *force, *proxyname;
21244 int forceopt = FALSE;
21245 /* Set peer channel variable */
21246 next = proxyname = ast_strdupa(v->value);
21247 if ((port = strchr(proxyname, ':'))) {
21248 *port++ = '\0';
21249 next = port;
21251 if ((force = strchr(next, ','))) {
21252 *force++ = '\0';
21253 forceopt = strcmp(force, "force");
21255 /* Allocate proxy object */
21256 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
21257 } else if (!strcasecmp(v->name, "host")) {
21258 if (!strcasecmp(v->value, "dynamic")) {
21259 /* They'll register with us */
21260 if (!found || !peer->host_dynamic) {
21261 /* Initialize stuff if this is a new peer, or if it used to
21262 * not be dynamic before the reload. */
21263 memset(&peer->addr.sin_addr, 0, 4);
21264 if (peer->addr.sin_port) {
21265 /* If we've already got a port, make it the default rather than absolute */
21266 peer->defaddr.sin_port = peer->addr.sin_port;
21267 peer->addr.sin_port = 0;
21270 peer->host_dynamic = TRUE;
21271 } else {
21272 /* Non-dynamic. Make sure we become that way if we're not */
21273 AST_SCHED_DEL(sched, peer->expire);
21274 peer->host_dynamic = FALSE;
21275 srvlookup = v->value;
21277 } else if (!strcasecmp(v->name, "defaultip")) {
21278 if (ast_get_ip(&peer->defaddr, v->value)) {
21279 unref_peer(peer, "unref_peer: from build_peer defaultip");
21280 return NULL;
21282 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
21283 int ha_error = 0;
21285 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
21286 if (ha_error)
21287 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
21288 } else if (!strcasecmp(v->name, "port")) {
21289 if (!realtime && peer->host_dynamic)
21290 peer->defaddr.sin_port = htons(atoi(v->value));
21291 else
21292 peer->addr.sin_port = htons(atoi(v->value));
21293 } else if (!strcasecmp(v->name, "callingpres")) {
21294 peer->callingpres = ast_parse_caller_presentation(v->value);
21295 if (peer->callingpres == -1)
21296 peer->callingpres = atoi(v->value);
21297 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) { /* "username" is deprecated */
21298 ast_copy_string(peer->username, v->value, sizeof(peer->username));
21299 if (!strcasecmp(v->name, "username")) {
21300 if (deprecation_warning) {
21301 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
21302 deprecation_warning = 0;
21304 peer->deprecated_username = 1;
21306 } else if (!strcasecmp(v->name, "language")) {
21307 ast_copy_string(peer->language, v->value, sizeof(peer->language));
21308 } else if (!strcasecmp(v->name, "regexten")) {
21309 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
21310 } else if (!strcasecmp(v->name, "callbackextension")) {
21311 ast_copy_string(callback, v->value, sizeof(callback));
21312 } else if (!strcasecmp(v->name, "callcounter")) {
21313 peer->call_limit = ast_true(v->value) ? 999 : 0;
21314 } else if (!strcasecmp(v->name, "call-limit")) {
21315 peer->call_limit = atoi(v->value);
21316 if (peer->call_limit < 0)
21317 peer->call_limit = 0;
21318 } else if (!strcasecmp(v->name, "busylevel")) {
21319 peer->busy_level = atoi(v->value);
21320 if (peer->busy_level < 0)
21321 peer->busy_level = 0;
21322 } else if (!strcasecmp(v->name, "amaflags")) {
21323 format = ast_cdr_amaflags2int(v->value);
21324 if (format < 0) {
21325 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
21326 } else {
21327 peer->amaflags = format;
21329 } else if (!strcasecmp(v->name, "accountcode")) {
21330 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
21331 } else if (!strcasecmp(v->name, "mohinterpret")) {
21332 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
21333 } else if (!strcasecmp(v->name, "mohsuggest")) {
21334 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
21335 } else if (!strcasecmp(v->name, "parkinglot")) {
21336 ast_copy_string(peer->parkinglot, v->value, sizeof(peer->parkinglot));
21337 } else if (!strcasecmp(v->name, "mailbox")) {
21338 add_peer_mailboxes(peer, v->value);
21339 } else if (!strcasecmp(v->name, "hasvoicemail")) {
21340 /* People expect that if 'hasvoicemail' is set, that the mailbox will
21341 * be also set, even if not explicitly specified. */
21342 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
21343 add_peer_mailboxes(peer, name);
21345 } else if (!strcasecmp(v->name, "subscribemwi")) {
21346 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
21347 } else if (!strcasecmp(v->name, "vmexten")) {
21348 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
21349 } else if (!strcasecmp(v->name, "callgroup")) {
21350 peer->callgroup = ast_get_group(v->value);
21351 } else if (!strcasecmp(v->name, "allowtransfer")) {
21352 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
21353 } else if (!strcasecmp(v->name, "pickupgroup")) {
21354 peer->pickupgroup = ast_get_group(v->value);
21355 } else if (!strcasecmp(v->name, "allow")) {
21356 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
21357 if (error)
21358 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
21359 } else if (!strcasecmp(v->name, "disallow")) {
21360 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
21361 if (error)
21362 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
21363 } else if (!strcasecmp(v->name, "registertrying")) {
21364 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
21365 } else if (!strcasecmp(v->name, "autoframing")) {
21366 peer->autoframing = ast_true(v->value);
21367 } else if (!strcasecmp(v->name, "rtptimeout")) {
21368 if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
21369 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
21370 peer->rtptimeout = global_rtptimeout;
21372 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
21373 if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
21374 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
21375 peer->rtpholdtimeout = global_rtpholdtimeout;
21377 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
21378 if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
21379 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
21380 peer->rtpkeepalive = global_rtpkeepalive;
21382 } else if (!strcasecmp(v->name, "timert1")) {
21383 if ((sscanf(v->value, "%d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
21384 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
21385 peer->timer_t1 = global_t1;
21387 } else if (!strcasecmp(v->name, "timerb")) {
21388 if ((sscanf(v->value, "%d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
21389 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
21390 peer->timer_b = global_timer_b;
21392 } else if (!strcasecmp(v->name, "setvar")) {
21393 peer->chanvars = add_var(v->value, peer->chanvars);
21394 } else if (!strcasecmp(v->name, "qualify")) {
21395 if (!strcasecmp(v->value, "no")) {
21396 peer->maxms = 0;
21397 } else if (!strcasecmp(v->value, "yes")) {
21398 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
21399 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
21400 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);
21401 peer->maxms = 0;
21403 } else if (!strcasecmp(v->name, "qualifyfreq")) {
21404 int i;
21405 if (sscanf(v->value, "%d", &i) == 1)
21406 peer->qualifyfreq = i * 1000;
21407 else {
21408 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
21409 peer->qualifyfreq = global_qualifyfreq;
21411 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
21412 peer->maxcallbitrate = atoi(v->value);
21413 if (peer->maxcallbitrate < 0)
21414 peer->maxcallbitrate = default_maxcallbitrate;
21415 } else if (!strcasecmp(v->name, "session-timers")) {
21416 int i = (int) str2stmode(v->value);
21417 if (i < 0) {
21418 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
21419 peer->stimer.st_mode_oper = global_st_mode;
21420 } else {
21421 peer->stimer.st_mode_oper = i;
21423 } else if (!strcasecmp(v->name, "session-expires")) {
21424 if (sscanf(v->value, "%d", &peer->stimer.st_max_se) != 1) {
21425 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
21426 peer->stimer.st_max_se = global_max_se;
21428 } else if (!strcasecmp(v->name, "session-minse")) {
21429 if (sscanf(v->value, "%d", &peer->stimer.st_min_se) != 1) {
21430 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
21431 peer->stimer.st_min_se = global_min_se;
21433 if (peer->stimer.st_min_se < 90) {
21434 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);
21435 peer->stimer.st_min_se = global_min_se;
21437 } else if (!strcasecmp(v->name, "session-refresher")) {
21438 int i = (int) str2strefresher(v->value);
21439 if (i < 0) {
21440 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
21441 peer->stimer.st_ref = global_st_refresher;
21442 } else {
21443 peer->stimer.st_ref = i;
21448 if (fullcontact->used > 0) {
21449 ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
21450 peer->rt_fromcontact = TRUE;
21453 if (srvlookup && peer->dnsmgr == NULL) {
21454 char transport[MAXHOSTNAMELEN];
21455 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
21457 if (ast_dnsmgr_lookup(srvlookup, &peer->addr, &peer->dnsmgr, global_srvlookup ? transport : NULL)) {
21458 unref_peer(peer, "getting rid of a peer pointer");
21459 return NULL;
21462 ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
21465 if (!peer->addr.sin_port)
21466 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
21468 if (!peer->socket.port)
21469 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
21471 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
21472 time_t nowtime = time(NULL);
21474 if ((nowtime - regseconds) > 0) {
21475 destroy_association(peer);
21476 memset(&peer->addr, 0, sizeof(peer->addr));
21477 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
21480 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
21481 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
21482 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
21483 global_allowsubscribe = TRUE; /* No global ban any more */
21484 if (!found && peer->host_dynamic && !peer->is_realtime)
21485 reg_source_db(peer);
21487 /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
21488 * subscribe to it now. */
21489 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
21490 !AST_LIST_EMPTY(&peer->mailboxes)) {
21491 add_peer_mwi_subs(peer);
21492 /* Send MWI from the event cache only. This is so we can send initial
21493 * MWI if app_voicemail got loaded before chan_sip. If it is the other
21494 * way, then we will get events when app_voicemail gets loaded. */
21495 sip_send_mwi_to_peer(peer, NULL, 1);
21497 peer->the_mark = 0;
21499 ast_free_ha(oldha);
21500 if (!ast_strlen_zero(callback)) { /* build string from peer info */
21501 char *reg_string;
21503 asprintf(&reg_string, "%s:%s@%s/%s", peer->username, peer->secret, peer->tohost, callback);
21504 if (reg_string) {
21505 sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
21506 ast_free(reg_string);
21509 return peer;
21512 static int peer_markall_func(void *userobj, void *arg, int flags)
21514 struct sip_peer *peer = userobj;
21515 peer->the_mark = 1;
21516 return 0;
21519 /*! \brief Re-read SIP.conf config file
21520 \note This function reloads all config data, except for
21521 active peers (with registrations). They will only
21522 change configuration data at restart, not at reload.
21523 SIP debug and recordhistory state will not change
21525 static int reload_config(enum channelreloadreason reason)
21527 struct ast_config *cfg, *ucfg;
21528 struct ast_variable *v;
21529 struct sip_peer *peer;
21530 struct sip_user *user;
21531 char *cat, *stringp, *context, *oldregcontext;
21532 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
21533 struct ast_flags dummy[2];
21534 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : CONFIG_FLAG_FILEUNCHANGED };
21535 int auto_sip_domains = FALSE;
21536 struct sockaddr_in old_bindaddr = bindaddr;
21537 int registry_count = 0, peer_count = 0, user_count = 0;
21538 time_t run_start, run_end;
21540 run_start = time(0);
21541 ast_unload_realtime("sipregs");
21542 ast_unload_realtime("sippeers");
21543 cfg = ast_config_load(config, config_flags);
21545 /* We *must* have a config file otherwise stop immediately */
21546 if (!cfg) {
21547 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
21548 return -1;
21549 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
21550 ucfg = ast_config_load("users.conf", config_flags);
21551 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
21552 return 1;
21553 /* Must reread both files, because one changed */
21554 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
21555 cfg = ast_config_load(config, config_flags);
21556 } else {
21557 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
21558 ucfg = ast_config_load("users.conf", config_flags);
21561 /* Initialize tcp sockets */
21562 memset(&sip_tcp_desc.sin, 0, sizeof(sip_tcp_desc.sin));
21563 memset(&sip_tls_desc.sin, 0, sizeof(sip_tls_desc.sin));
21565 sip_tcp_desc.sin.sin_family = AF_INET;
21567 sip_tcp_desc.sin.sin_port = htons(STANDARD_SIP_PORT);
21568 sip_tls_desc.sin.sin_port = htons(STANDARD_TLS_PORT);
21570 if (reason != CHANNEL_MODULE_LOAD) {
21571 ast_debug(4, "--------------- SIP reload started\n");
21573 clear_realm_authentication(authl);
21574 clear_sip_domains();
21575 authl = NULL;
21577 /* First, destroy all outstanding registry calls */
21578 /* This is needed, since otherwise active registry entries will not be destroyed */
21579 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do { /* regl is locked */
21581 /* avoid a deadlock in the unlink_all call, if iterator->call's (a dialog) registry entry
21582 is this registry entry. In other words, if the dialog we are pointing to points back to
21583 us, then if we get a lock on this object, and try to UNREF it, we will deadlock, because
21584 we already ... NO. This is not the problem. */
21585 ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
21586 if (iterator->call) {
21587 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
21588 /* This will also remove references to the registry */
21589 dialog_unlink_all(iterator->call, TRUE, TRUE);
21590 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
21591 /* iterator->call = sip_destroy(iterator->call); */
21593 ASTOBJ_UNLOCK(iterator);
21595 } while(0));
21597 /* Then, actually destroy users and registry */
21598 ao2_t_ref(users, -1, "destroy users table");
21599 ast_debug(4, "--------------- Done destroying user list\n");
21600 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
21601 ast_debug(4, "--------------- Done destroying registry list\n");
21602 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, 0, "callback to mark all peers");
21603 /* reinstate the user table */
21604 users = ao2_t_container_alloc(hash_user_size, user_hash_cb, user_cmp_cb, "allocate users");
21607 /* Reset certificate handling for TLS sessions */
21608 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
21609 default_tls_cfg.cipher = ast_strdup("");
21610 default_tls_cfg.cafile = ast_strdup("");
21611 default_tls_cfg.capath = ast_strdup("");
21613 /* Initialize copy of current global_regcontext for later use in removing stale contexts */
21614 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
21615 oldregcontext = oldcontexts;
21617 /* Clear all flags before setting default values */
21618 /* Preserve debugging settings for console */
21619 sipdebug &= sip_debug_console;
21620 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
21621 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
21623 /* Reset IP addresses */
21624 memset(&bindaddr, 0, sizeof(bindaddr));
21625 memset(&stunaddr, 0, sizeof(stunaddr));
21626 memset(&internip, 0, sizeof(internip));
21628 /* Free memory for local network address mask */
21629 ast_free_ha(localaddr);
21630 memset(&localaddr, 0, sizeof(localaddr));
21631 memset(&externip, 0, sizeof(externip));
21632 memset(&default_prefs, 0 , sizeof(default_prefs));
21633 memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
21634 global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
21635 global_outboundproxy.ip.sin_family = AF_INET; /* Type of address: IPv4 */
21636 ourport_tcp = STANDARD_SIP_PORT;
21637 ourport_tls = STANDARD_TLS_PORT;
21638 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
21639 global_srvlookup = DEFAULT_SRVLOOKUP;
21640 global_tos_sip = DEFAULT_TOS_SIP;
21641 global_tos_audio = DEFAULT_TOS_AUDIO;
21642 global_tos_video = DEFAULT_TOS_VIDEO;
21643 global_tos_text = DEFAULT_TOS_TEXT;
21644 global_cos_sip = DEFAULT_COS_SIP;
21645 global_cos_audio = DEFAULT_COS_AUDIO;
21646 global_cos_video = DEFAULT_COS_VIDEO;
21647 global_cos_text = DEFAULT_COS_TEXT;
21649 externhost[0] = '\0'; /* External host name (for behind NAT DynDNS support) */
21650 externexpire = 0; /* Expiration for DNS re-issuing */
21651 externrefresh = 10;
21653 /* Reset channel settings to default before re-configuring */
21654 allow_external_domains = DEFAULT_ALLOW_EXT_DOM; /* Allow external invites */
21655 global_regcontext[0] = '\0';
21656 global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
21657 expiry = DEFAULT_EXPIRY;
21658 global_notifyringing = DEFAULT_NOTIFYRINGING;
21659 global_limitonpeers = FALSE; /*!< Match call limit on peers only */
21660 global_notifyhold = FALSE; /*!< Keep track of hold status for a peer */
21661 global_directrtpsetup = FALSE; /* Experimental feature, disabled by default */
21662 global_alwaysauthreject = 0;
21663 global_allowsubscribe = FALSE;
21664 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
21665 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
21666 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
21667 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
21668 ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
21669 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
21670 compactheaders = DEFAULT_COMPACTHEADERS;
21671 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
21672 global_regattempts_max = 0;
21673 pedanticsipchecking = DEFAULT_PEDANTIC;
21674 autocreatepeer = DEFAULT_AUTOCREATEPEER;
21675 global_autoframing = 0;
21676 global_allowguest = DEFAULT_ALLOWGUEST;
21677 global_callcounter = DEFAULT_CALLCOUNTER;
21678 global_match_auth_username = FALSE; /*!< Match auth username if available instead of From: Default off. */
21679 global_rtptimeout = 0;
21680 global_rtpholdtimeout = 0;
21681 global_rtpkeepalive = 0;
21682 global_allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
21683 global_rtautoclear = 120;
21684 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE); /* Default for peers, users: TRUE */
21685 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP); /* Default for peers, users: TRUE */
21686 sip_cfg.peer_rtupdate = TRUE;
21688 /* Session-Timers */
21689 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
21690 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
21691 global_min_se = DEFAULT_MIN_SE;
21692 global_max_se = DEFAULT_MAX_SE;
21694 /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
21695 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
21696 default_subscribecontext[0] = '\0';
21697 default_language[0] = '\0';
21698 default_fromdomain[0] = '\0';
21699 default_qualify = DEFAULT_QUALIFY;
21700 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
21701 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
21702 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
21703 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
21704 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833); /*!< Default DTMF setting: RFC2833 */
21705 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581); /*!< NAT support if requested by device with rport */
21706 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE); /*!< Allow re-invites */
21708 /* Debugging settings, always default to off */
21709 dumphistory = FALSE;
21710 recordhistory = FALSE;
21711 sipdebug &= ~sip_debug_config;
21713 /* Misc settings for the channel */
21714 global_relaxdtmf = FALSE;
21715 global_callevents = FALSE;
21716 global_authfailureevents = FALSE;
21717 global_t1 = SIP_TIMER_T1;
21718 global_timer_b = 64 * SIP_TIMER_T1;
21719 global_t1min = DEFAULT_T1MIN;
21720 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
21722 global_matchexterniplocally = FALSE;
21724 /* Copy the default jb config over global_jbconf */
21725 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
21727 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
21728 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
21731 /* Read the [general] config section of sip.conf (or from realtime config) */
21732 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
21733 if (handle_common_options(&global_flags[0], &dummy[0], v))
21734 continue;
21735 /* handle jb conf */
21736 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
21737 continue;
21739 /* Create the dialogs list */
21740 if (!strcasecmp(v->name, "context")) {
21741 ast_copy_string(default_context, v->value, sizeof(default_context));
21742 } else if (!strcasecmp(v->name, "subscribecontext")) {
21743 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
21744 } else if (!strcasecmp(v->name, "callcounter")) {
21745 global_callcounter = ast_true(v->value) ? 1 : 0;
21746 } else if (!strcasecmp(v->name, "allowguest")) {
21747 global_allowguest = ast_true(v->value) ? 1 : 0;
21748 } else if (!strcasecmp(v->name, "realm")) {
21749 ast_copy_string(global_realm, v->value, sizeof(global_realm));
21750 } else if (!strcasecmp(v->name, "useragent")) {
21751 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
21752 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
21753 } else if (!strcasecmp(v->name, "sdpsession")) {
21754 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
21755 } else if (!strcasecmp(v->name, "sdpowner")) {
21756 /* Field cannot contain spaces */
21757 if (!strstr(v->value, " "))
21758 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
21759 else
21760 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
21761 } else if (!strcasecmp(v->name, "allowtransfer")) {
21762 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
21763 } else if (!strcasecmp(v->name, "rtcachefriends")) {
21764 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
21765 } else if (!strcasecmp(v->name, "rtsavesysname")) {
21766 sip_cfg.rtsave_sysname = ast_true(v->value);
21767 } else if (!strcasecmp(v->name, "rtupdate")) {
21768 sip_cfg.peer_rtupdate = ast_true(v->value);
21769 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
21770 sip_cfg.ignore_regexpire = ast_true(v->value);
21771 } else if (!strcasecmp(v->name, "t1min")) {
21772 global_t1min = atoi(v->value);
21773 } else if (!strcasecmp(v->name, "tcpenable")) {
21774 sip_tcp_desc.sin.sin_family = ast_false(v->value) ? 0 : AF_INET;
21775 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
21776 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.sin))
21777 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
21778 } else if (!strcasecmp(v->name, "tlsenable")) {
21779 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
21780 sip_tls_desc.sin.sin_family = AF_INET;
21781 } else if (!strcasecmp(v->name, "tlscertfile")) {
21782 ast_free(default_tls_cfg.certfile);
21783 default_tls_cfg.certfile = ast_strdup(v->value);
21784 } else if (!strcasecmp(v->name, "tlscipher")) {
21785 ast_free(default_tls_cfg.cipher);
21786 default_tls_cfg.cipher = ast_strdup(v->value);
21787 } else if (!strcasecmp(v->name, "tlscafile")) {
21788 ast_free(default_tls_cfg.cafile);
21789 default_tls_cfg.cafile = ast_strdup(v->value);
21790 } else if (!strcasecmp(v->name, "tlscapath")) {
21791 ast_free(default_tls_cfg.capath);
21792 default_tls_cfg.capath = ast_strdup(v->value);
21793 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
21794 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
21795 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
21796 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
21797 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
21798 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.sin))
21799 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
21800 } else if (!strcasecmp(v->name, "rtautoclear")) {
21801 int i = atoi(v->value);
21802 if (i > 0)
21803 global_rtautoclear = i;
21804 else
21805 i = 0;
21806 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
21807 } else if (!strcasecmp(v->name, "usereqphone")) {
21808 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
21809 } else if (!strcasecmp(v->name, "relaxdtmf")) {
21810 global_relaxdtmf = ast_true(v->value);
21811 } else if (!strcasecmp(v->name, "vmexten")) {
21812 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
21813 } else if (!strcasecmp(v->name, "rtptimeout")) {
21814 if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
21815 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
21816 global_rtptimeout = 0;
21818 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
21819 if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
21820 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
21821 global_rtpholdtimeout = 0;
21823 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
21824 if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
21825 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
21826 global_rtpkeepalive = 0;
21828 } else if (!strcasecmp(v->name, "compactheaders")) {
21829 compactheaders = ast_true(v->value);
21830 } else if (!strcasecmp(v->name, "notifymimetype")) {
21831 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
21832 } else if (!strncasecmp(v->name, "limitonpeer", 11) || !strcasecmp(v->name, "counteronpeer")) {
21833 global_limitonpeers = ast_true(v->value);
21834 } else if (!strcasecmp(v->name, "directrtpsetup")) {
21835 global_directrtpsetup = ast_true(v->value);
21836 } else if (!strcasecmp(v->name, "notifyringing")) {
21837 global_notifyringing = ast_true(v->value);
21838 } else if (!strcasecmp(v->name, "notifyhold")) {
21839 global_notifyhold = ast_true(v->value);
21840 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
21841 global_alwaysauthreject = ast_true(v->value);
21842 } else if (!strcasecmp(v->name, "mohinterpret")) {
21843 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
21844 } else if (!strcasecmp(v->name, "mohsuggest")) {
21845 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
21846 } else if (!strcasecmp(v->name, "language")) {
21847 ast_copy_string(default_language, v->value, sizeof(default_language));
21848 } else if (!strcasecmp(v->name, "regcontext")) {
21849 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
21850 stringp = newcontexts;
21851 /* Let's remove any contexts that are no longer defined in regcontext */
21852 cleanup_stale_contexts(stringp, oldregcontext);
21853 /* Create contexts if they don't exist already */
21854 while ((context = strsep(&stringp, "&"))) {
21855 ast_copy_string(used_context, context, sizeof(used_context));
21856 ast_context_find_or_create(NULL, NULL, context, "SIP");
21858 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
21859 } else if (!strcasecmp(v->name, "regextenonqualify")) {
21860 global_regextenonqualify = ast_true(v->value);
21861 } else if (!strcasecmp(v->name, "callerid")) {
21862 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
21863 } else if (!strcasecmp(v->name, "fromdomain")) {
21864 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
21865 } else if (!strcasecmp(v->name, "outboundproxy")) {
21866 char *name, *port = NULL, *force;
21868 name = ast_strdupa(v->value);
21869 if ((port = strchr(name, ':'))) {
21870 *port++ = '\0';
21871 global_outboundproxy.ip.sin_port = htons(atoi(port));
21874 if ((force = strchr(port ? port : name, ','))) {
21875 *force++ = '\0';
21876 global_outboundproxy.force = (!strcasecmp(force, "force"));
21878 ast_copy_string(global_outboundproxy.name, name, sizeof(global_outboundproxy.name));
21879 proxy_update(&global_outboundproxy);
21881 } else if (!strcasecmp(v->name, "autocreatepeer")) {
21882 autocreatepeer = ast_true(v->value);
21883 } else if (!strcasecmp(v->name, "match_auth_username")) {
21884 global_match_auth_username = ast_true(v->value);
21885 } else if (!strcasecmp(v->name, "srvlookup")) {
21886 global_srvlookup = ast_true(v->value);
21887 } else if (!strcasecmp(v->name, "pedantic")) {
21888 pedanticsipchecking = ast_true(v->value);
21889 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
21890 max_expiry = atoi(v->value);
21891 if (max_expiry < 1)
21892 max_expiry = DEFAULT_MAX_EXPIRY;
21893 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
21894 min_expiry = atoi(v->value);
21895 if (min_expiry < 1)
21896 min_expiry = DEFAULT_MIN_EXPIRY;
21897 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
21898 default_expiry = atoi(v->value);
21899 if (default_expiry < 1)
21900 default_expiry = DEFAULT_DEFAULT_EXPIRY;
21901 } else if (!strcasecmp(v->name, "sipdebug")) {
21902 if (ast_true(v->value))
21903 sipdebug |= sip_debug_config;
21904 } else if (!strcasecmp(v->name, "dumphistory")) {
21905 dumphistory = ast_true(v->value);
21906 } else if (!strcasecmp(v->name, "recordhistory")) {
21907 recordhistory = ast_true(v->value);
21908 } else if (!strcasecmp(v->name, "registertimeout")) {
21909 global_reg_timeout = atoi(v->value);
21910 if (global_reg_timeout < 1)
21911 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
21912 } else if (!strcasecmp(v->name, "registerattempts")) {
21913 global_regattempts_max = atoi(v->value);
21914 } else if (!strcasecmp(v->name, "stunaddr")) {
21915 stunaddr.sin_port = htons(3478);
21916 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
21917 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
21918 externexpire = time(NULL);
21919 } else if (!strcasecmp(v->name, "bindaddr")) {
21920 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
21921 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
21922 } else if (!strcasecmp(v->name, "localnet")) {
21923 struct ast_ha *na;
21924 int ha_error = 0;
21926 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
21927 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
21928 else
21929 localaddr = na;
21930 if (ha_error)
21931 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
21932 } else if (!strcasecmp(v->name, "externip")) {
21933 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
21934 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
21935 externexpire = 0;
21936 /* If no port was specified use the value of bindport */
21937 if (!externip.sin_port)
21938 externip.sin_port = bindaddr.sin_port;
21939 } else if (!strcasecmp(v->name, "externhost")) {
21940 ast_copy_string(externhost, v->value, sizeof(externhost));
21941 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
21942 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
21943 externexpire = time(NULL);
21944 } else if (!strcasecmp(v->name, "externrefresh")) {
21945 if (sscanf(v->value, "%d", &externrefresh) != 1) {
21946 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
21947 externrefresh = 10;
21949 } else if (!strcasecmp(v->name, "allow")) {
21950 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
21951 if (error)
21952 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
21953 } else if (!strcasecmp(v->name, "disallow")) {
21954 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
21955 if (error)
21956 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
21957 } else if (!strcasecmp(v->name, "autoframing")) {
21958 global_autoframing = ast_true(v->value);
21959 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
21960 allow_external_domains = ast_true(v->value);
21961 } else if (!strcasecmp(v->name, "autodomain")) {
21962 auto_sip_domains = ast_true(v->value);
21963 } else if (!strcasecmp(v->name, "domain")) {
21964 char *domain = ast_strdupa(v->value);
21965 char *context = strchr(domain, ',');
21967 if (context)
21968 *context++ = '\0';
21970 if (ast_strlen_zero(context))
21971 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
21972 if (ast_strlen_zero(domain))
21973 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
21974 else
21975 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
21976 } else if (!strcasecmp(v->name, "register")) {
21977 if (sip_register(v->value, v->lineno) == 0)
21978 registry_count++;
21979 } else if (!strcasecmp(v->name, "tos_sip")) {
21980 if (ast_str2tos(v->value, &global_tos_sip))
21981 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
21982 } else if (!strcasecmp(v->name, "tos_audio")) {
21983 if (ast_str2tos(v->value, &global_tos_audio))
21984 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
21985 } else if (!strcasecmp(v->name, "tos_video")) {
21986 if (ast_str2tos(v->value, &global_tos_video))
21987 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
21988 } else if (!strcasecmp(v->name, "tos_text")) {
21989 if (ast_str2tos(v->value, &global_tos_text))
21990 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
21991 } else if (!strcasecmp(v->name, "cos_sip")) {
21992 if (ast_str2cos(v->value, &global_cos_sip))
21993 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
21994 } else if (!strcasecmp(v->name, "cos_audio")) {
21995 if (ast_str2cos(v->value, &global_cos_audio))
21996 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
21997 } else if (!strcasecmp(v->name, "cos_video")) {
21998 if (ast_str2cos(v->value, &global_cos_video))
21999 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
22000 } else if (!strcasecmp(v->name, "cos_text")) {
22001 if (ast_str2cos(v->value, &global_cos_text))
22002 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
22003 } else if (!strcasecmp(v->name, "bindport")) {
22004 int i;
22005 if (sscanf(v->value, "%d", &i) == 1) {
22006 bindaddr.sin_port = htons(i);
22007 } else {
22008 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
22010 } else if (!strcasecmp(v->name, "hash_user")) {
22011 int i;
22012 if (sscanf(v->value, "%d", &i) == 1 && i > 2) {
22013 hash_user_size = i;
22014 } else {
22015 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);
22017 } else if (!strcasecmp(v->name, "hash_peer")) {
22018 int i;
22019 if (sscanf(v->value, "%d", &i) == 1 && i > 2) {
22020 hash_peer_size = i;
22021 } else {
22022 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);
22024 } else if (!strcasecmp(v->name, "hash_dialog")) {
22025 int i;
22026 if (sscanf(v->value, "%d", &i) == 1 && i > 2) {
22027 hash_dialog_size = i;
22028 } else {
22029 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);
22031 } else if (!strcasecmp(v->name, "qualify")) {
22032 if (!strcasecmp(v->value, "no")) {
22033 default_qualify = 0;
22034 } else if (!strcasecmp(v->value, "yes")) {
22035 default_qualify = DEFAULT_MAXMS;
22036 } else if (sscanf(v->value, "%d", &default_qualify) != 1) {
22037 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
22038 default_qualify = 0;
22040 } else if (!strcasecmp(v->name, "qualifyfreq")) {
22041 int i;
22042 if (sscanf(v->value, "%d", &i) == 1)
22043 global_qualifyfreq = i * 1000;
22044 else {
22045 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
22046 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
22048 } else if (!strcasecmp(v->name, "callevents")) {
22049 global_callevents = ast_true(v->value);
22050 } else if (!strcasecmp(v->name, "authfailureevents")) {
22051 global_authfailureevents = ast_true(v->value);
22052 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
22053 default_maxcallbitrate = atoi(v->value);
22054 if (default_maxcallbitrate < 0)
22055 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
22056 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
22057 global_matchexterniplocally = ast_true(v->value);
22058 } else if (!strcasecmp(v->name, "session-timers")) {
22059 int i = (int) str2stmode(v->value);
22060 if (i < 0) {
22061 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
22062 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
22063 } else {
22064 global_st_mode = i;
22066 } else if (!strcasecmp(v->name, "session-expires")) {
22067 if (sscanf(v->value, "%d", &global_max_se) != 1) {
22068 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
22069 global_max_se = DEFAULT_MAX_SE;
22071 } else if (!strcasecmp(v->name, "session-minse")) {
22072 if (sscanf(v->value, "%d", &global_min_se) != 1) {
22073 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
22074 global_min_se = DEFAULT_MIN_SE;
22076 if (global_min_se < 90) {
22077 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);
22078 global_min_se = DEFAULT_MIN_SE;
22080 } else if (!strcasecmp(v->name, "session-refresher")) {
22081 int i = (int) str2strefresher(v->value);
22082 if (i < 0) {
22083 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
22084 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
22085 } else {
22086 global_st_refresher = i;
22091 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
22092 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
22093 allow_external_domains = 1;
22096 /* Build list of authentication to various SIP realms, i.e. service providers */
22097 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
22098 /* Format for authentication is auth = username:password@realm */
22099 if (!strcasecmp(v->name, "auth"))
22100 authl = add_realm_authentication(authl, v->value, v->lineno);
22103 if (ucfg) {
22104 struct ast_variable *gen;
22105 int genhassip, genregistersip;
22106 const char *hassip, *registersip;
22108 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
22109 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
22110 gen = ast_variable_browse(ucfg, "general");
22111 cat = ast_category_browse(ucfg, NULL);
22112 while (cat) {
22113 if (strcasecmp(cat, "general")) {
22114 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
22115 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
22116 if (ast_true(hassip) || (!hassip && genhassip)) {
22117 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
22118 if (user) {
22119 ao2_t_link(users, user, "link user into users table");
22120 unref_user(user, "Unref the result of build_user. Now, the table link is the only one left.");
22121 user_count++;
22123 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
22124 if (peer) {
22125 ao2_t_link(peers, peer, "link peer into peer table");
22126 if (peer->addr.sin_addr.s_addr) {
22127 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
22130 unref_peer(peer, "unref_peer: from reload_config");
22131 peer_count++;
22134 if (ast_true(registersip) || (!registersip && genregistersip)) {
22135 char tmp[256];
22136 const char *host = ast_variable_retrieve(ucfg, cat, "host");
22137 const char *username = ast_variable_retrieve(ucfg, cat, "username");
22138 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
22139 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
22140 if (!host)
22141 host = ast_variable_retrieve(ucfg, "general", "host");
22142 if (!username)
22143 username = ast_variable_retrieve(ucfg, "general", "username");
22144 if (!secret)
22145 secret = ast_variable_retrieve(ucfg, "general", "secret");
22146 if (!contact)
22147 contact = "s";
22148 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
22149 if (!ast_strlen_zero(secret))
22150 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
22151 else
22152 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
22153 if (sip_register(tmp, 0) == 0)
22154 registry_count++;
22158 cat = ast_category_browse(ucfg, cat);
22160 ast_config_destroy(ucfg);
22164 /* Load peers, users and friends */
22165 cat = NULL;
22166 while ( (cat = ast_category_browse(cfg, cat)) ) {
22167 const char *utype;
22168 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
22169 continue;
22170 utype = ast_variable_retrieve(cfg, cat, "type");
22171 if (!utype) {
22172 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
22173 continue;
22174 } else {
22175 int is_user = 0, is_peer = 0;
22176 if (!strcasecmp(utype, "user"))
22177 is_user = 1;
22178 else if (!strcasecmp(utype, "friend"))
22179 is_user = is_peer = 1;
22180 else if (!strcasecmp(utype, "peer"))
22181 is_peer = 1;
22182 else {
22183 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
22184 continue;
22186 if (is_user) {
22187 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
22188 if (user) {
22189 ao2_t_link(users, user, "link user into users table");
22190 unref_user(user, "Unref the result of build_user. Now, the table link is the only one left.");
22191 user_count++;
22194 if (is_peer) {
22195 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
22196 if (peer) {
22197 ao2_t_link(peers, peer, "link peer into peers table");
22198 if (peer->addr.sin_addr.s_addr) {
22199 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
22201 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
22202 peer_count++;
22208 bindaddr.sin_family = AF_INET;
22209 internip = bindaddr;
22210 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
22211 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
22212 ast_config_destroy(cfg);
22213 return 0;
22215 ast_mutex_lock(&netlock);
22216 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
22217 close(sipsock);
22218 sipsock = -1;
22220 if (sipsock < 0) {
22221 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
22222 if (sipsock < 0) {
22223 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
22224 ast_config_destroy(cfg);
22225 return -1;
22226 } else {
22227 /* Allow SIP clients on the same host to access us: */
22228 const int reuseFlag = 1;
22230 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
22231 (const char*)&reuseFlag,
22232 sizeof reuseFlag);
22234 ast_enable_packet_fragmentation(sipsock);
22236 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
22237 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
22238 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
22239 strerror(errno));
22240 close(sipsock);
22241 sipsock = -1;
22242 } else {
22243 ast_verb(2, "SIP Listening on %s:%d\n",
22244 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
22245 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
22249 if (stunaddr.sin_addr.s_addr != 0) {
22250 ast_debug(1, "stun to %s:%d\n",
22251 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
22252 ast_stun_request(sipsock, &stunaddr,
22253 NULL, &externip);
22254 ast_debug(1, "STUN sees us at %s:%d\n",
22255 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
22257 ast_mutex_unlock(&netlock);
22259 /* Add default domains - host name, IP address and IP:port
22260 * Only do this if user added any sip domain with "localdomains"
22261 * In order to *not* break backwards compatibility
22262 * Some phones address us at IP only, some with additional port number
22264 if (auto_sip_domains) {
22265 char temp[MAXHOSTNAMELEN];
22267 /* First our default IP address */
22268 if (bindaddr.sin_addr.s_addr)
22269 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
22270 else
22271 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
22273 /* Our extern IP address, if configured */
22274 if (externip.sin_addr.s_addr)
22275 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
22277 /* Extern host name (NAT traversal support) */
22278 if (!ast_strlen_zero(externhost))
22279 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
22281 /* Our host name */
22282 if (!gethostname(temp, sizeof(temp)))
22283 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
22286 /* Release configuration from memory */
22287 ast_config_destroy(cfg);
22289 /* Load the list of manual NOTIFY types to support */
22290 if (notify_types)
22291 ast_config_destroy(notify_types);
22292 notify_types = ast_config_load(notify_config, config_flags);
22294 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
22295 ast_tcptls_server_start(&sip_tcp_desc);
22297 if (ast_ssl_setup(sip_tls_desc.tls_cfg))
22298 ast_tcptls_server_start(&sip_tls_desc);
22299 else if (sip_tls_desc.tls_cfg->enabled) {
22300 sip_tls_desc.tls_cfg = NULL;
22301 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
22304 /* Done, tell the manager */
22305 manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\nUser_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count, user_count);
22306 run_end = time(0);
22307 ast_debug(4, "reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
22309 return 0;
22312 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
22314 struct sip_pvt *p;
22315 struct ast_udptl *udptl = NULL;
22317 p = chan->tech_pvt;
22318 if (!p)
22319 return NULL;
22321 sip_pvt_lock(p);
22322 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
22323 udptl = p->udptl;
22324 sip_pvt_unlock(p);
22325 return udptl;
22328 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
22330 struct sip_pvt *p;
22332 p = chan->tech_pvt;
22333 if (!p)
22334 return -1;
22335 sip_pvt_lock(p);
22336 if (udptl)
22337 ast_udptl_get_peer(udptl, &p->udptlredirip);
22338 else
22339 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
22340 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
22341 if (!p->pendinginvite) {
22342 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);
22343 transmit_reinvite_with_sdp(p, TRUE, FALSE);
22344 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
22345 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);
22346 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
22349 /* Reset lastrtprx timer */
22350 p->lastrtprx = p->lastrtptx = time(NULL);
22351 sip_pvt_unlock(p);
22352 return 0;
22355 /*! \brief Handle T38 reinvite
22356 \todo Make sure we don't destroy the call if we can't handle the re-invite.
22357 Nothing should be changed until we have processed the SDP and know that we
22358 can handle it.
22360 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
22362 struct sip_pvt *p;
22363 int flag = 0;
22365 p = chan->tech_pvt;
22366 if (!p || !pvt->udptl)
22367 return -1;
22369 /* Setup everything on the other side like offered/responded from first side */
22370 sip_pvt_lock(p);
22372 /*! \todo check if this is not set earlier when setting up the PVT. If not
22373 maybe it should move there. */
22374 p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;
22376 ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
22377 ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
22378 ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
22380 if (reinvite) { /* If we are handling sending re-invite to the other side of the bridge */
22381 /*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
22382 not really T38 re-invites which are different. In this
22383 case it's used properly, to see if we can reinvite over
22384 NAT
22386 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
22387 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
22388 flag =1;
22389 } else {
22390 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
22392 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
22393 if (!p->pendinginvite) {
22394 if (flag)
22395 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));
22396 else
22397 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));
22398 change_t38_state(p, T38_LOCAL_REINVITE);
22399 transmit_reinvite_with_sdp(p, TRUE, FALSE);
22400 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
22401 if (flag)
22402 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));
22403 else
22404 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));
22405 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
22408 /* Reset lastrtprx timer */
22409 p->lastrtprx = p->lastrtptx = time(NULL);
22410 sip_pvt_unlock(p);
22411 return 0;
22412 } else { /* If we are handling sending 200 OK to the other side of the bridge */
22413 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
22414 ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
22415 flag = 1;
22416 } else {
22417 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
22419 if (flag)
22420 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));
22421 else
22422 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));
22423 change_t38_state(pvt, T38_ENABLED);
22424 change_t38_state(p, T38_ENABLED);
22425 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
22426 p->lastrtprx = p->lastrtptx = time(NULL);
22427 sip_pvt_unlock(p);
22428 return 0;
22433 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
22434 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
22436 struct sip_pvt *p = NULL;
22437 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
22439 if (!(p = chan->tech_pvt))
22440 return AST_RTP_GET_FAILED;
22442 sip_pvt_lock(p);
22443 if (!(p->rtp)) {
22444 sip_pvt_unlock(p);
22445 return AST_RTP_GET_FAILED;
22448 *rtp = p->rtp;
22450 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
22451 res = AST_RTP_TRY_PARTIAL;
22452 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
22453 res = AST_RTP_TRY_NATIVE;
22454 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
22455 res = AST_RTP_GET_FAILED;
22457 sip_pvt_unlock(p);
22459 return res;
22462 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
22463 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
22465 struct sip_pvt *p = NULL;
22466 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
22468 if (!(p = chan->tech_pvt))
22469 return AST_RTP_GET_FAILED;
22471 sip_pvt_lock(p);
22472 if (!(p->vrtp)) {
22473 sip_pvt_unlock(p);
22474 return AST_RTP_GET_FAILED;
22477 *rtp = p->vrtp;
22479 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
22480 res = AST_RTP_TRY_NATIVE;
22482 sip_pvt_unlock(p);
22484 return res;
22487 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
22488 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
22490 struct sip_pvt *p = NULL;
22491 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
22493 if (!(p = chan->tech_pvt))
22494 return AST_RTP_GET_FAILED;
22496 sip_pvt_lock(p);
22497 if (!(p->trtp)) {
22498 sip_pvt_unlock(p);
22499 return AST_RTP_GET_FAILED;
22502 *rtp = p->trtp;
22504 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
22505 res = AST_RTP_TRY_NATIVE;
22507 sip_pvt_unlock(p);
22509 return res;
22512 /*! \brief Set the RTP peer for this call */
22513 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)
22515 struct sip_pvt *p;
22516 int changed = 0;
22518 p = chan->tech_pvt;
22519 if (!p)
22520 return -1;
22522 /* Disable early RTP bridge */
22523 if (chan->_state != AST_STATE_UP && !global_directrtpsetup) /* We are in early state */
22524 return 0;
22526 sip_pvt_lock(p);
22527 if (p->alreadygone) {
22528 /* If we're destroyed, don't bother */
22529 sip_pvt_unlock(p);
22530 return 0;
22533 /* if this peer cannot handle reinvites of the media stream to devices
22534 that are known to be behind a NAT, then stop the process now
22536 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
22537 sip_pvt_unlock(p);
22538 return 0;
22541 if (rtp) {
22542 changed |= ast_rtp_get_peer(rtp, &p->redirip);
22543 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
22544 memset(&p->redirip, 0, sizeof(p->redirip));
22545 changed = 1;
22547 if (vrtp) {
22548 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
22549 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
22550 memset(&p->vredirip, 0, sizeof(p->vredirip));
22551 changed = 1;
22553 if (trtp) {
22554 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
22555 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
22556 memset(&p->tredirip, 0, sizeof(p->tredirip));
22557 changed = 1;
22559 if (codecs && (p->redircodecs != codecs)) {
22560 p->redircodecs = codecs;
22561 changed = 1;
22563 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
22564 if (chan->_state != AST_STATE_UP) { /* We are in early state */
22565 if (p->do_history)
22566 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
22567 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));
22568 } else if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
22569 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));
22570 transmit_reinvite_with_sdp(p, FALSE, FALSE);
22571 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
22572 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));
22573 /* We have a pending Invite. Send re-invite when we're done with the invite */
22574 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
22577 /* Reset lastrtprx timer */
22578 p->lastrtprx = p->lastrtptx = time(NULL);
22579 sip_pvt_unlock(p);
22580 return 0;
22583 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
22584 static char *descrip_dtmfmode = " SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
22585 static char *app_dtmfmode = "SIPDtmfMode";
22587 static char *app_sipaddheader = "SIPAddHeader";
22588 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
22590 static char *descrip_sipaddheader = ""
22591 " SIPAddHeader(Header: Content):\n"
22592 "Adds a header to a SIP call placed with DIAL.\n"
22593 "Remember to user the X-header if you are adding non-standard SIP\n"
22594 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
22595 "Adding the wrong headers may jeopardize the SIP dialog.\n"
22596 "Always returns 0\n";
22599 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
22600 static int sip_dtmfmode(struct ast_channel *chan, void *data)
22602 struct sip_pvt *p;
22603 char *mode = data;
22605 if (!data) {
22606 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
22607 return 0;
22609 ast_channel_lock(chan);
22610 if (!IS_SIP_TECH(chan->tech)) {
22611 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
22612 ast_channel_unlock(chan);
22613 return 0;
22615 p = chan->tech_pvt;
22616 if (!p) {
22617 ast_channel_unlock(chan);
22618 return 0;
22620 sip_pvt_lock(p);
22621 if (!strcasecmp(mode, "info")) {
22622 ast_clear_flag(&p->flags[0], SIP_DTMF);
22623 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
22624 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
22625 } else if (!strcasecmp(mode, "shortinfo")) {
22626 ast_clear_flag(&p->flags[0], SIP_DTMF);
22627 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
22628 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
22629 } else if (!strcasecmp(mode, "rfc2833")) {
22630 ast_clear_flag(&p->flags[0], SIP_DTMF);
22631 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
22632 p->jointnoncodeccapability |= AST_RTP_DTMF;
22633 } else if (!strcasecmp(mode, "inband")) {
22634 ast_clear_flag(&p->flags[0], SIP_DTMF);
22635 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
22636 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
22637 } else
22638 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
22639 if (p->rtp)
22640 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
22641 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
22642 if (!p->vad) {
22643 p->vad = ast_dsp_new();
22644 ast_dsp_set_features(p->vad, DSP_FEATURE_DIGIT_DETECT);
22646 } else {
22647 if (p->vad) {
22648 ast_dsp_free(p->vad);
22649 p->vad = NULL;
22652 sip_pvt_unlock(p);
22653 ast_channel_unlock(chan);
22654 return 0;
22657 /*! \brief Add a SIP header to an outbound INVITE */
22658 static int sip_addheader(struct ast_channel *chan, void *data)
22660 int no = 0;
22661 int ok = FALSE;
22662 char varbuf[30];
22663 char *inbuf = data;
22665 if (ast_strlen_zero(inbuf)) {
22666 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
22667 return 0;
22669 ast_channel_lock(chan);
22671 /* Check for headers */
22672 while (!ok && no <= 50) {
22673 no++;
22674 snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);
22676 /* Compare without the leading underscore */
22677 if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
22678 ok = TRUE;
22680 if (ok) {
22681 pbx_builtin_setvar_helper (chan, varbuf, inbuf);
22682 if (sipdebug)
22683 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
22684 } else {
22685 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
22687 ast_channel_unlock(chan);
22688 return 0;
22691 /*! \brief Transfer call before connect with a 302 redirect
22692 \note Called by the transfer() dialplan application through the sip_transfer()
22693 pbx interface function if the call is in ringing state
22694 \todo Fix this function so that we wait for reply to the REFER and
22695 react to errors, denials or other issues the other end might have.
22697 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
22699 char *cdest;
22700 char *extension, *host, *port;
22701 char tmp[80];
22703 cdest = ast_strdupa(dest);
22705 extension = strsep(&cdest, "@");
22706 host = strsep(&cdest, ":");
22707 port = strsep(&cdest, ":");
22708 if (ast_strlen_zero(extension)) {
22709 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
22710 return 0;
22713 /* we'll issue the redirect message here */
22714 if (!host) {
22715 char *localtmp;
22717 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
22718 if (ast_strlen_zero(tmp)) {
22719 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
22720 return 0;
22722 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
22723 && (localtmp = strchr(localtmp, '@'))) {
22724 char lhost[80], lport[80];
22726 memset(lhost, 0, sizeof(lhost));
22727 memset(lport, 0, sizeof(lport));
22728 localtmp++;
22729 /* This is okey because lhost and lport are as big as tmp */
22730 sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
22731 if (ast_strlen_zero(lhost)) {
22732 ast_log(LOG_ERROR, "Can't find the host address\n");
22733 return 0;
22735 host = ast_strdupa(lhost);
22736 if (!ast_strlen_zero(lport)) {
22737 port = ast_strdupa(lport);
22742 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
22743 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
22745 sip_scheddestroy(p, SIP_TRANS_TIMEOUT); /* Make sure we stop send this reply. */
22746 sip_alreadygone(p);
22747 /* hangup here */
22748 return 0;
22751 /*! \brief Return SIP UA's codec (part of the RTP interface) */
22752 static int sip_get_codec(struct ast_channel *chan)
22754 struct sip_pvt *p = chan->tech_pvt;
22755 return p->peercapability ? p->peercapability : p->capability;
22758 /*! \brief Send a poke to all known peers
22759 Space them out 100 ms apart
22760 XXX We might have a cool algorithm for this or use random - any suggestions?
22762 static void sip_poke_all_peers(void)
22764 int ms = 0;
22765 struct ao2_iterator i;
22766 struct sip_peer *peer;
22768 i = ao2_iterator_init(peers, 0);
22770 if (!speerobjs) /* No peers, just give up */
22771 return;
22773 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
22774 ao2_lock(peer);
22775 ms += 100;
22776 AST_SCHED_REPLACE(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer);
22777 ao2_unlock(peer);
22778 unref_peer(peer, "toss iterator peer ptr");
22782 /*! \brief Send all known registrations */
22783 static void sip_send_all_registers(void)
22785 int ms;
22786 int regspacing;
22787 if (!regobjs)
22788 return;
22789 regspacing = default_expiry * 1000/regobjs;
22790 if (regspacing > 100)
22791 regspacing = 100;
22792 ms = regspacing;
22793 ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
22794 ASTOBJ_WRLOCK(iterator);
22795 ms += regspacing;
22796 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
22797 registry_unref(_data, "REPLACE sched del decs the refcount"),
22798 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
22799 registry_addref(iterator, "REPLACE sched add incs the refcount"));
22800 ASTOBJ_UNLOCK(iterator);
22801 } while (0)
22805 /*! \brief Reload module */
22806 static int sip_do_reload(enum channelreloadreason reason)
22808 time_t start_poke, end_poke;
22810 reload_config(reason);
22811 ast_sched_dump(sched);
22813 start_poke = time(0);
22814 /* Prune peers who still are supposed to be deleted */
22815 ao2_t_callback(peers, OBJ_NODATA|OBJ_UNLINK, peer_is_marked, 0, "callback to remove marked peers");
22817 ast_debug(4, "--------------- Done destroying pruned peers\n");
22819 /* Send qualify (OPTIONS) to all peers */
22820 sip_poke_all_peers();
22822 /* Register with all services */
22823 sip_send_all_registers();
22824 end_poke = time(0);
22826 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
22828 ast_debug(4, "--------------- SIP reload done\n");
22830 return 0;
22833 /*! \brief Force reload of module from cli */
22834 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
22837 switch (cmd) {
22838 case CLI_INIT:
22839 e->command = "sip reload";
22840 e->usage =
22841 "Usage: sip reload\n"
22842 " Reloads SIP configuration from sip.conf\n";
22843 return NULL;
22844 case CLI_GENERATE:
22845 return NULL;
22848 ast_mutex_lock(&sip_reload_lock);
22849 if (sip_reloading)
22850 ast_verbose("Previous SIP reload not yet done\n");
22851 else {
22852 sip_reloading = TRUE;
22853 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
22855 ast_mutex_unlock(&sip_reload_lock);
22856 restart_monitor();
22858 return CLI_SUCCESS;
22861 /*! \brief Part of Asterisk module interface */
22862 static int reload(void)
22864 if (sip_reload(0, 0, NULL))
22865 return 0;
22866 return 1;
22869 static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
22870 /*! \brief SIP Cli commands definition */
22871 static struct ast_cli_entry cli_sip[] = {
22872 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels/subscriptions"),
22873 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains."),
22874 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
22875 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
22876 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
22877 AST_CLI_DEFINE(sip_dbdump, "dump peer info into realtime db sql format"),
22878 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
22879 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registery\n"),
22880 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
22881 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
22882 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
22883 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
22884 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
22885 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
22886 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
22887 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
22888 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
22889 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
22890 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
22891 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
22892 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
22893 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
22896 /*! \brief PBX load module - initialization */
22897 static int load_module(void)
22899 ast_verbose("SIP channel loading...\n");
22900 /* the fact that ao2_containers can't resize automatically is a major worry! */
22901 /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
22902 users = ao2_t_container_alloc(hash_user_size, user_hash_cb, user_cmp_cb, "allocate users");
22903 peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
22904 peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
22905 dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
22907 ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
22909 if (!(sched = sched_context_create())) {
22910 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
22911 return AST_MODULE_LOAD_FAILURE;
22914 if (!(io = io_context_create())) {
22915 ast_log(LOG_ERROR, "Unable to create I/O context\n");
22916 sched_context_destroy(sched);
22917 return AST_MODULE_LOAD_FAILURE;
22920 sip_reloadreason = CHANNEL_MODULE_LOAD;
22922 if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
22923 return AST_MODULE_LOAD_DECLINE;
22925 /* Prepare the version that does not require DTMF BEGIN frames.
22926 * We need to use tricks such as memcpy and casts because the variable
22927 * has const fields.
22929 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
22930 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
22932 /* Make sure we can register our sip channel type */
22933 if (ast_channel_register(&sip_tech)) {
22934 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
22935 io_context_destroy(io);
22936 sched_context_destroy(sched);
22937 return AST_MODULE_LOAD_FAILURE;
22940 /* Register all CLI functions for SIP */
22941 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
22943 /* Tell the RTP subdriver that we're here */
22944 ast_rtp_proto_register(&sip_rtp);
22946 /* Tell the UDPTL subdriver that we're here */
22947 ast_udptl_proto_register(&sip_udptl);
22949 /* Register dialplan applications */
22950 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
22951 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
22953 /* Register dialplan functions */
22954 ast_custom_function_register(&sip_header_function);
22955 ast_custom_function_register(&sippeer_function);
22956 ast_custom_function_register(&sipchaninfo_function);
22957 ast_custom_function_register(&checksipdomain_function);
22959 /* Register manager commands */
22960 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
22961 "List SIP peers (text format)", mandescr_show_peers);
22962 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
22963 "Show SIP peer (text format)", mandescr_show_peer);
22964 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
22965 "Show SIP peer (text format)", mandescr_show_peer);
22966 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
22967 "Show SIP registrations (text format)", mandescr_show_registry);
22968 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
22969 "Send a SIP notify", mandescr_sipnotify);
22970 sip_poke_all_peers();
22971 sip_send_all_registers();
22973 /* And start the monitor for the first time */
22974 restart_monitor();
22976 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
22977 "name", RQ_CHAR, 10,
22978 "ipaddr", RQ_CHAR, 15,
22979 "port", RQ_UINTEGER2, 5,
22980 "regseconds", RQ_UINTEGER2, 5, /* Max of 18 hours */
22981 "defaultuser", RQ_CHAR, 10,
22982 "fullcontact", RQ_CHAR, 20,
22983 "regserver", RQ_CHAR, 20,
22984 "useragent", RQ_CHAR, 20,
22985 NULL);
22987 return AST_MODULE_LOAD_SUCCESS;
22990 /*! \brief PBX unload module API */
22991 static int unload_module(void)
22993 struct sip_pvt *p;
22994 struct sip_threadinfo *th;
22995 struct ast_context *con;
22996 struct ao2_iterator i;
22998 ast_sched_dump(sched);
23000 /* First, take us out of the channel type list */
23001 ast_channel_unregister(&sip_tech);
23003 /* Unregister dial plan functions */
23004 ast_custom_function_unregister(&sipchaninfo_function);
23005 ast_custom_function_unregister(&sippeer_function);
23006 ast_custom_function_unregister(&sip_header_function);
23007 ast_custom_function_unregister(&checksipdomain_function);
23009 /* Unregister dial plan applications */
23010 ast_unregister_application(app_dtmfmode);
23011 ast_unregister_application(app_sipaddheader);
23013 /* Unregister CLI commands */
23014 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
23016 /* Disconnect from the RTP subsystem */
23017 ast_rtp_proto_unregister(&sip_rtp);
23019 /* Disconnect from UDPTL */
23020 ast_udptl_proto_unregister(&sip_udptl);
23022 /* Unregister AMI actions */
23023 ast_manager_unregister("SIPpeers");
23024 ast_manager_unregister("SIPshowpeer");
23025 ast_manager_unregister("SIPqualifypeer");
23026 ast_manager_unregister("SIPshowregistry");
23027 ast_manager_unregister("SIPnotify");
23029 /* Kill TCP/TLS server threads */
23030 if (sip_tcp_desc.master)
23031 ast_tcptls_server_stop(&sip_tcp_desc);
23032 if (sip_tls_desc.master)
23033 ast_tcptls_server_stop(&sip_tls_desc);
23035 /* Kill all existing TCP/TLS threads */
23036 AST_LIST_LOCK(&threadl);
23037 AST_LIST_TRAVERSE_SAFE_BEGIN(&threadl, th, list) {
23038 pthread_t thread = th->threadid;
23039 th->stop = 1;
23040 AST_LIST_UNLOCK(&threadl);
23041 pthread_kill(thread, SIGURG);
23042 pthread_join(thread, NULL);
23043 AST_LIST_LOCK(&threadl);
23045 AST_LIST_TRAVERSE_SAFE_END;
23046 AST_LIST_UNLOCK(&threadl);
23048 /* Hangup all dialogs if they have an owner */
23049 i = ao2_iterator_init(dialogs, 0);
23050 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
23051 if (p->owner)
23052 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
23053 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
23056 ast_mutex_lock(&monlock);
23057 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
23058 pthread_cancel(monitor_thread);
23059 pthread_kill(monitor_thread, SIGURG);
23060 pthread_join(monitor_thread, NULL);
23062 monitor_thread = AST_PTHREADT_STOP;
23063 ast_mutex_unlock(&monlock);
23065 /* Destroy all the dialogs and free their memory */
23066 i = ao2_iterator_init(dialogs, 0);
23067 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
23068 dialog_unlink_all(p, TRUE, TRUE);
23069 ao2_t_ref(p, -1, "throw away iterator result");
23072 /* Free memory for local network address mask */
23073 ast_free_ha(localaddr);
23075 clear_realm_authentication(authl);
23078 if (default_tls_cfg.certfile)
23079 ast_free(default_tls_cfg.certfile);
23080 if (default_tls_cfg.cipher)
23081 ast_free(default_tls_cfg.cipher);
23082 if (default_tls_cfg.cafile)
23083 ast_free(default_tls_cfg.cafile);
23084 if (default_tls_cfg.capath)
23085 ast_free(default_tls_cfg.capath);
23087 ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
23088 ASTOBJ_CONTAINER_DESTROY(&regl);
23090 ao2_t_ref(peers, -1, "unref the peers table");
23091 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
23092 ao2_t_ref(users, -1, "unref the users table");
23093 ao2_t_ref(dialogs, -1, "unref the dialogs table");
23095 clear_sip_domains();
23096 close(sipsock);
23097 sched_context_destroy(sched);
23098 con = ast_context_find(used_context);
23099 if (con)
23100 ast_context_destroy(con, "SIP");
23101 ast_unload_realtime("sipregs");
23102 ast_unload_realtime("sippeers");
23104 return 0;
23107 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
23108 .load = load_module,
23109 .unload = unload_module,
23110 .reload = reload,